A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
ci: licence-free golden check of released desktop players (refs #54) (#533)
Eyal Golan53a011a06dda
diff --git a/.github/workflows/player-golden.yml b/.github/workflows/player-golden.ymlnew file mode 100644index 000000000..5169fa5a9--- /dev/null+++ b/.github/workflows/player-golden.yml@@ -0,0 +1,138 @@+name: Player golden++# The licence-free golden check of the released desktop players (plan+# docs/superpowers/specs/2026-10-14-desktop-builds-and-release-pipeline.md, sections 2.2 and 6.3; decision O7 in+# docs/oss/DECISIONS.md). The players are built on the owner's Mac and attached to a GitHub Release; this workflow only+# downloads them and runs `-batchmode -nographics -golden` on clean GitHub-hosted machines (docs/determinism.md). No+# Unity install, no Unity licence and no secret: the only credential is the default token, read-only, which+# `gh release download` uses.+#+# Trust: it runs binaries, so it runs only binaries from a release of THIS repository, which only someone with write+# access can publish. It never runs on pull requests, takes no URL and no Actions artifact (a fork's pull request can+# upload artifacts here), and the manual input is a tag checked against vX.Y.Z before anything uses it. The expected+# hashes are read from the golden manifest AT THE RELEASE TAG (sim/Statecraft.Sim.Tests/golden/manifest.txt), the commit+# the players were built from, so no hash is copied here. Every action is pinned to a commit SHA+# (scripts/oss/pin_actions.py). scripts/oss/tests/test_github_config.py pins these properties.+#+# Asset names (the contract with the release script, tools/release_build.py; ASSETS in tools/player_golden_check.py):+# statecraft-israel-<tag>-windows-x64.zip Windows x64 (Mono, built on the Mac; decision O8)+# statecraft-israel-<tag>-linux-x64.tar.gz Linux x64 (tar keeps the executable bit)+# statecraft-israel-<tag>-macos-universal.zip macOS Universal (IL2CPP), the .app inside; checked twice, on macos-15+# (arm64 slice) and macos-15-intel (x86_64 slice; GitHub ends it in Aug 2027: #548)+# Each archive also carries the notices (REQUIRED_NOTICES in tools/player_golden_check.py) at its top level, beside the+# player or the .app; a missing one fails before the player runs.+# <tag> is the release tag with its v (statecraft-israel-v0.2.0-windows-x64.zip), like the web zip in docs/RELEASING.md.+# A release with desktop players must carry all three, attached in the same `gh release create` (docs/RELEASING.md,+# step 6): one or two fails the run. A release with none (web only) passes, with an UNCHECKED warning in the summary.+# Uploading or replacing an asset later fires no event: dispatch this workflow for the tag again. Each download is+# checked against the SHA-256 digest GitHub records for the asset, so a replaced asset fails until it is re-run.++on:+ release:+ types: [published]+ workflow_dispatch:+ inputs:+ tag:+ description: "Release tag of this repository to check (vX.Y.Z)"+ required: true+ type: string++permissions:+ contents: read++env:+ UV_PYTHON: "3.12"++concurrency:+ group: player-golden-${{ github.event_name == 'release' && github.ref_name || inputs.tag }}+ cancel-in-progress: false++jobs:+ plan:+ name: Player golden (find the players)+ runs-on: ubuntu-24.04+ timeout-minutes: 5+ outputs:+ tag: ${{ steps.tag.outputs.tag }}+ matrix: ${{ steps.plan.outputs.matrix }}+ count: ${{ steps.plan.outputs.count }}+ steps:+ - name: The tag, checked before anything uses it+ id: tag+ env:+ EVENT: ${{ github.event_name }}+ INPUT_TAG: ${{ inputs.tag }}+ REF_NAME: ${{ github.ref_name }}+ run: |+ if [ "$EVENT" = release ]; then tag="$REF_NAME"; else tag="$INPUT_TAG"; fi+ # The same pattern as TAG in tools/player_golden_check.py (tools/tests/test_player_golden_check.py pins them).+ re='^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z]+(\.[0-9A-Za-z]+)*)?$'+ if [[ ! $tag =~ $re ]]; then+ echo "::error::not a release tag (expected vX.Y.Z)"; exit 1+ fi+ echo "tag=$tag" >> "$GITHUB_OUTPUT"+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ sparse-checkout: tools/player_golden_check.py+ sparse-checkout-cone-mode: false+ - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0+ with:+ version: "0.12.5"+ enable-cache: false+ - name: The release's players+ id: plan+ env:+ GH_TOKEN: ${{ github.token }}+ EVENT: ${{ github.event_name }}+ TAG: ${{ steps.tag.outputs.tag }}+ run: |+ gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json tagName,isDraft,assets > "$RUNNER_TEMP/release.json"+ uv run --no-project tools/player_golden_check.py plan --tag "$TAG" --event "$EVENT" --output "$GITHUB_OUTPUT" --summary "$GITHUB_STEP_SUMMARY" < "$RUNNER_TEMP/release.json"++ golden:+ name: Player golden (${{ matrix.label }})+ needs: plan+ if: needs.plan.outputs.count != '0'+ strategy:+ fail-fast: false+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 30+ defaults:+ run:+ shell: bash+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ sparse-checkout: tools/player_golden_check.py+ sparse-checkout-cone-mode: false+ # The manifest of the commit the players were built from: the hashes the players themselves compare against.+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: refs/tags/${{ needs.plan.outputs.tag }}+ path: released+ persist-credentials: false+ sparse-checkout: sim/Statecraft.Sim.Tests/golden/manifest.txt+ sparse-checkout-cone-mode: false+ - uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v10.3.0+ with:+ version: "0.12.5"+ enable-cache: false+ - name: Download the player from the release+ env:+ GH_TOKEN: ${{ github.token }}+ TAG: ${{ needs.plan.outputs.tag }}+ ASSET: ${{ matrix.asset }}+ run: gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "$ASSET" --dir "$RUNNER_TEMP/download"+ - name: Run the player's golden check+ env:+ PLATFORM: ${{ matrix.platform }}+ ASSET: ${{ matrix.asset }}+ SHA256: ${{ matrix.sha256 }}+ ARCH: ${{ matrix.arch }}+ run: >-+ uv run --no-project tools/player_golden_check.py run --platform "$PLATFORM" ${ARCH:+--arch "$ARCH"}+ --archive "$RUNNER_TEMP/download/$ASSET" --sha256 "$SHA256" --manifest released/sim/Statecraft.Sim.Tests/golden/manifest.txt+ --work "$RUNNER_TEMP/golden" --timeout 900diff --git a/BUILDING.md b/BUILDING.mdindex 629f66b8f..92e83916f 100644--- a/BUILDING.md+++ b/BUILDING.md@@ -24,7 +24,7 @@ python3 -m http.server 8000 --directory unity/Builds/Web-disabled # then open```Desktop players (macOS IL2CPP; Linux and Windows on Mono, built from the Mac) and their build record come from-`uv run tools/release_build.py`; see "Desktop builds" in [`docs/RELEASING.md`](docs/RELEASING.md).+`uv run tools/release_build.py`; see "Desktop builds" in step 5 of [`docs/RELEASING.md`](docs/RELEASING.md).A build rewrites some cached settings. Drop them afterwards with`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`.diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 187a9099c..87a2dc853 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -43,14 +43,59 @@ GitHub Releases page (and, from M4, on itch.io). Steps 1–3 are a normal pull rtrims the least recently used above 1 GiB (`MaximumCacheSize=1073741824` in the 6000.3 loader). With hashed names,every build with the same `bundleVersion` adds one more `.data` there until that cap; the version bump in step 2clears them at each release.-6. **Tag and publish (owner):**++ **Desktop builds (macOS, Linux, Windows).** Desktop players are built on the owner's Mac (decisions O7 and O8 in+ `docs/oss/DECISIONS.md`; plan in `docs/superpowers/specs/2026-10-14-desktop-builds-and-release-pipeline.md`). On the merged `main`, tag `HEAD` first+ (`git tag -a vX.Y.Z -m "Statecraft: Israel vX.Y.Z"`; step 6 pushes it), then:++ ```bash+ uv run tools/release_build.py --platform all --tag vX.Y.Z # or mac, linux, windows; --dry-run prints the commands+ ```++ Before building anything it refuses: a dirty tree; a branch other than `main`, or a `HEAD` that your last+ `git fetch origin` did not show on `origin/main` (the script never fetches); a tag that is not `v` plus `bundleVersion`+ (a `-suffix` is allowed; it is the default) or does not point at `HEAD`; an editor whose version is not the one in `ProjectVersion.txt`; an+ `--out` inside any checkout or worktree of the repository (ignored folders too: a build empties+ `StreamingAssets/content`), or one that is not empty. It also stops if Unity Hub lacks a module the platforms need: Mac+ Build Support (IL2CPP), Linux Build Support (Mono) or Windows Build Support (Mono); the message names them and gives the+ Hub command. `--dev` makes a test build from any branch: not `-shareable`, no `--tag`, and archives named+ `vX.Y.Z-dev.<commit>` so they cannot pass for a release.++ Each build runs under `tools/machine_lock.py --shared --wait-unity`. The script runs the `-golden` check on the macOS+ player, the only one the Mac can run; the Linux and Windows players are recorded as unchecked until the CI player check+ runs them. It archives each player under the names that check expects (`statecraft-israel-vX.Y.Z-macos-universal.zip`,+ made with `ditto`; `-linux-x64.tar.gz`; `-windows-x64.zip`), each with `LICENSE`, `NOTICE`, `THIRD-PARTY-NOTICES.md`,+ the two font licences (`OFL-EBGaramond.txt`, `OFL-FrankRuhlLibre.txt`) and `LICENSES/` beside the player (it lists the+ archive to check), and writes `build-record.json`, `build-record.md`, a `files-<platform>.sha256` list of each+ archive's files and the build's `event-photos-<platform>.json` to `~/statecraft-release/v<version>-<commit>-<UTC time>/`+ (or `--out`), and prints the path. It never commits, pushes or uploads: copy the record files to the build records+ repository by hand. Signing and Steam upload are later steps, not yet scripted.+6. **Tag and publish (owner), in one `gh release create`.** The release carries the web zip and, once desktop players+ ship (decisions O1, O7 and O9 in `docs/oss/DECISIONS.md`), all three desktop archives from "Desktop builds" above, as+ a pre-release with "unchecked" in its notes. Never publish first and upload the players afterwards:```bash- git tag -a vX.Y.Z -m "Statecraft: Israel vX.Y.Z" && git push origin vX.Y.Z- gh release create vX.Y.Z unity/Builds/statecraft-israel-vX.Y.Z-web.zip --title "vX.Y.Z" --notes-file <(awk '/^## \[X.Y.Z\]/{f=1;next} /^## \[/{f=0} f' CHANGELOG.md)+ git tag -a vX.Y.Z -m "Statecraft: Israel vX.Y.Z" # skip if "Desktop builds" already made it+ git push origin vX.Y.Z+ gh release create vX.Y.Z --prerelease --title "vX.Y.Z" --notes-file <notes from CHANGELOG.md, saying "unchecked"> \+ unity/Builds/statecraft-israel-vX.Y.Z-web.zip <out>/statecraft-israel-vX.Y.Z-windows-x64.zip \+ <out>/statecraft-israel-vX.Y.Z-linux-x64.tar.gz <out>/statecraft-israel-vX.Y.Z-macos-universal.zip```- Paste the SHA-256 from step 5 into the release notes.+ `<out>` is the folder `tools/release_build.py` printed. The notes are the version's CHANGELOG section+ (`awk '/^## \[X.Y.Z\]/{f=1;next} /^## \[/{f=0} f' CHANGELOG.md`), the SHA-256 from step 5, and "unchecked".++ Publishing starts the `Player golden` workflow (`.github/workflows/player-golden.yml`). It downloads each player,+ checks it against the SHA-256 GitHub records for the asset, and runs `-batchmode -nographics -golden` on GitHub's+ Windows and Linux machines, and the Mac app twice: on Apple silicon (`macos-15`, its arm64 slice) and on Intel+ (`macos-15-intel`, its x86_64 slice; issue #548 tracks its end in August 2027). It fails when only one or two of the+ three archives are attached. A release with none (a web-only release, before desktop players ship) passes, but its+ run summary says UNCHECKED.+ - **The release stays a pre-release marked "unchecked" until that run is green.** Testers can download a pre-release+ as soon as it is published, so do not announce it before then. Then remove "unchecked" from the notes.+ - **Uploading or replacing an archive later** (`gh release upload`, with or without `--clobber`) starts no run. After+ any such upload, run `gh workflow run player-golden.yml -f tag=vX.Y.Z` and wait for it to pass+ (`gh run watch`). A run that started before the replacement fails on the digest; run it again.7. **Check every published artefact:** download each uploaded archive (GitHub Releases, and itch.io once used) into anempty folder, then list it and look for the notices: for a `.zip` (the web zip, the macOS and Windows players),`unzip -Z1 <zip> | grep -E '^(LICENSE|NOTICE|THIRD-PARTY-NOTICES.md|OFL-EBGaramond.txt|OFL-FrankRuhlLibre.txt)$'`;@@ -58,35 +103,6 @@ GitHub Releases page (and, from M4, on itch.io). Steps 1–3 are a normal pull r`tar -tzf <archive> | grep -E '^(\./)?(LICENSE|NOTICE|THIRD-PARTY-NOTICES.md|OFL-EBGaramond.txt|OFL-FrankRuhlLibre.txt)$'`.It must print five lines for each archive.-## Desktop builds (macOS, Linux, Windows)--Desktop players are built on the owner's Mac (decisions O7 and O8 in `docs/oss/DECISIONS.md`; plan in-`docs/superpowers/specs/2026-10-14-desktop-builds-and-release-pipeline.md`). On the merged `main`, after the tag-(step 6's `git tag -a vX.Y.Z`, not yet pushed if you like) is on `HEAD`:--```bash-uv run tools/release_build.py --platform all --tag vX.Y.Z # or mac, linux, windows; --dry-run prints the commands-```--Before building anything it refuses: a dirty tree; a branch other than `main`, or a `HEAD` that your last-`git fetch origin` did not show on `origin/main` (the script never fetches); a tag that is not `v` plus `bundleVersion`-(a `-suffix` is allowed; it is the default) or does not point at `HEAD`; an editor whose version is not the one in `ProjectVersion.txt`; an-`--out` inside any checkout or worktree of the repository (ignored folders too: a build empties-`StreamingAssets/content`), or one that is not empty. It also stops if Unity Hub lacks a module the platforms need: Mac-Build Support (IL2CPP), Linux Build Support (Mono) or Windows Build Support (Mono); the message names them and gives the-Hub command. `--dev` makes a test build from any branch: not `-shareable`, no `--tag`, and archives named-`vX.Y.Z-dev.<commit>` so they cannot pass for a release.--Each build runs under `tools/machine_lock.py --shared --wait-unity`. The script runs the `-golden` check on the macOS-player, the only one the Mac can run; the Linux and Windows players are recorded as unchecked until the CI player check-runs them. It archives each player under the names that check expects (`statecraft-israel-vX.Y.Z-macos-universal.zip`,-made with `ditto`; `-linux-x64.tar.gz`; `-windows-x64.zip`), each with `LICENSE`, `NOTICE`, `THIRD-PARTY-NOTICES.md`, the two font-licences (`OFL-EBGaramond.txt`, `OFL-FrankRuhlLibre.txt`) and `LICENSES/` beside the player (it lists the archive to check), and writes `build-record.json`, `build-record.md`, a-`files-<platform>.sha256` list of each archive's files and the build's `event-photos-<platform>.json` to-`~/statecraft-release/v<version>-<commit>-<UTC time>/` (or `--out`), and prints the path. It never commits, pushes or-uploads: copy the record files to the build records repository by hand. Signing and Steam upload are later steps, not yet-scripted.-## Refreshing the README screenshotsThe README's screenshots are claims about the current build. Re-take them whenever the build looks different, anddiff --git a/scripts/oss/tests/test_github_config.py b/scripts/oss/tests/test_github_config.pyindex 0f8e6966c..dab20d789 100644--- a/scripts/oss/tests/test_github_config.py+++ b/scripts/oss/tests/test_github_config.py@@ -142,3 +142,36 @@ def test_merge_workflow_waits_for_every_required_check():wf = yaml.safe_load(MERGE.read_text(encoding="utf-8"))need = set(wf["jobs"]["merge"]["env"]["REQUIRED_CHECKS"].split("|"))assert need == EXPECTED_JOBS+++PLAYER = ROOT / ".github/workflows/player-golden.yml"+++def test_player_golden_runs_only_the_repositorys_own_released_players():+ # Plan 2026-10-14 section 6.3 and decision O7: GitHub runners only check the players the owner built and released.+ # The workflow runs binaries, so nothing a pull request, a URL or an Actions artifact supplies may reach it.+ wf = yaml.safe_load(PLAYER.read_text(encoding="utf-8"))+ text = PLAYER.read_text(encoding="utf-8")+ assert triggers(wf) == {"release": {"types": ["published"]},+ "workflow_dispatch": {"inputs": {"tag": triggers(wf)["workflow_dispatch"]["inputs"]["tag"]}}}+ assert wf["permissions"] == {"contents": "read"}+ assert "secrets." not in text and "UNITY_" not in text and "game-ci/" not in text # no Unity licence or editor+ for s in steps(wf):+ if s.get("uses", "").startswith("actions/checkout@"):+ assert s.get("with", {}).get("persist-credentials") is False, s+ assert "${{" not in s.get("run", ""), s # inputs and event fields reach the shell only through env:+ # An empty matrix is a workflow error, so the player jobs need the guard; one platform's failure must not cancel the+ # others' runs (review N2).+ golden = wf["jobs"]["golden"]+ assert golden["needs"] == "plan" and golden["if"] == "needs.plan.outputs.count != '0'"+ assert golden["strategy"]["fail-fast"] is False+ assert golden["strategy"]["matrix"] == "${{ fromJSON(needs.plan.outputs.matrix) }}"+ run_step = next(s for s in golden["steps"] if "player_golden_check.py run" in s.get("run", ""))+ assert '--sha256 "$SHA256"' in run_step["run"] and run_step["env"]["SHA256"] == "${{ matrix.sha256 }}"+ assert '${ARCH:+--arch "$ARCH"}' in run_step["run"] and run_step["env"]["ARCH"] == "${{ matrix.arch }}"+ assert golden["name"] == "Player golden (${{ matrix.label }})" and golden["runs-on"] == "${{ matrix.runner }}"+ downloads = [s["run"] for s in steps(wf) if "gh release download" in s.get("run", "")]+ assert downloads and all('--repo "$GITHUB_REPOSITORY"' in r for r in downloads)+ assert "curl" not in text and "wget" not in text and "download-artifact" not in text+ for ref_line in re.findall(r"uses:\s*[\w.-]+/[\w./-]+@[0-9a-f]{40}.*", text):+ assert re.search(r"# v\d+\.\d+\.\d+$", ref_line), ref_linediff --git a/tools/README.md b/tools/README.mdindex a7e9b943b..5c0eca4b9 100644--- a/tools/README.md+++ b/tools/README.md@@ -29,13 +29,18 @@ Offline data tools (uv inline-script Python). Run from the repo root.and prints the accuracy table of `docs/routes.md`.- `web_check.py` serves a WebGL build on http://localhost and opens it in headless Chrome for Testing (Playwright'scache; macOS only, arm64 or x64); it passes when the console shows the expected lines (`GOLDEN OK ...`, `SMOKE OK ...`).+- `player_golden_check.py` is the logic of `.github/workflows/player-golden.yml`: `plan` lists the desktop players a+ GitHub 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,+ printing the player log otherwise. Stdlib only; no Unity and no licence needed.- `package_release.py` zips a Brotli WebGL build 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/` arenamed by their content hash (issue #437); it reads their names from the build's `index.html`, zips only those andrefuses a build that is missing one.- `release_build.py [--platform mac|linux|windows|all] [--out DIR] [--tag vX.Y.Z] [--dev] [--dry-run] [--unity PATH]`builds the desktop players under the machine lock, runs the macOS player's golden check and writes a build record- outside every checkout (`docs/RELEASING.md`, "Desktop builds"). A release must be `main` at its tag; `--dev` builds+ outside every checkout (`docs/RELEASING.md`, step 5, "Desktop builds"). A release must be `main` at its tag; `--dev` buildsanywhere under a `-dev.<commit>` name. It never commits, pushes or uploads.- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.- `terrain_bake.py` writes `unity/Assets/Textures/Map/terrain_bake.png` (AO, curvature, sky-view), `ao.png` (the AOdiff --git a/tools/player_golden_check.py b/tools/player_golden_check.pynew file mode 100644index 000000000..681c168af--- /dev/null+++ b/tools/player_golden_check.py@@ -0,0 +1,338 @@+# /// script+# requires-python = ">=3.12"+# dependencies = []+# ///+"""The licence-free golden check of a released desktop player (.github/workflows/player-golden.yml; plan+docs/superpowers/specs/2026-10-14-desktop-builds-and-release-pipeline.md, sections 2.2 and 6.3; decision O7).++ uv run tools/player_golden_check.py plan --tag vX.Y.Z --event release|workflow_dispatch --output FILE [--summary FILE] < release.json+ uv run tools/player_golden_check.py run --platform windows|linux|macos [--arch arm64|x86_64 (macos)] --archive FILE --sha256 HEX --manifest manifest.txt+ --work DIR++`plan` reads `gh release view --json tagName,isDraft,assets` on stdin, checks the tag's form and that the release is+published, and appends to FILE (the job's $GITHUB_OUTPUT) `matrix=` the GitHub Actions matrix of the players and+`count=` their number. Each entry carries the SHA-256 GitHub records for the asset (its `digest`). A release with desktop+players must carry all three: one or two fails, and so does an asset without a SHA-256 digest. No player at all fails a+manual run; on a release event it passes (a web-only release) but writes an "UNCHECKED" warning to the run summary.++`run` checks the archive's SHA-256 against that digest (so a re-uploaded asset fails until it is re-planned), unpacks it+into an empty folder, finds the player, checks the layout (the notices of REQUIRED_NOTICES at the top level beside the+player or the .app), runs it with+`-batchmode -nographics -golden -logFile <absolute path>` (docs/determinism.md) 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+it prints the whole player log. With --arch (the Mac app, run once per slice) the runner's `uname -m` must be that+architecture and `lipo -archs` must list it. Exit 0 when the check passes, 1 when it fails, 2 on bad input.++The release asset names are a contract with the release script (tools/release_build.py): see ASSETS.+Stdlib only.+"""+import argparse+import hashlib+import json+import os+import re+import subprocess+import sys+import tarfile+import zipfile+from pathlib import Path++# A release tag: vMAJOR.MINOR.PATCH, optionally with a pre-release suffix (v0.2.0-rc.1). Nothing else reaches a path,+# a download or a checkout.+# re.ASCII: \d must not accept other scripts' digits. The workflow's shell check is the same pattern (a test pins them).+TAG = re.compile(r"v\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*)?", re.ASCII)+DIGEST = re.compile(r"sha256:([0-9a-f]{64})", re.ASCII)++# The asset names the release script must attach to the GitHub Release, by platform (the web zip already follows this+# form: statecraft-israel-vX.Y.Z-web.zip, docs/RELEASING.md). {tag} is the release tag, v included.+ASSETS = {+ "windows": "statecraft-israel-{tag}-windows-x64.zip",+ "linux": "statecraft-israel-{tag}-linux-x64.tar.gz",+ "macos": "statecraft-israel-{tag}-macos-universal.zip",+}+# The GitHub-hosted runners each player is checked on (standard runners, free and unlimited for a public repository,+# plan 6.1): (runner label, the CPU architecture it must report). The Universal Mac app runs twice, so each of its two+# native IL2CPP slices is checked on its own CPU: macos-15 is Apple silicon, macos-15-intel is x86_64 (GitHub offers it+# until August 2027, runner-images#13045; what replaces it is issue #548). An empty architecture is not checked.+RUNNERS = {+ "windows": [("windows-2025", "")],+ "linux": [("ubuntu-24.04", "")],+ "macos": [("macos-15", "arm64"), ("macos-15-intel", "x86_64")],+}++# The notices every archive carries at its top level, beside the player (tools/release_build.py adds them and takes+# this list; the web packager, scripts/oss/package_web.sh, copies the same files: test_release_build pins that).+REQUIRED_NOTICES = ["LICENSE", "LICENSES/CC-BY-4.0.txt", "LICENSES/CC-BY-SA-4.0.txt", "LICENSES/CC0-1.0.txt",+ "LICENSES/YamlDotNet-MIT.txt", "NOTICE", "OFL-EBGaramond.txt", "OFL-FrankRuhlLibre.txt",+ "THIRD-PARTY-NOTICES.md"]+NOTICE_TOPS = {n.split("/")[0] for n in REQUIRED_NOTICES}++GOLDENS = (("1950", "hash1950"), ("1952", "hash1952"))+FAIL = re.compile(r"\b(GOLDEN FAIL|BOOT FAIL)\b")+++def asset_name(tag: str, platform: str) -> str:+ if not TAG.fullmatch(tag):+ raise ValueError(f"not a release tag: {tag!r} (expected vX.Y.Z)")+ return ASSETS[platform].format(tag=tag)+++def plan(tag: str, release: dict, event: str) -> tuple[list[dict], list[str], bool]:+ """(matrix include list, messages as workflow commands, ok) for a release's JSON from gh+ (`gh release view --json tagName,isDraft,assets`; each asset has `name` and `digest`)."""+ if not TAG.fullmatch(tag):+ return [], [f"::error::not a release tag: {tag!r} (expected vX.Y.Z)"], False+ if release.get("tagName") != tag:+ return [], [f"::error::the release is for {release.get('tagName')!r}, not {tag!r}"], False+ if release.get("isDraft"):+ return [], [f"::error::release {tag} is a draft; only published releases are checked"], False+ digests = {a.get("name"): a.get("digest") for a in release.get("assets", [])}+ include, missing, msgs = [], [], []+ found = 0+ for platform, runners in RUNNERS.items():+ name = asset_name(tag, platform)+ if name not in digests:+ missing.append(f"{platform} ({name})")+ continue+ found += 1+ m = DIGEST.fullmatch(digests[name] or "")+ if not m:+ msgs.append(f"::error::asset {name} has no SHA-256 digest from GitHub ({digests[name]!r})")+ for runner, arch in runners:+ include.append({"platform": platform, "label": f"{platform} {arch}".strip(), "runner": runner, "arch": arch,+ "asset": name, "sha256": m.group(1) if m else ""})+ if not include:+ if event == "workflow_dispatch":+ return [], [f"::error::release {tag} has none of the player assets"], False+ # A web-only release is valid; failing it would make red runs routine. The summary says it loudly instead.+ return [], [f"::warning::UNCHECKED: release {tag} has no desktop player. If players are uploaded later, run "+ f"gh workflow run player-golden.yml -f tag={tag} (docs/RELEASING.md, step 6)"], True+ if missing:+ msgs.append(f"::error::release {tag} has {found} of the 3 desktop players; missing: {', '.join(missing)}. "+ "Attach all three in the same gh release create (docs/RELEASING.md, step 6)")+ if msgs:+ return [], msgs, False+ return include, msgs, True+++def read_manifest(text: str) -> dict[str, str]:+ out = {}+ for line in text.splitlines():+ parts = line.split()+ if len(parts) == 2 and not line.startswith("#"):+ out[parts[0]] = parts[1]+ return out+++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]+++def check_log(log: str, expected: list[str], exit_code: int | None) -> list[str]:+ """The problems with a player run: empty when it passed. The player prints each GOLDEN line bare on its own line+ (GameBoot.cs Debug.Log; the Mac player log of the #542 release-script run shows exactly that), so a line must equal+ the expected text after stripping: no prefix, and no extra character (one more hex digit is a different hash)."""+ lines = [l.strip() for l in log.splitlines()]+ problems = []+ if exit_code is None:+ problems.append("the player did not exit before the timeout")+ elif exit_code != 0:+ problems.append(f"the player exited {exit_code}")+ for want in expected:+ if want not in lines:+ problems.append(f"missing line: {want}")+ problems += [f"failure line: {l}" for l in lines if FAIL.search(l)]+ return problems+++def unpack(archive: Path, dest: Path) -> None:+ """Unpacks into dest, which must be new or empty. tar keeps the Linux player's executable bit; ditto keeps the Mac+ app's bundle layout and modes; the Windows zip needs neither."""+ dest.mkdir(parents=True, exist_ok=True)+ if any(dest.iterdir()):+ raise ValueError(f"{dest} is not empty")+ name = archive.name+ if name.endswith(".tar.gz"):+ with tarfile.open(archive) as t:+ t.extractall(dest, filter="data") # refuses absolute paths, .. and links that leave dest+ elif name.endswith(".zip") and sys.platform == "darwin":+ subprocess.run(["ditto", "-x", "-k", str(archive), str(dest)], check=True)+ elif name.endswith(".zip"):+ with zipfile.ZipFile(archive) as z:+ z.extractall(dest) # zipfile drops absolute paths and .. components+ else:+ raise ValueError(f"not a .zip or .tar.gz: {name}")+++def find_player(root: Path, platform: str) -> Path:+ """The one player executable under root."""+ if platform == "windows":+ found = [p for p in root.rglob("*.exe") if not p.name.lower().startswith("unitycrashhandler")]+ elif platform == "linux":+ found = [p for p in root.rglob("*.x86_64") if p.is_file()]+ elif platform == "macos":+ found = [p for app in root.rglob("*.app") if app.is_dir()+ for p in (app / "Contents" / "MacOS").glob("*") if p.is_file()]+ else:+ raise ValueError(f"unknown platform {platform!r}")+ if len(found) != 1:+ raise ValueError(f"expected one {platform} player under {root}, found {len(found)}: "+ + ", ".join(str(p.relative_to(root)) for p in sorted(found)))+ return found[0]+++def layout_problems(root: Path, platform: str, exe: Path) -> list[str]:+ """How an unpacked archive breaks the release layout (tools/release_build.py, make_archive): the notices at the top+ level; Windows and Linux: the player there too; macOS: the .app there, and nothing else beside it but the notices."""+ problems = [f"missing notice: {n}" for n in REQUIRED_NOTICES if not (root / n).is_file()]+ if platform == "macos":+ app = exe.parents[2] # <app>/Contents/MacOS/<exe>+ if app.parent != root:+ problems.append(f"the app is not at the archive's top level: {app.relative_to(root)}")+ extra = sorted(p.name for p in root.iterdir() if p != app and p.name not in NOTICE_TOPS)+ if extra:+ problems.append(f"unexpected beside the app: {', '.join(extra)}")+ elif exe.parent != root:+ problems.append(f"the player is not at the archive's top level: {exe.relative_to(root)}")+ return problems+++def sha256(path: Path) -> str:+ h = hashlib.sha256()+ with path.open("rb") as f:+ for block in iter(lambda: f.read(1 << 20), b""):+ h.update(block)+ return h.hexdigest()+++def check_arch(exe: Path, arch: str, machine: str, archs: str) -> list[str]:+ """Problems with running exe's `arch` slice here: this machine must be that CPU (`uname -m`), and the executable+ must carry the slice (`lipo -archs`), so a wrong runner label cannot quietly check the other slice."""+ problems = []+ if machine != arch:+ problems.append(f"the runner is {machine}, not {arch}: check the runner label")+ if arch not in archs.split():+ problems.append(f"{exe.name} has no {arch} slice (lipo -archs: {archs.strip() or 'nothing'})")+ return problems+++def run_player(exe: Path, log: Path, timeout: int) -> int | None:+ """Runs the golden check; the exit code, or None on timeout. subprocess waits for a Windows GUI-subsystem player+ too, which a plain PowerShell call would not."""+ if os.name != "nt":+ exe.chmod(exe.stat().st_mode | 0o111)+ cmd = [str(exe), "-batchmode", "-nographics", "-golden", "-logFile", str(log.resolve())]+ print("RUN", " ".join(cmd), flush=True)+ try:+ return subprocess.run(cmd, cwd=exe.parent, timeout=timeout).returncode+ except subprocess.TimeoutExpired:+ return None+++def summary(tag: str, include: list[dict], ok: bool) -> str:+ if not ok:+ return f"## Player golden {tag}: REFUSED\n\nNo player was run; see the plan job's errors.\n"+ if not include:+ return (f"## Player golden {tag}: UNCHECKED\n\nThe release has no desktop player, so none was run. If players "+ f"are uploaded later, run `gh workflow run player-golden.yml -f tag={tag}` and wait for it to pass.\n")+ rows = "".join(f"| {e['label']} | `{e['runner']}` | `{e['asset']}` | `{e['sha256']}` |\n" for e in include)+ return (f"## Player golden {tag}\n\n| Player | Runner | Asset | SHA-256 (GitHub digest) |\n| --- | --- | --- | --- |\n"+ f"{rows}")+++def cmd_plan(a) -> int:+ try:+ release = json.load(sys.stdin)+ except json.JSONDecodeError as e:+ print(f"::error::the release JSON is unreadable: {e}")+ return 2+ include, msgs, ok = plan(a.tag, release, a.event)+ for m in msgs:+ print(m)+ if a.summary:+ with open(a.summary, "a", encoding="utf-8") as f:+ f.write(summary(a.tag, include, ok))+ matrix = json.dumps({"include": include}, separators=(",", ":"))+ print(f"MATRIX {matrix}")+ if ok:+ with open(a.output, "a", encoding="utf-8") as f:+ f.write(f"matrix={matrix}\ncount={len(include)}\n")+ return 0 if ok else 1+++def cmd_run(a) -> int:+ try:+ expected = expected_lines(read_manifest(Path(a.manifest).read_text(encoding="utf-8")))+ archive = Path(a.archive)+ got = sha256(archive)+ print(f"ARCHIVE {archive.name} sha256 {got}", flush=True)+ if got != a.sha256:+ raise ValueError(f"{archive.name} has SHA-256 {got}, but GitHub's digest for the asset is {a.sha256!r}; "+ "it was replaced after the plan job: run the workflow again")+ if (a.platform == "macos") != bool(a.arch):+ raise ValueError("--arch (arm64 or x86_64) is required for macos and only for macos")+ work = Path(a.work).resolve() # the player runs with cwd at its folder, so every path must be absolute+ unpack(archive, work / "player")+ exe = find_player(work / "player", a.platform)+ if problems := layout_problems(work / "player", a.platform, exe):+ raise ValueError("; ".join(problems))+ if a.arch:+ machine = subprocess.run(["uname", "-m"], capture_output=True, text=True, check=True).stdout.strip()+ archs = subprocess.run(["lipo", "-archs", str(exe)], capture_output=True, text=True, check=True).stdout+ print(f"ARCH runner {machine}, player slices {archs.strip()}", flush=True)+ if problems := check_arch(exe, a.arch, machine, archs):+ raise ValueError("; ".join(problems))+ except (OSError, ValueError, subprocess.CalledProcessError, tarfile.TarError, zipfile.BadZipFile) as e:+ print(f"::error::{a.platform}: {e}")+ print(f"PLAYER GOLDEN ERROR {a.platform}")+ return 2+ log = work / "player.log"+ try:+ code = run_player(exe, log, a.timeout)+ except OSError as e: # the player could not be started at all (for example: Exec format error); it has no exit code+ code, start_error = None, f"the player could not be started: {e}"+ else:+ start_error = ""+ text = log.read_text(encoding="utf-8", errors="replace") if log.exists() else ""+ problems = [start_error] if start_error else check_log(text, expected, code)+ if not problems:+ for line in expected:+ print(line)+ print(f"PLAYER GOLDEN OK {a.platform}")+ return 0+ print(f"----- player log ({log}) -----")+ print(text if text else "(no log was written)")+ print("----- end of player log -----")+ for p in problems:+ print(f"::error::{a.platform}: {p}")+ print(f"PLAYER GOLDEN FAIL {a.platform}")+ return 1+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ sub = ap.add_subparsers(dest="cmd", required=True)+ p = sub.add_parser("plan")+ p.add_argument("--tag", required=True)+ p.add_argument("--event", required=True, choices=["release", "workflow_dispatch"])+ p.add_argument("--output", required=True, help="the file to append matrix= and count= to ($GITHUB_OUTPUT)")+ p.add_argument("--summary", help="the file to append a Markdown summary to ($GITHUB_STEP_SUMMARY)")+ r = sub.add_parser("run")+ r.add_argument("--platform", required=True, choices=sorted(ASSETS))+ r.add_argument("--archive", required=True)+ r.add_argument("--arch", choices=["arm64", "x86_64"],+ help="macos only, and required there: the slice to check; the runner must be that CPU and the app "+ "must carry it")+ r.add_argument("--sha256", required=True, help="the asset's SHA-256 from GitHub (hex), from plan")+ r.add_argument("--manifest", required=True)+ r.add_argument("--work", required=True)+ r.add_argument("--timeout", type=int, default=900)+ a = ap.parse_args(argv)+ return cmd_plan(a) if a.cmd == "plan" else cmd_run(a)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/release_build.py b/tools/release_build.pyindex ffc20f0fd..b09613576 100644--- a/tools/release_build.py+++ b/tools/release_build.py@@ -64,6 +64,8 @@ from dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Path+import player_golden_check as pgc # tools/: the one asset-name contract, tag rule and golden pass rule (issue #546)+REPO = Path(__file__).resolve().parents[1]LOCK_TIMEOUT = 30 * 24 * 3600 # machine_lock's own default gives up after an hour; a release waits for the machineHUB = "/Applications/Unity Hub.app/Contents/MacOS/Unity Hub"@@ -71,23 +73,17 @@ METHOD = "Statecraft.Game.EditorTools.Build."# The licence and attribution files every archive carries beside the player (RELEASING.md step 7): the list# scripts/oss/package_web.sh copies into the web zip and checks (test_the_notice_list_is_the_web_packagers keeps them# one list). Archive name -> source in the repository; LICENSES/ is copied whole, as the web packager does.-REQUIRED_NOTICES = ["LICENSE", "LICENSES/CC-BY-4.0.txt", "LICENSES/CC-BY-SA-4.0.txt", "LICENSES/CC0-1.0.txt",- "LICENSES/YamlDotNet-MIT.txt", "NOTICE", "OFL-EBGaramond.txt", "OFL-FrankRuhlLibre.txt",- "THIRD-PARTY-NOTICES.md"]+REQUIRED_NOTICES = pgc.REQUIRED_NOTICES # one list with the CI player check, which checks every archive has them# Each font's own OFL text (its copyright line differs), under the names site/public/fonts uses. Every OFL.txt under# unity/Assets/UI/Fonts must be here (test_every_shipped_fonts_licence_is_a_required_notice).FONT_LICENCES = {"OFL-EBGaramond.txt": "unity/Assets/UI/Fonts/OFL.txt","OFL-FrankRuhlLibre.txt": "unity/Assets/UI/Fonts/FrankRuhlLibre/OFL.txt"}-NOTICE_TOPS = {"LICENSE", "LICENSES", "NOTICE", "THIRD-PARTY-NOTICES.md", *FONT_LICENCES}+NOTICE_TOPS = pgc.NOTICE_TOPSPHOTOS = "event-photos.json" # Build.PhotoManifestName: written beside every player, read by packaging, not the player-# The release asset names: a contract with the CI player golden check (tools/player_golden_check.py, PR #533), in the-# form of the web zip (statecraft-israel-vX.Y.Z-web.zip, docs/RELEASING.md). {tag} carries the v.-ARCHIVES = {- "mac": "statecraft-israel-{tag}-macos-universal.zip",- "linux": "statecraft-israel-{tag}-linux-x64.tar.gz",- "windows": "statecraft-israel-{tag}-windows-x64.zip",-}-TAG = re.compile(r"v\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:\.[0-9A-Za-z]+)*)?", re.ASCII) # ASCII: \d must not match other digits+# The release asset names and the tag rule are the CI player golden check's (tools/player_golden_check.py), so the two+# cannot drift (issue #546). {tag} carries the v. The CI check names the Mac "macos".+ARCHIVES = {"mac": pgc.ASSETS["macos"], "linux": pgc.ASSETS["linux"], "windows": pgc.ASSETS["windows"]}+TAG = pgc.TAG@dataclass(frozen=True)@@ -263,16 +259,17 @@ def golden_command(player: Path, log: Path) -> list[str]:# --- results -------------------------------------------------------------------------------------------------------------def golden_lines(log_text: str) -> list[str]:- return [m.group(0) for m in re.finditer(r"GOLDEN (?:OK|FAIL) \d{4} [0-9a-f]{64}(?: expected [0-9a-f]{64})?", log_text)]+ """The GOLDEN lines as the player printed them (stripped), for the build record."""+ return [l.strip() for l in log_text.splitlines() if l.strip().startswith(("GOLDEN OK ", "GOLDEN FAIL "))]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, and no GOLDEN FAIL or BOOT FAIL line (the same- rule as the CI player check of PR #533)."""- lines = set(golden_lines(log_text))- ok = exit_code == 0 and all(f"GOLDEN OK {year} {h}" in lines for year, h in expected.items())- failed = re.search(r"\b(GOLDEN FAIL|BOOT FAIL)\b", log_text) is not None- return "pass" if ok and len(expected) == 2 and not failed else "fail"+ """pass only on exit 0, both `GOLDEN OK <year> <pinned hash>` lines exactly as the player prints them (bare, one per+ line), 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]+ return "pass" if not pgc.check_log(log_text, wanted, exit_code) else "fail"def archive_name(tag: str, platform: str) -> str:@@ -339,15 +336,13 @@ def make_archive(p: Platform, folder: Path, target: Path, dest: Path) -> None:def player_problem(p: Platform, folder: Path) -> str | None:- """Why the player folder breaks the archive contract of PR #533, or None: one player .exe (crash handler aside), one- *.x86_64, or one .app with one file in Contents/MacOS."""- if p.name == "windows":- found = [f for f in folder.rglob("*.exe") if not f.name.lower().startswith("unitycrashhandler")]- elif p.name == "linux":- found = [f for f in folder.rglob("*.x86_64") if f.is_file()]- else:- found = [f for app in folder.rglob("*.app") if app.is_dir() for f in (app / "Contents/MacOS").glob("*") if f.is_file()]- return None if len(found) == 1 else f"expected one {p.name} player in {folder}, found {len(found)}"+ """Why the player folder breaks the archive contract, or None: the CI player check's own find_player (one player+ .exe, crash handler aside; one *.x86_64; or one .app with one file in Contents/MacOS), so the two cannot drift."""+ try:+ pgc.find_player(folder, "macos" if p.name == "mac" else p.name)+ except ValueError as e:+ return str(e)+ return Nonedef file_sha256(path: Path) -> str:diff --git a/tools/tests/test_player_golden_check.py b/tools/tests/test_player_golden_check.pynew file mode 100644index 000000000..45a43c84c--- /dev/null+++ b/tools/tests/test_player_golden_check.py@@ -0,0 +1,437 @@+import hashlib+import io+import json+import re+import shutil+import subprocess+import sys+import tarfile+import zipfile+from pathlib import Path++import pytest++import player_golden_check as pg++REPO = Path(__file__).resolve().parents[2]+H50, H52 = "a" * 64, "b" * 64+MANIFEST = f"# comment\nhash1950 {H50}\nhash1952 {H52}\nsmoke5 {'c' * 64}\n"+EXPECTED = [f"GOLDEN OK 1950 {H50}", f"GOLDEN OK 1952 {H52}"]+++def digest(name):+ return "sha256:" + hashlib.sha256(name.encode()).hexdigest()+++def add_notices_to_tar(t):+ """The notices at the archive's top level, as tools/release_build.py adds them (#552)."""+ for n in pg.REQUIRED_NOTICES:+ info = tarfile.TarInfo(n)+ data = f"{n}\n".encode()+ info.size = len(data)+ t.addfile(info, io.BytesIO(data))+++def release(tag, *names, draft=False):+ return {"tagName": tag, "isDraft": draft, "assets": [{"name": n, "digest": digest(n)} for n in names]}+++def players(tag):+ return [pg.asset_name(tag, p) for p in ("windows", "linux", "macos")]+++def test_asset_names_are_the_release_script_contract():+ assert pg.asset_name("v0.2.0", "windows") == "statecraft-israel-v0.2.0-windows-x64.zip"+ assert pg.asset_name("v0.2.0", "linux") == "statecraft-israel-v0.2.0-linux-x64.tar.gz"+ assert pg.asset_name("v0.2.0-rc.1", "macos") == "statecraft-israel-v0.2.0-rc.1-macos-universal.zip"+++TAGS = {"v0.2.0": True, "v10.20.30": True, "v0.2.0-rc.1": True, "v1.0.0-beta.2.x9": True,+ "0.2.0": False, "v0.2": False, "v0.2.0 ": False, "v0.2.0;id": False, "v0.2.0/../x": False, "main": False, "": False,+ "v1.2.3-": False, "v1.2.3-rc..1": False, "v1.0.0\nmatrix=x": False, "v1.0.0\n": False, "v\u0661.0.0": False,+ "v1.0.0-r\u00e9": False, "V1.0.0": False, "xv1.0.0": False, "refs/tags/v1.0.0": False}+++def test_the_workflows_shell_tag_check_accepts_exactly_what_the_python_one_does():+ text = (REPO / ".github/workflows/player-golden.yml").read_text(encoding="utf-8")+ shell_re = re.search(r"^\s*re='([^']+)'$", text, re.M).group(1)+ for tag, want in TAGS.items():+ assert bool(pg.TAG.fullmatch(tag)) is want, tag+ r = subprocess.run(["bash", "-c", 're=$1; [[ $2 =~ $re ]]', "_", shell_re, tag], env={"LC_ALL": "C"})+ assert (r.returncode == 0) is want, tag++[email protected]("tag", [t for t, ok in TAGS.items() if not ok])+def test_anything_but_a_release_tag_is_refused(tag):+ with pytest.raises(ValueError):+ pg.asset_name(tag, "linux")+ include, msgs, ok = pg.plan(tag, release(tag), "workflow_dispatch")+ assert not ok and include == [] and msgs[0].startswith("::error::")+++def test_plan_lists_all_three_players_with_githubs_digests():+ r = release("v0.2.0", "statecraft-israel-v0.2.0-web.zip", *players("v0.2.0"))+ include, msgs, ok = pg.plan("v0.2.0", r, "release")+ assert ok and msgs == []+ win, lin, mac = players("v0.2.0")+ assert include == [+ {"platform": "windows", "label": "windows", "runner": "windows-2025", "arch": "", "asset": win,+ "sha256": digest(win)[7:]},+ {"platform": "linux", "label": "linux", "runner": "ubuntu-24.04", "arch": "", "asset": lin,+ "sha256": digest(lin)[7:]},+ {"platform": "macos", "label": "macos arm64", "runner": "macos-15", "arch": "arm64", "asset": mac,+ "sha256": digest(mac)[7:]},+ {"platform": "macos", "label": "macos x86_64", "runner": "macos-15-intel", "arch": "x86_64", "asset": mac,+ "sha256": digest(mac)[7:]},+ ]+++def test_the_mac_player_runs_on_apple_silicon_and_on_intel():+ # Review S3: the Universal app has two native IL2CPP slices; each is run on its own CPU, never under Rosetta.+ assert pg.RUNNERS["macos"] == [("macos-15", "arm64"), ("macos-15-intel", "x86_64")]+ include, _, ok = pg.plan("v0.2.0", release("v0.2.0", *players("v0.2.0")), "workflow_dispatch")+ assert ok and [(e["runner"], e["arch"]) for e in include if e["platform"] == "macos"] == [+ ("macos-15", "arm64"), ("macos-15-intel", "x86_64")]+ assert len({e["label"] for e in include}) == len(include) # the job names differ+++def test_the_arch_check_catches_a_wrong_runner_or_a_missing_slice():+ exe = Path("Statecraft Israel")+ assert pg.check_arch(exe, "x86_64", "x86_64", "x86_64 arm64\n") == []+ assert pg.check_arch(exe, "arm64", "arm64", "x86_64 arm64\n") == []+ assert pg.check_arch(exe, "x86_64", "arm64", "x86_64 arm64") == ["the runner is arm64, not x86_64: check the runner label"]+ assert pg.check_arch(exe, "x86_64", "x86_64", "arm64") == ["Statecraft Israel has no x86_64 slice (lipo -archs: arm64)"]++[email protected]("event", ["release", "workflow_dispatch"])+def test_a_partial_set_of_players_fails_and_runs_none(event):+ # Review M1: a release with only the Mac zip (already checked on the owner's Mac) must not pass green.+ r = release("v0.2.0", "statecraft-israel-v0.2.0-web.zip", players("v0.2.0")[2])+ include, msgs, ok = pg.plan("v0.2.0", r, event)+ assert not ok and include == []+ assert msgs == ["::error::release v0.2.0 has 1 of the 3 desktop players; missing: windows "+ "(statecraft-israel-v0.2.0-windows-x64.zip), linux (statecraft-israel-v0.2.0-linux-x64.tar.gz). "+ "Attach all three in the same gh release create (docs/RELEASING.md, step 6)"]++[email protected]("bad", [None, "", "sha1:" + "a" * 40, "sha256:" + "A" * 64, "sha256:" + "a" * 63])+def test_an_asset_without_a_sha256_digest_fails(bad):+ r = release("v0.2.0", *players("v0.2.0"))+ r["assets"][1]["digest"] = bad+ include, msgs, ok = pg.plan("v0.2.0", r, "release")+ assert not ok and include == [] and "has no SHA-256 digest" in msgs[0]+++def test_no_player_fails_a_manual_run_but_a_web_only_release_passes_unchecked(tmp_path, monkeypatch):+ r = release("v0.2.0", "statecraft-israel-v0.2.0-web.zip")+ include, msgs, ok = pg.plan("v0.2.0", r, "release")+ assert ok and include == [] and msgs[0].startswith("::warning::UNCHECKED: release v0.2.0 has no desktop player")+ assert "gh workflow run player-golden.yml -f tag=v0.2.0" in msgs[0]+ assert pg.plan("v0.2.0", r, "workflow_dispatch")[2] is False+ monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(r)))+ out, summary = tmp_path / "out", tmp_path / "summary"+ assert pg.main(["plan", "--tag", "v0.2.0", "--event", "release", "--output", str(out), "--summary", str(summary)]) == 0+ assert out.read_text().splitlines()[1] == "count=0"+ assert summary.read_text().startswith("## Player golden v0.2.0: UNCHECKED")+++def test_drafts_and_mismatched_releases_are_refused(tmp_path, monkeypatch):+ assert pg.plan("v0.2.0", release("v0.2.0", draft=True), "release")[2] is False+ assert pg.plan("v0.2.0", release("v0.1.0"), "release")[2] is False+ # The command exits 1 on a refusal and writes no matrix, so the player jobs are skipped behind a failed job.+ monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(release("v0.2.0", *players("v0.2.0"), draft=True))))+ out = tmp_path / "out"+ assert pg.main(["plan", "--tag", "v0.2.0", "--event", "release", "--output", str(out)]) == 1+ assert not out.exists()+++def test_plan_command_writes_the_matrix_to_the_github_output(tmp_path, monkeypatch, capsys):+ monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(release("v1.0.0", *players("v1.0.0")))))+ out = tmp_path / "github_output"+ assert pg.main(["plan", "--tag", "v1.0.0", "--event", "release", "--output", str(out)]) == 0+ lines = out.read_text().splitlines()+ matrix = json.loads(lines[0].removeprefix("matrix="))+ assert [e["label"] for e in matrix["include"]] == ["windows", "linux", "macos arm64", "macos x86_64"]+ assert lines[1] == "count=4"+++def 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"))+ 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"]+++def test_a_passing_log_needs_both_lines_and_exit_zero():+ log = "Initialize engine\r\n" + "\r\n".join(EXPECTED) + "\r\n"+ 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]}"]+++def test_a_wrong_hash_or_a_fail_line_fails():+ wrong = f"GOLDEN OK 1950 {H50}\nGOLDEN FAIL 1952 {'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}"]+ 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) == [+ f"missing line: {EXPECTED[0]}", f"missing line: {EXPECTED[1]}"]+++def test_find_player_finds_exactly_one(tmp_path):+ (tmp_path / "w" / "Statecraft_Data").mkdir(parents=True)+ (tmp_path / "w" / "Statecraft Israel.exe").write_bytes(b"")+ (tmp_path / "w" / "UnityCrashHandler64.exe").write_bytes(b"")+ assert pg.find_player(tmp_path / "w", "windows").name == "Statecraft Israel.exe"+ (tmp_path / "w" / "Other.exe").write_bytes(b"")+ with pytest.raises(ValueError, match="found 2"):+ pg.find_player(tmp_path / "w", "windows")+ (tmp_path / "l" / "statecraft").mkdir(parents=True)+ (tmp_path / "l" / "statecraft" / "Statecraft.x86_64").write_bytes(b"")+ assert pg.find_player(tmp_path / "l", "linux").name == "Statecraft.x86_64"+ macos = tmp_path / "m" / "Statecraft.app" / "Contents" / "MacOS"+ macos.mkdir(parents=True)+ (macos / "Statecraft Israel").write_bytes(b"")+ assert pg.find_player(tmp_path / "m", "macos").name == "Statecraft Israel"+ with pytest.raises(ValueError, match="found 0"):+ pg.find_player(tmp_path / "w", "linux")+++def test_unpack_keeps_the_executable_bit_and_refuses_paths_that_leave_the_folder(tmp_path):+ exe = tmp_path / "Statecraft.x86_64"+ exe.write_bytes(b"#!/bin/sh\n")+ exe.chmod(0o755)+ good = tmp_path / "good.tar.gz"+ with tarfile.open(good, "w:gz") as t:+ t.add(exe, arcname="statecraft/Statecraft.x86_64")+ pg.unpack(good, tmp_path / "out")+ assert (tmp_path / "out/statecraft/Statecraft.x86_64").stat().st_mode & 0o111+ with pytest.raises(ValueError, match="not empty"):+ pg.unpack(good, tmp_path / "out")+ bad = tmp_path / "bad.tar.gz"+ with tarfile.open(bad, "w:gz") as t:+ t.add(exe, arcname="../escaped")+ with pytest.raises(tarfile.TarError):+ pg.unpack(bad, tmp_path / "out2")+ assert not (tmp_path / "escaped").exists()+ z = tmp_path / "p.zip"+ with zipfile.ZipFile(z, "w") as zf:+ zf.writestr("Statecraft/Statecraft Israel.exe", b"")+ pg.unpack(z, tmp_path / "out3")+ assert pg.find_player(tmp_path / "out3", "windows").name == "Statecraft Israel.exe"+ with pytest.raises(ValueError, match="not a .zip or .tar.gz"):+ pg.unpack(tmp_path / "good.7z", tmp_path / "out4")++[email protected](sys.platform == "win32", reason="the fake player is a shell script")+def test_run_passes_a_player_that_prints_the_goldens_and_prints_the_log_when_it_does_not(tmp_path, capsys):+ (tmp_path / "manifest.txt").write_text(MANIFEST)++ def archive(name, script):+ exe = tmp_path / "Statecraft.x86_64"+ exe.write_text("#!/bin/sh\n" + script)+ exe.chmod(0o755)+ path = tmp_path / name+ with tarfile.open(path, "w:gz") as t:+ t.add(exe, arcname="Statecraft.x86_64")+ add_notices_to_tar(t)+ return path++ # The fake player writes its log where -logFile says (the last argument), as the Unity player does.+ ok = archive("ok.tar.gz", "for a; do log=$a; done\n" + "".join(f"echo '{l}' >> \"$log\"\n" for l in EXPECTED))+ args = ["run", "--platform", "linux", "--manifest", str(tmp_path / "manifest.txt")]++ def sha(p):+ return ["--sha256", pg.sha256(p)]++ # Review S2: an archive that is not the one GitHub's digest names is refused before it is unpacked or run.+ assert pg.main(args + ["--archive", str(ok), "--sha256", "0" * 64, "--work", str(tmp_path / "w0")]) == 2+ out = capsys.readouterr().out+ assert "but GitHub's digest for the asset is" in out and not (tmp_path / "w0").exists()+ assert pg.main(args + ["--archive", str(ok), *sha(ok), "--work", str(tmp_path / "w1")]) == 0+ out = capsys.readouterr().out+ assert "PLAYER GOLDEN OK linux" in out and "ARCHIVE ok.tar.gz sha256 " in out and "-batchmode -nographics -golden -logFile" in out++ bad = archive("bad.tar.gz", "for a; do log=$a; done\necho 'GOLDEN FAIL 1950 x expected y' >> \"$log\"\nexit 1\n")+ assert pg.main(args + ["--archive", str(bad), *sha(bad), "--work", str(tmp_path / "w2")]) == 1+ out = capsys.readouterr().out+ assert "----- player log" in out and "GOLDEN FAIL 1950 x expected y" in out and "PLAYER GOLDEN FAIL linux" in out++ slow = archive("slow.tar.gz", "sleep 30\n")+ assert pg.main(args + ["--archive", str(slow), *sha(slow), "--work", str(tmp_path / "w3"), "--timeout", "1"]) == 1+ assert "did not exit before the timeout" in capsys.readouterr().out++[email protected](sys.platform != "darwin" or not shutil.which("ditto"), reason="the macOS zip is unpacked with ditto")+def test_a_mac_app_zipped_with_ditto_comes_back_runnable(tmp_path):+ # The release script zips the app with ditto -c -k --norsrc --keepParent; unpack() uses ditto -x -k on macOS.+ macos = tmp_path / "build" / "Statecraft.app" / "Contents" / "MacOS"+ macos.mkdir(parents=True)+ exe = macos / "Statecraft Israel"+ exe.write_text("#!/bin/sh\n")+ exe.chmod(0o755)+ z = tmp_path / "statecraft-israel-v0.2.0-macos-universal.zip"+ subprocess.run(["ditto", "-c", "-k", "--norsrc", "--keepParent", str(tmp_path / "build" / "Statecraft.app"), str(z)],+ check=True)+ pg.unpack(z, tmp_path / "out")+ found = pg.find_player(tmp_path / "out", "macos")+ assert found == tmp_path / "out" / "Statecraft.app" / "Contents" / "MacOS" / "Statecraft Israel"+ assert found.stat().st_mode & 0o111+++def test_the_pass_rule_matches_the_real_player_log_format():+ # Review T53 S-B: the #542 run's Mac player log carries the GOLDEN lines bare. A prefixed line, or a hash with one+ # 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]}"]+++def test_the_release_script_shares_the_asset_names_the_tag_rule_and_the_pass_rule():+ # Issue #546: tools/release_build.py takes all three from this module, so the build record and CI cannot disagree.+ import release_build as rb+ assert 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}+ 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:+ for code in (0, 1, None):+ assert (rb.golden_status(log, code, expected) == "pass") is (pg.check_log(log, EXPECTED, code) == []), (log, code)+++def fake_linux_player(tmp_path, body: bytes, name="p.tar.gz"):+ exe = tmp_path / "Statecraft.x86_64"+ exe.write_bytes(body)+ exe.chmod(0o755)+ path = tmp_path / name+ with tarfile.open(path, "w:gz") as t:+ t.add(exe, arcname="Statecraft.x86_64")+ add_notices_to_tar(t)+ return path++[email protected](sys.platform == "win32", reason="exec format errors are POSIX")+def test_a_player_that_cannot_start_fails_cleanly(tmp_path, capsys):+ (tmp_path / "manifest.txt").write_text(MANIFEST)+ arc = fake_linux_player(tmp_path, b"\x00\x01 not an executable")+ code = pg.main(["run", "--platform", "linux", "--manifest", str(tmp_path / "manifest.txt"), "--archive", str(arc),+ "--sha256", pg.sha256(arc), "--work", str(tmp_path / "w")])+ out = capsys.readouterr().out+ assert code == 1 and "::error::linux: the player could not be started" in out and "PLAYER GOLDEN FAIL linux" in out+ assert "exited" not in out and "missing line" not in out, "no made-up exit code (review T53)"+++def test_arch_is_required_for_macos_and_refused_elsewhere(tmp_path, capsys):+ (tmp_path / "manifest.txt").write_text(MANIFEST)+ arc = fake_linux_player(tmp_path, b"#!/bin/sh\n")+ base = ["run", "--manifest", str(tmp_path / "manifest.txt"), "--archive", str(arc), "--sha256", pg.sha256(arc)]+ assert pg.main(base + ["--platform", "linux", "--arch", "x86_64", "--work", str(tmp_path / "w1")]) == 2+ assert pg.main(base + ["--platform", "macos", "--work", str(tmp_path / "w2")]) == 2+ assert capsys.readouterr().out.count("--arch (arm64 or x86_64) is required for macos and only for macos") == 2+ with pytest.raises(SystemExit):+ pg.main(base + ["--platform", "macos", "--arch", "", "--work", str(tmp_path / "w3")])++[email protected](sys.platform != "darwin" or not shutil.which("ditto"), reason="needs ditto, lipo and uname")+def test_run_refuses_a_mac_runner_of_the_other_architecture_before_running(tmp_path, capsys):+ # Review T53 nit: pins the call into check_arch (the `if a.arch:` wiring), not only check_arch itself.+ (tmp_path / "manifest.txt").write_text(MANIFEST)+ macos = tmp_path / "build" / "Statecraft.app" / "Contents" / "MacOS"+ macos.mkdir(parents=True)+ shutil.copy("/usr/bin/true", macos / "Statecraft Israel")+ z = mac_release_zip(tmp_path)+ here = subprocess.run(["uname", "-m"], capture_output=True, text=True, check=True).stdout.strip()+ other = "x86_64" if here == "arm64" else "arm64"+ code = pg.main(["run", "--platform", "macos", "--arch", other, "--manifest", str(tmp_path / "manifest.txt"),+ "--archive", str(z), "--sha256", pg.sha256(z), "--work", str(tmp_path / "w")])+ out = capsys.readouterr().out+ assert code == 2 and f"the runner is {here}, not {other}: check the runner label" in out and "RUN " not in out+++def mac_release_zip(tmp_path, notices=pg.REQUIRED_NOTICES, extra=()):+ """A zip shaped like tools/release_build.py's (#552): ditto zips the .app, then the notices go in at the top level."""+ z = tmp_path / "statecraft-israel-v0.2.0-macos-universal.zip"+ subprocess.run(["ditto", "-c", "-k", "--norsrc", "--keepParent", str(tmp_path / "build" / "Statecraft.app"), str(z)],+ check=True)+ with zipfile.ZipFile(z, "a") as zf:+ for n in [*notices, *extra]:+ zf.writestr(n, f"{n}\n")+ return z+++def unpacked(tmp_path, platform, notices=pg.REQUIRED_NOTICES, extra=(), nested=False):+ """An unpacked archive shaped like #552's: the player (Windows, Linux) or the .app (macOS) plus the notices."""+ root = tmp_path / f"u-{platform}"+ base = root / "statecraft" if nested else root+ if platform == "windows":+ (base / "Statecraft_Data").mkdir(parents=True)+ (base / "UnityCrashHandler64.exe").write_bytes(b"")+ exe = base / "Statecraft Israel.exe"+ elif platform == "linux":+ (base / "Statecraft_Data").mkdir(parents=True)+ exe = base / "Statecraft.x86_64"+ else:+ (base / "Statecraft.app" / "Contents" / "MacOS").mkdir(parents=True)+ exe = base / "Statecraft.app" / "Contents" / "MacOS" / "Statecraft Israel"+ exe.write_bytes(b"")+ for n in [*notices, *extra]:+ (root / n).parent.mkdir(parents=True, exist_ok=True)+ (root / n).write_text(n)+ return root++[email protected]("platform", ["windows", "linux", "macos"])+def test_the_player_plus_the_notices_is_the_accepted_layout(tmp_path, platform):+ root = unpacked(tmp_path, platform)+ exe = pg.find_player(root, platform) # the notices are not players: LICENSES/ holds only .txt+ assert pg.layout_problems(root, platform, exe) == []++[email protected]("platform", ["windows", "linux", "macos"])+def test_a_missing_notice_or_a_nested_player_breaks_the_layout(tmp_path, platform):+ root = unpacked(tmp_path, platform, notices=[n for n in pg.REQUIRED_NOTICES if n != "LICENSES/CC0-1.0.txt"])+ assert pg.layout_problems(root, platform, pg.find_player(root, platform)) == ["missing notice: LICENSES/CC0-1.0.txt"]+ nested = unpacked(tmp_path / "n", platform, nested=True)+ problems = pg.layout_problems(nested, platform, pg.find_player(nested, platform))+ assert "not at the archive's top level" in problems[0]+++def test_nothing_but_the_notices_may_sit_beside_the_mac_app(tmp_path):+ root = unpacked(tmp_path, "macos", extra=["event-photos.json"])+ assert pg.layout_problems(root, "macos", pg.find_player(root, "macos")) == ["unexpected beside the app: event-photos.json"]+++def test_the_release_script_shares_the_notice_list_and_the_one_player_rule():+ import release_build as rb+ assert rb.REQUIRED_NOTICES is pg.REQUIRED_NOTICES and rb.NOTICE_TOPS == pg.NOTICE_TOPS+ assert set(rb.FONT_LICENCES) <= rb.NOTICE_TOPS++[email protected](sys.platform != "darwin" or not shutil.which("ditto"), reason="the macOS zip is unpacked with ditto")+def test_a_mac_release_zip_with_its_notices_unpacks_to_an_accepted_layout(tmp_path):+ macos = tmp_path / "build" / "Statecraft.app" / "Contents" / "MacOS"+ macos.mkdir(parents=True)+ (macos / "Statecraft Israel").write_bytes(b"")+ pg.unpack(mac_release_zip(tmp_path), tmp_path / "out")+ exe = pg.find_player(tmp_path / "out", "macos")+ assert pg.layout_problems(tmp_path / "out", "macos", exe) == []+ assert (tmp_path / "out" / "LICENSES" / "CC0-1.0.txt").is_file()+++def test_a_release_archive_without_its_notices_is_refused_before_the_player_runs(tmp_path, capsys):+ (tmp_path / "manifest.txt").write_text(MANIFEST)+ exe = tmp_path / "Statecraft.x86_64"+ exe.write_text("#!/bin/sh\n")+ exe.chmod(0o755)+ arc = tmp_path / "bare.tar.gz"+ with tarfile.open(arc, "w:gz") as t:+ t.add(exe, arcname="Statecraft.x86_64")+ code = pg.main(["run", "--platform", "linux", "--manifest", str(tmp_path / "manifest.txt"), "--archive", str(arc),+ "--sha256", pg.sha256(arc), "--work", str(tmp_path / "w")])+ out = capsys.readouterr().out+ assert code == 2 and "missing notice: LICENSE" in out and "RUN " not in outdiff --git a/tools/tests/test_release_build.py b/tools/tests/test_release_build.pyindex c0e106e45..57c0de223 100644--- a/tools/tests/test_release_build.py+++ b/tools/tests/test_release_build.py@@ -788,3 +788,13 @@ def test_every_shipped_fonts_licence_is_a_required_notice():for name in rb.FONT_LICENCES:assert name in rb.REQUIRED_NOTICESassert rb.FONT_LICENCES == FONT_SOURCES, "the names site/public/fonts already uses"+++def test_the_golden_rule_wants_the_exact_bare_lines_the_player_prints():+ """Review T53 S-B: the real Mac player log (the #542 run) has the GOLDEN lines bare, one per line. A prefixed line is+ not that format, and a hash with one more hex character is a different hash; both fail, as in CI (#533)."""+ expected = {"1950": H1950, "1952": H1952}+ assert rb.golden_status(f"Initialize engine\nGOLDEN OK 1950 {H1950}\r\nGOLDEN OK 1952 {H1952}\n", 0, expected) == "pass"+ assert rb.golden_status(f"12:00:01 GOLDEN OK 1950 {H1950}\n12:00:02 GOLDEN OK 1952 {H1952}\n", 0, expected) == "fail"+ assert rb.golden_status(f"GOLDEN OK 1950 {H1950}a\nGOLDEN OK 1952 {H1952}\n", 0, expected) == "fail"+ assert rb.golden_lines(f"GOLDEN OK 1950 {H1950}a\n") == [f"GOLDEN OK 1950 {H1950}a"], "the record shows what was printed"