Skip to content

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

Tools: local desktop release script and Mono Linux/Windows builds (refs #54) (#542)

Eyal Golan101095acc3d8
diff --git a/BUILDING.md b/BUILDING.md
index 4089b6026..629f66b8f 100644
--- a/BUILDING.md
+++ b/BUILDING.md
@@ -23,6 +23,9 @@ export UNITY="/Applications/Unity/Hub/Editor/6000.3.25f1/Unity.app/Contents/MacO
python3 -m http.server 8000 --directory unity/Builds/Web-disabled # then open http://localhost:8000/
```
+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).
+
A build rewrites some cached settings. Drop them afterwards with
`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bf2a084f8..4ec4e7427 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,12 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- Desktop release builds from the Mac (refs #54; Phases 0-1 of the plan in PR #482): `Build.LinuxMono` and
+ `Build.WindowsMono` build the Linux and Windows x64 players on Mono (decisions O7, O8) and put the committed IL2CPP
+ setting back afterwards, and
+ `tools/release_build.py` builds the macOS, Linux and Windows players under the machine lock, runs the player golden
+ check on the macOS player and writes a build record (commit, Unity version, UTC date, SHA-256 and size per player,
+ golden results) outside the repository. It never commits, pushes or uploads.
- The map's frame (refs #36, promo 02): at the overview the board now ends in a walnut frame on a dark wooden table,
with a bevel of cut earth where the relief stands above the frame and the frame's lip where the sea and low coast meet
it. It replaces the border skirt's flat tan slab and the sea past the map's edge. At 16:9 only the overview shows it (the
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 27ab0da48..03b90cea0 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -55,6 +55,34 @@ GitHub Releases page (and, from M4, on itch.io). Steps 1–3 are a normal pull r
folder, then run `unzip -Z1 <zip> | grep -E '^(LICENSE|NOTICE|THIRD-PARTY-NOTICES.md|OFL.txt)$'`. It must print four
lines for each zip.
+## 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`) 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. Adding the notices to the archives, signing and
+Steam upload are later steps, not yet scripted.
+
## Refreshing the README screenshots
The README's screenshots are claims about the current build. Re-take them whenever the build looks different, and
diff --git a/tools/README.md b/tools/README.md
index 4a90e65fd..3c4778ecb 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -30,6 +30,10 @@ Offline data tools (uv inline-script Python). Run from the repo root.
(exit 1) until every sensitive event is `sensitivity-reviewed` (docs/m3-release.md). The files under `Build/` are
named by their content hash (issue #437); it reads their names from the build's `index.html`, zips only those and
refuses 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
+ anywhere 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 AO
alone, imported uncompressed) and `coast.png`
diff --git a/tools/release_build.py b/tools/release_build.py
new file mode 100644
index 000000000..2e91d845e
--- /dev/null
+++ b/tools/release_build.py
@@ -0,0 +1,527 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""Build the desktop players on the owner's Mac and write a build record (refs #54; Phases 0-1 of the
+plan in PR #482, spec
+docs/superpowers/specs/2026-10-14-desktop-builds-and-release-pipeline.md, sections 6.4 and 6.5).
+
+Usage: uv run tools/release_build.py [--platform mac|linux|windows|all] [--out DIR] [--tag vX.Y.Z] [--dev] [--dry-run]
+ [--unity PATH]
+
+- Refuses, before anything is built (spec 6.4 step 1):
+ - a dirty working tree (tracked changes or untracked files);
+ - a release (no --dev) unless HEAD is on main and contained in refs/remotes/origin/main (as last fetched; the script
+ never fetches), and the tag (--tag, default v<bundleVersion>) is v<bundleVersion>[-suffix] and points at HEAD;
+ - an editor whose version (its Info.plist) is not the one in unity/ProjectSettings/ProjectVersion.txt;
+ - an --out inside any checkout of the repository (the main one and every worktree, ignored paths included, compared
+ after resolving symlinks, .. and case), or an --out that exists and is not empty.
+ A --dev build runs on any branch and commit; it takes no --tag, is not -shareable, and its archives are named
+ v<bundleVersion>-dev.<commit8>, so they can never pass for a release's assets.
+- Checks the Unity modules each selected platform needs and fails (exit 2) naming the ones to add in Unity Hub.
+- Builds the sim DLLs (tools/build_sim_for_unity.py), then each player: macOS IL2CPP (Build.Mac), Linux and Windows on
+ Mono (Build.LinuxMono, Build.WindowsMono; decisions O7 and O8). Every Unity run goes through
+ `uv run tools/machine_lock.py --shared --wait-unity`, never with -nographics, and is followed by
+ `git checkout -- unity/ProjectSettings unity/Assets/Settings` to drop the settings churn (also on an exception). Release
+ builds are -shareable (the sensitivity gate).
+- Runs the player golden check (docs/determinism.md) on the macOS player, the only one the Mac can run:
+ `-batchmode -nographics -golden -logFile <absolute>`, under the shared lock. It passes only on exit 0 with both
+ `GOLDEN OK` lines carrying the hashes pinned in sim/Statecraft.Sim.Tests/golden/manifest.txt. The Linux and Windows
+ players are recorded as unchecked, for the CI player check (spec 6.3).
+- Archives each player under the asset name the CI player check expects (PR #533's contract; ARCHIVES below):
+ statecraft-israel-<tag>-macos-universal.zip (ditto --norsrc, the .app alone), statecraft-israel-<tag>-linux-x64.tar.gz and
+ statecraft-israel-<tag>-windows-x64.zip. It checks first that the folder holds exactly one player executable. An
+ archive holds the player only: not Unity's *_DoNotShip folders, and not event-photos.json, the build's photo manifest
+ (packaging evidence the player never reads), which is copied beside the record as event-photos-<platform>.json.
+- Writes build-record.json, build-record.md and files-<platform>.sha256: one `shasum -a 256` line per file the archive
+ holds, so `shasum -a 256 -c` run where the archive was unpacked checks every file. The record carries the SHA-256 and
+ size of each archive and file list, and whether the tree was still clean after the builds.
+
+The output folder defaults to ~/statecraft-release/v<version>-<commit>-<UTC stamp>/: outside every worktree, so removing
+a worktree or cleaning unity/Builds cannot take a release with it, and outside git, so nothing in it can be committed
+by accident. Build records live in the owner's
+separate records repository (decision O12): this script never commits, pushes or uploads anything; it prints where the
+record is, and the owner copies it.
+
+Exit 0 when every build succeeded and every check that ran passed; 1 on a refusal, a failed build or a failed golden
+(the record is still written for a failed golden); 2 when the editor or a module is missing.
+"""
+import argparse
+import hashlib
+import json
+import os
+import plistlib
+import re
+import subprocess
+import sys
+import tarfile
+import time
+import zipfile
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+
+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 machine
+HUB = "/Applications/Unity Hub.app/Contents/MacOS/Unity Hub"
+METHOD = "Statecraft.Game.EditorTools.Build."
+PHOTOS = "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
+
+
+@dataclass(frozen=True)
+class Platform:
+ name: str
+ method: str # Build.<method>
+ build_target: str # Unity's -buildTarget
+ backend: str
+ module_id: str # Unity Hub's module id
+ module_name: str
+ module_dir: str # where the module lives, relative to the editor folder (modules.json's destination)
+ output: str # the player's path inside players/<name>/
+ runs_here: bool # whether the Mac can run this player's golden check
+
+
+PLATFORMS = {
+ "mac": Platform("mac", "Mac", "OSXUniversal", "IL2CPP", "mac-il2cpp", "Mac Build Support (IL2CPP)",
+ "Unity.app/Contents/PlaybackEngines/MacStandaloneSupport", "Statecraft.app", True),
+ "linux": Platform("linux", "LinuxMono", "Linux64", "Mono", "linux-mono", "Linux Build Support (Mono)",
+ "PlaybackEngines/LinuxStandaloneSupport", "Statecraft.x86_64", False),
+ "windows": Platform("windows", "WindowsMono", "Win64", "Mono", "windows-mono", "Windows Build Support (Mono)",
+ "PlaybackEngines/WindowsStandaloneSupport", "Statecraft.exe", False),
+}
+
+
+@dataclass
+class Result:
+ returncode: int
+ stdout: str = ""
+
+
+def run(cmd: list, **kw) -> Result:
+ """The one place a process is started (tests replace it). Output is captured only when asked for."""
+ capture = kw.pop("capture", False)
+ p = subprocess.run([str(c) for c in cmd], text=True, capture_output=capture, **kw)
+ return Result(p.returncode, p.stdout if capture else "")
+
+
+def utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def parse(argv: list[str]) -> argparse.Namespace:
+ ap = argparse.ArgumentParser(description="Build the desktop players and write a build record (never pushes).")
+ ap.add_argument("--platform", choices=["mac", "linux", "windows", "all"], default="all")
+ ap.add_argument("--out", type=Path, default=None, help="output folder (default ~/statecraft-release/<run>)")
+ ap.add_argument("--dev", action="store_true", help="a development build: no -shareable, so not for sharing")
+ ap.add_argument("--dry-run", action="store_true", help="check, then print the commands without running them")
+ ap.add_argument("--tag", default=None, help="the release tag in the archive names, v included (default "
+ "v<bundleVersion>)")
+ ap.add_argument("--unity", type=Path, default=None, help="the Unity executable (default: the Hub path of the "
+ "version in ProjectVersion.txt)")
+ return ap.parse_args(argv)
+
+
+def selected(a: argparse.Namespace) -> list[str]:
+ return list(PLATFORMS) if a.platform == "all" else [a.platform]
+
+
+# --- what the repository says ------------------------------------------------------------------------------------------
+
+def unity_version() -> tuple[str, str]:
+ text = (REPO / "unity/ProjectSettings/ProjectVersion.txt").read_text()
+ m = re.search(r"m_EditorVersionWithRevision:\s*(\S+)\s*\((\w+)\)", text)
+ if not m:
+ raise SystemExit("cannot read the Unity version from unity/ProjectSettings/ProjectVersion.txt")
+ return m.group(1), m.group(2)
+
+
+def versions() -> dict:
+ bundle = re.search(r"^\s*bundleVersion:\s*(\S+)", (REPO / "unity/ProjectSettings/ProjectSettings.asset").read_text(), re.M)
+ sim = re.search(r'Version\s*=\s*"([^"]+)"', (REPO / "sim/Statecraft.Sim/SimInfo.cs").read_text())
+ return {"bundle_version": bundle.group(1) if bundle else None, "sim_version": sim.group(1) if sim else None}
+
+
+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()
+ return pins
+
+
+def editor_version(unity: Path) -> tuple[str, str] | None:
+ """(version, revision) from the editor's Info.plist ("Unity version 6000.3.25f1 (e1dba0a9aba4). ..."), or None."""
+ try:
+ with open(unity.parents[1] / "Info.plist", "rb") as f:
+ info = plistlib.load(f).get("CFBundleGetInfoString", "")
+ except (OSError, plistlib.InvalidFileException):
+ return None
+ m = re.search(r"Unity version (\S+) \((\w+)\)", info)
+ return (m.group(1), m.group(2)) if m else None
+
+
+def default_out(commit: str, version: str, stamp: str) -> Path:
+ return Path.home() / "statecraft-release" / f"v{version}-{commit[:8]}-{stamp}"
+
+
+# --- checks --------------------------------------------------------------------------------------------------------------
+
+def git(*args: str) -> Result:
+ return run(["git", *args], cwd=REPO, capture=True)
+
+
+def dirty_lines() -> list[str]:
+ return [l for l in git("status", "--porcelain", "--untracked-files=normal").stdout.splitlines() if l.strip()]
+
+
+def missing_modules(names: list[str], editor_root: Path) -> list[Platform]:
+ return [PLATFORMS[n] for n in names if not (editor_root / PLATFORMS[n].module_dir).is_dir()]
+
+
+def modules_message(missing: list[Platform], version: str) -> str:
+ rows = "\n".join(f" - {p.module_name} (Unity Hub module id {p.module_id}), for --platform {p.name}" for p in missing)
+ ids = " ".join(f"-m {p.module_id}" for p in missing)
+ return (f"MISSING UNITY MODULES for Unity {version}:\n{rows}\n"
+ f"Add them in Unity Hub (Installs > {version} > Manage > Add modules), or from the command line:\n"
+ f' "{HUB}" -- --headless install-modules -v {version} {ids}\n'
+ "Nothing was built.")
+
+
+def checkouts() -> list[Path]:
+ """This checkout, the main one and every worktree of the repository."""
+ listed = git("worktree", "list", "--porcelain").stdout.splitlines()
+ return [REPO, *(Path(l[len("worktree "):]) for l in listed if l.startswith("worktree "))]
+
+
+def canonical(path: Path) -> str:
+ """The path with symlinks (dangling ones included), .. and, for APFS, which ignores case, case resolved."""
+ return os.path.realpath(os.path.abspath(path)).casefold()
+
+
+def inside_a_checkout(out: Path) -> Path | None:
+ """The checkout that contains out, or None. Ignored paths count: ContentSync deletes
+ unity/Assets/StreamingAssets/content on every build, and unity/Library and unity/Builds belong to Unity."""
+ target = canonical(out)
+ for root in checkouts():
+ r = canonical(root)
+ if target == r or target.startswith(r.rstrip(os.sep) + os.sep):
+ return root
+ return None
+
+
+# --- commands ------------------------------------------------------------------------------------------------------------
+
+def locked(cmd: list, wait_unity: bool) -> list[str]:
+ head = ["uv", "run", str(REPO / "tools/machine_lock.py"), "--shared"]
+ if wait_unity:
+ head.append("--wait-unity")
+ return [*head, "--timeout", str(LOCK_TIMEOUT), "--", *[str(c) for c in cmd]]
+
+
+def build_command(unity: Path, p: Platform, target: Path, log: Path, shareable: bool) -> list[str]:
+ cmd = [str(unity), "-batchmode", "-CI", "false", "-GITHUB_ACTIONS", "false", "-TF_BUILD", "false", "-quit",
+ "-projectPath", str(REPO / "unity"), "-buildTarget", p.build_target, "-executeMethod", METHOD + p.method,
+ "-out", str(target), "-logFile", str(log)]
+ if shareable:
+ cmd.append("-shareable")
+ return locked(cmd, wait_unity=True)
+
+
+def mac_executable(app: Path) -> Path:
+ with open(app / "Contents/Info.plist", "rb") as f:
+ return app / "Contents/MacOS" / plistlib.load(f)["CFBundleExecutable"]
+
+
+def golden_command(player: Path, log: Path) -> list[str]:
+ # A player, not the editor: docs/determinism.md runs it -batchmode -nographics, with an absolute -logFile.
+ return locked([str(player), "-batchmode", "-nographics", "-golden", "-logFile", str(log.resolve())], wait_unity=False)
+
+
+# --- 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)]
+
+
+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"
+
+
+def archive_name(tag: str, platform: str) -> str:
+ return ARCHIVES[platform].format(tag=tag)
+
+
+def make_archive(p: Platform, folder: Path, target: Path, dest: Path) -> None:
+ """The release archive of one player folder. macOS: ditto keeps the bundle (modes, links), and the zip holds the
+ .app alone. Linux: tar keeps the executable bit. Windows: a zip of the folder."""
+ if p.name == "mac":
+ # --norsrc: no AppleDouble ._* entries, which unzip would leave as files the file list does not name.
+ if run(["ditto", "-c", "-k", "--norsrc", "--keepParent", str(target), str(dest)]).returncode != 0:
+ raise SystemExit(f"ditto failed for {target}")
+ elif p.name == "linux":
+ with tarfile.open(dest, "w:gz") as t:
+ for path in shipped(folder):
+ t.add(path, arcname=path.relative_to(folder).as_posix(), recursive=False)
+ else:
+ with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z:
+ for path in shipped(folder):
+ z.write(path, path.relative_to(folder).as_posix())
+
+
+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)}"
+
+
+def file_sha256(path: Path) -> str:
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def unity_seconds(log_text: str) -> int | None:
+ m = re.search(r"BUILD Succeeded \S+ -> .*?, (\d+)s", log_text)
+ return int(m.group(1)) if m else None
+
+
+def shipped(folder: Path) -> list[Path]:
+ """Every path under folder that is part of the player, sorted: Unity's own *_DoNotShip and
+ *_ButDontShipItWithYourGame folders (IL2CPP sources, Burst debug data) and the photo manifest are left out."""
+ def skip(path: Path) -> bool:
+ top = path.relative_to(folder).parts[0]
+ return top.endswith("_DoNotShip") or top.endswith("_ButDontShipItWithYourGame") or top == PHOTOS
+ return sorted(p for p in folder.rglob("*") if not skip(p))
+
+
+def tree_manifest(folder: Path) -> tuple[str, int, int]:
+ """`shasum -a 256` lines for every file under folder, sorted by path; a symlink is listed by its target, not
+ followed (`shasum -c` skips such a line with a warning); the do-not-ship folders are left out. Returns the text, the number of entries and the bytes of the regular files."""
+ rows, size = [], 0
+ for path in shipped(folder):
+ rel = path.relative_to(folder).as_posix()
+ if path.is_symlink():
+ rows.append((rel, f"symlink {rel} -> {os.readlink(path)}"))
+ elif path.is_file():
+ size += path.stat().st_size
+ rows.append((rel, f"{file_sha256(path)} {rel}"))
+ rows.sort(key=lambda r: r[0])
+ return "".join(line + "\n" for _, line in rows), len(rows), size
+
+
+def markdown(r: dict) -> str:
+ out = [f"# Build record: Statecraft: Israel {r['version']['bundle_version']} ({r['commit'][:8]})", "",
+ f"- Commit: `{r['commit']}` ({r['describe']}, branch {r['branch']}); tree clean before the builds: "
+ f"{r['tree_clean']}, after: {r['tree_clean_after_builds']}"
+ + (f" ({'; '.join(r['dirty_after_builds'])})" if r["dirty_after_builds"] else ""),
+ f"- {'Release' if r['release'] else 'Development build, not a release'}: tag `{r['tag']}`",
+ f"- Date (UTC): {r['date_utc']}",
+ f"- Unity: {r['unity']['version']} ({r['unity']['revision']})",
+ f"- Version: bundleVersion {r['version']['bundle_version']}, SimInfo.Version {r['version']['sim_version']}",
+ f"- Shareable build: {r['shareable']}" + ("" if r["shareable"] else " (a --dev build: not for sharing)"),
+ f"- Signing: {r['signing']}", "",
+ "| Platform | Backend | Architecture | Archive | Archive bytes | Archive SHA-256 | Player files | Player bytes "
+ "| File list SHA-256 | Golden |",
+ "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |"]
+ for a in r["artifacts"]:
+ ar = a["archive"]
+ out.append(f"| {a['platform']} | {a['backend']} | {a['architecture'] or '-'} | `{ar['name']}` | {ar['bytes']} | "
+ f"`{ar['sha256']}` | {a['files']} | {a['bytes']} | `{a['file_list_sha256']}` | {a['golden']['status']} |")
+ out.append("")
+ for a in r["artifacts"]:
+ g = a["golden"]
+ out.append(f"- {a['platform']}: {g['status']}" + (f", exit {g['exit_code']}" if g["exit_code"] is not None else "")
+ + (f"; {g['note']}" if g.get("note") else ""))
+ out.extend(f" - `{line}`" for line in g["lines"])
+ out += ["", "The archive is the release asset. Each file list (`" + "`, `".join(a["file_list"] for a in r["artifacts"])
+ + "`) names exactly the files its archive holds; `shasum -a 256 -c` on it, run where the archive was "
+ "unpacked, checks every regular file (it skips `symlink` lines, which give a link's target instead). The build's photo manifest is kept beside the record "
+ "(`event-photos-<platform>.json`), not in the archive.",
+ "Steam build ID: (added by the owner after an upload).", ""]
+ return "\n".join(out)
+
+
+# --- the run -------------------------------------------------------------------------------------------------------------
+
+def main(argv: list[str] | None = None) -> int:
+ a = parse(sys.argv[1:] if argv is None else argv)
+ names = selected(a)
+ version, revision = unity_version()
+ unity = a.unity or Path(f"/Applications/Unity/Hub/Editor/{version}/Unity.app/Contents/MacOS/Unity")
+ if not unity.is_file():
+ print(f"NO UNITY EDITOR at {unity}: install Unity {version} ({revision}) through Unity Hub (docs/dev-setup.md)",
+ file=sys.stderr)
+ return 2
+ found = editor_version(unity)
+ if found != (version, revision):
+ have = f"{found[0]} ({found[1]})" if found else "an unknown version"
+ print(f"REFUSED: {unity} is Unity {have}, but unity/ProjectSettings/ProjectVersion.txt asks for {version} "
+ f"({revision}); the record names the project's version, so build with that editor.", file=sys.stderr)
+ return 1
+ editor_root = unity.parents[3] # <version>/Unity.app/Contents/MacOS/Unity
+ missing = missing_modules(names, editor_root)
+ if missing:
+ print(modules_message(missing, version), file=sys.stderr)
+ return 2
+ dirty = dirty_lines()
+ if dirty:
+ print("REFUSED: the working tree is not clean. A build record names a commit, so build only a committed tree.\n"
+ + "\n".join(" " + l for l in dirty)
+ + "\nAfter a Unity run, `git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset` "
+ "drops the settings churn (and the UNITY_MCP_* defines).", file=sys.stderr)
+ return 1
+
+ commit = git("rev-parse", "HEAD").stdout.strip()
+ branch = git("rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
+ describe = git("describe", "--tags", "--always", "--dirty").stdout.strip()
+ vers = versions()
+ started = utc_now()
+ release = not a.dev
+ if release:
+ tag = a.tag or f"v{vers['bundle_version']}"
+ if not TAG.fullmatch(tag):
+ print(f"REFUSED: {tag!r} is not a release tag (vX.Y.Z)", file=sys.stderr)
+ return 1
+ if tag != f"v{vers['bundle_version']}" and not tag.startswith(f"v{vers['bundle_version']}-"):
+ print(f"REFUSED: the tag {tag} is not bundleVersion {vers['bundle_version']} (v{vers['bundle_version']}, "
+ "optionally with a -suffix); the archives would name a version the player does not carry.",
+ file=sys.stderr)
+ return 1
+ if branch != "main":
+ where = "HEAD is detached; check out main" if branch == "HEAD" else f"not on {branch!r}"
+ print(f"REFUSED: a release is built on main ({where}; spec 6.4 step 1). Use --dev for a test build.",
+ file=sys.stderr)
+ return 1
+ if git("merge-base", "--is-ancestor", "HEAD", "refs/remotes/origin/main").returncode != 0:
+ print(f"REFUSED: HEAD ({commit[:8]}) is not on origin/main as this checkout last saw it; a release is a "
+ "reviewed commit on GitHub's main. Run `git fetch origin` (this script never does) and check that "
+ "your main matches origin/main.", file=sys.stderr)
+ return 1
+ if tag not in git("tag", "--points-at", "HEAD").stdout.split():
+ print(f"REFUSED: the tag {tag} does not point at HEAD ({commit[:8]}); tag the release commit first, or use "
+ "--dev for a test build.", file=sys.stderr)
+ return 1
+ else:
+ if a.tag:
+ print("REFUSED: a --dev build takes no --tag; its archives are named v<bundleVersion>-dev.<commit>.",
+ file=sys.stderr)
+ return 1
+ tag = f"v{vers['bundle_version']}-dev.{commit[:8]}"
+ out = (a.out or default_out(commit, vers["bundle_version"] or "0", started.strftime("%Y%m%dT%H%M%SZ"))).absolute()
+ if (root := inside_a_checkout(out)) is not None:
+ print(f"REFUSED: {out} is inside the checkout {root}; choose a folder outside every checkout of the repository "
+ "(the default is ~/statecraft-release/).", file=sys.stderr)
+ return 1
+ if out.exists() and (not out.is_dir() or any(out.iterdir())):
+ print(f"REFUSED: {out} exists and is not empty; a release folder starts empty.", file=sys.stderr)
+ return 1
+ shareable = release
+ plan = [(PLATFORMS[n], out / "players" / n / PLATFORMS[n].output, out / "logs" / f"unity-build-{n}.log") for n in names]
+ sim = [sys.executable, str(REPO / "tools/build_sim_for_unity.py")]
+ if a.dry_run:
+ print("DRY RUN: nothing is built or written.\n" + " ".join(sim))
+ for p, target, log in plan:
+ print(" ".join(f'"{c}"' if " " in c else c for c in build_command(unity, p, target, log, shareable)))
+ print("git checkout -- unity/ProjectSettings unity/Assets/Settings")
+ print(f"archive: {out / archive_name(tag, p.name)}")
+ if p.runs_here:
+ print(" ".join(golden_command(target / "Contents/MacOS/<CFBundleExecutable>", out / "logs/golden-mac.log")))
+ print(f"record: {out / 'build-record.json'}")
+ return 0
+
+ (out / "logs").mkdir(parents=True, exist_ok=True)
+ if run(sim, cwd=REPO).returncode != 0:
+ print("FAILED: tools/build_sim_for_unity.py", file=sys.stderr)
+ return 1
+ expected = expected_goldens()
+ artifacts, all_ok = [], True
+ for p, target, log in plan:
+ print(f"release_build: building {p.name} ({p.backend}) -> {target}", flush=True)
+ t0 = time.monotonic()
+ try:
+ code = run(build_command(unity, p, target, log, shareable), cwd=REPO).returncode
+ finally:
+ run(["git", "checkout", "--", "unity/ProjectSettings", "unity/Assets/Settings"], cwd=REPO)
+ wall = round(time.monotonic() - t0)
+ log_text = log.read_text(errors="replace") if log.exists() else ""
+ if code != 0 or not target.exists():
+ print(f"FAILED: the {p.name} build (exit {code}); see {log}", file=sys.stderr)
+ return 1
+ folder = out / "players" / p.name
+ text, files, size = tree_manifest(folder)
+ listing = out / f"files-{p.name}.sha256"
+ listing.write_text(text)
+ photos = None
+ if (folder / PHOTOS).is_file():
+ copy = out / f"event-photos-{p.name}.json"
+ copy.write_bytes((folder / PHOTOS).read_bytes())
+ photos = {"file": copy.name, "sha256": file_sha256(copy)}
+ if problem := player_problem(p, folder):
+ print(f"FAILED: {problem}", file=sys.stderr)
+ return 1
+ archive = out / archive_name(tag, p.name)
+ make_archive(p, folder, target, archive)
+ arch = None
+ if p.name == "mac":
+ arch = run(["lipo", "-archs", str(mac_executable(target))], capture=True).stdout.strip() or None
+ golden = {"status": "unchecked", "exit_code": None, "lines": [],
+ "note": "this player cannot run on the Mac; the CI player golden check runs it (spec 6.3)"}
+ if p.runs_here:
+ glog = out / "logs" / f"golden-{p.name}.log"
+ gcode = run(golden_command(mac_executable(target), glog), cwd=REPO).returncode
+ gtext = glog.read_text(errors="replace") if glog.exists() else ""
+ golden = {"status": golden_status(gtext, gcode, expected), "exit_code": gcode, "lines": golden_lines(gtext),
+ "log": str(glog.relative_to(out))}
+ all_ok &= golden["status"] == "pass"
+ artifacts.append({"platform": p.name, "build_target": p.build_target, "backend": p.backend,
+ "architecture": arch, "build_method": METHOD + p.method,
+ "path": str(target.relative_to(out)), "files": files, "bytes": size,
+ "archive": {"name": archive.name, "bytes": archive.stat().st_size,
+ "sha256": file_sha256(archive)},
+ "file_list_sha256": file_sha256(listing), "file_list": listing.name,
+ "photo_manifest": photos,
+ "unity_build_seconds": unity_seconds(log_text), "wall_seconds_with_lock_wait": wall,
+ "unity_log": str(log.relative_to(out)), "golden": golden})
+
+ dirty_after = [l.strip() for l in dirty_lines()]
+ record = {"schema": 1, "tool": "tools/release_build.py", "commit": commit,
+ "describe": describe, "branch": branch, "release": release,
+ "tree_clean": True, # checked before the builds: a dirty tree is refused
+ "tree_clean_after_builds": not dirty_after, "dirty_after_builds": dirty_after,
+ "date_utc": started.strftime("%Y-%m-%dT%H:%M:%SZ"), "unity": {"version": version, "revision": revision},
+ "version": vers, "tag": tag, "shareable": shareable, "signing": "none", "golden_expected": expected,
+ "artifacts": artifacts, "steam_build_id": None}
+ (out / "build-record.json").write_text(json.dumps(record, indent=2) + "\n")
+ (out / "build-record.md").write_text(markdown(record))
+ print(f"RECORD {out / 'build-record.json'}\nRECORD {out / 'build-record.md'}")
+ for a_ in artifacts:
+ print(f"{a_['archive']['name']}: sha256 {a_['archive']['sha256']}, {a_['archive']['bytes']} bytes, "
+ f"golden {a_['golden']['status']}")
+ print("Nothing was pushed or uploaded. Copy the record files to the build records repository.")
+ return 0 if all_ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/tests/test_release_build.py b/tools/tests/test_release_build.py
new file mode 100644
index 000000000..0d422a4e3
--- /dev/null
+++ b/tools/tests/test_release_build.py
@@ -0,0 +1,673 @@
+"""tools/release_build.py: the local desktop release script (#482 Phases 0-1). Every subprocess (git, Unity, the player,
+the lock) is faked; nothing here starts Unity or touches the network."""
+import hashlib
+import json
+from pathlib import Path
+
+import pytest
+
+import release_build as rb
+
+H1950 = "71e9904d0ee48083db9bbba281f3f046136482ba83ee056e48d57b62e76a5b07"
+H1952 = "62f8ec61a14acff4eab503381994a7c94d7a2f786dcfde5c4c19439ac8b4c5e8"
+SHA = "1b7a36cb" + "0" * 32
+
+
+def repo(tmp_path):
+ """A minimal repository tree with the files the script reads."""
+ root = tmp_path / "repo"
+ (root / "unity/ProjectSettings").mkdir(parents=True)
+ (root / "unity/ProjectSettings/ProjectVersion.txt").write_text(
+ "m_EditorVersion: 6000.3.25f1\nm_EditorVersionWithRevision: 6000.3.25f1 (e1dba0a9aba4)\n")
+ (root / "unity/ProjectSettings/ProjectSettings.asset").write_text("PlayerSettings:\n bundleVersion: 0.1.0\n")
+ (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")
+ return root
+
+
+def editor(tmp_path):
+ """A fake Unity install with every module of the three platforms; tests remove one to make it missing."""
+ root = tmp_path / "Editor" / "6000.3.25f1"
+ exe = root / "Unity.app/Contents/MacOS/Unity"
+ exe.parent.mkdir(parents=True)
+ exe.write_text("")
+ write_editor_version(exe, "6000.3.25f1 (e1dba0a9aba4)")
+ for module in rb.PLATFORMS.values():
+ (root / module.module_dir).mkdir(parents=True, exist_ok=True)
+ return exe
+
+
+def write_editor_version(exe, version):
+ (exe.parents[1] / "Info.plist").write_bytes(
+ b'<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict><key>CFBundleGetInfoString</key>'
+ + f"<string>Unity version {version}. (c) 2005-2026 Unity Technologies.</string></dict></plist>".encode())
+
+
+class Fake:
+ """Records every command and plays git, Unity and the player."""
+
+ def __init__(self, dirty="", golden_ok=True, build_ok=True, branch="main", tags=("v0.1.0",), worktrees=None,
+ build_raises=None, dirty_after="", on_origin_main=True):
+ self.calls: list[list[str]] = []
+ self.dirty, self.golden_ok, self.build_ok = dirty, golden_ok, build_ok
+ self.branch, self.tags, self.worktrees = branch, tags, worktrees
+ self.build_raises, self.dirty_after, self.built = build_raises, dirty_after, False
+ self.on_origin_main = on_origin_main
+
+ def __call__(self, cmd, **kw):
+ cmd = [str(c) for c in cmd]
+ self.calls.append(cmd)
+ out, code = "", 0
+ if cmd[:2] == ["git", "status"]:
+ out = self.dirty_after if self.built else self.dirty
+ elif cmd[:2] == ["git", "rev-parse"]:
+ out = self.branch + "\n" if "--abbrev-ref" in cmd else SHA + "\n"
+ elif cmd[:2] == ["git", "merge-base"]:
+ code = 0 if self.on_origin_main else 1
+ elif cmd[:3] == ["git", "tag", "--points-at"]:
+ out = "".join(t + "\n" for t in self.tags)
+ elif cmd[:3] == ["git", "worktree", "list"]:
+ out = "".join(f"worktree {w}\nHEAD {SHA}\nbranch refs/heads/x\n\n" for w in self.worktrees or [])
+ elif cmd[:2] == ["git", "describe"]:
+ out = "v0.1.0-5-g1b7a36cb\n"
+ elif cmd[:2] == ["git", "check-ignore"]:
+ code = 0 # as if git ignored every path: being ignored must not make a folder in a checkout acceptable
+ elif "-executeMethod" in cmd:
+ self.built = True
+ if self.build_raises:
+ raise self.build_raises
+ target = Path(cmd[cmd.index("-out") + 1])
+ log = Path(cmd[cmd.index("-logFile") + 1])
+ if target.suffix == ".app":
+ (target / "Contents/MacOS").mkdir(parents=True)
+ (target / "Contents/Info.plist").write_bytes(
+ b'<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>'
+ b"<key>CFBundleExecutable</key><string>Statecraft Israel</string></dict></plist>")
+ (target / "Contents/MacOS/Statecraft Israel").write_bytes(b"player")
+ else:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(b"player " + target.name.encode())
+ (target.parent / "event-photos.json").write_text("{}\n")
+ log.write_text("BUILD Succeeded StandaloneOSX -> x: 1.0 MB on disk, 0 errors, 321s\n")
+ if not self.build_ok: # Unity failed, but a (partial or older) player is still there
+ log.write_text("BUILD Failed StandaloneOSX -> x: 0.0 MB on disk, 3 errors, 12s\n")
+ code = 1
+ elif "-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")
+ code = 0 if self.golden_ok else 1
+ elif cmd[0] == "ditto":
+ Path(cmd[-1]).write_bytes(b"PK mac zip of " + Path(cmd[-2]).name.encode())
+ elif cmd[0] == "lipo":
+ out = "x86_64 arm64\n"
+ return rb.Result(code, out)
+
+
+def run_main(argv, repo, editor, fake, monkeypatch):
+ monkeypatch.setattr(rb, "REPO", repo)
+ monkeypatch.setattr(rb, "run", fake)
+ if fake.worktrees is None:
+ fake.worktrees = [repo]
+ return rb.main(["--unity", str(editor), *argv])
+
+
+def unity_calls(fake):
+ return [c for c in fake.calls if "-executeMethod" in c]
+
+
+# --- arguments ---------------------------------------------------------------------------------------------------------
+
+def test_the_platform_flag_selects_one_or_all():
+ assert rb.selected(rb.parse(["--platform", "mac"])) == ["mac"]
+ assert rb.selected(rb.parse(["--platform", "all"])) == ["mac", "linux", "windows"]
+ assert rb.selected(rb.parse([])) == ["mac", "linux", "windows"], "a release builds every platform by default"
+ with pytest.raises(SystemExit):
+ rb.parse(["--platform", "ios"])
+
+
+def test_out_dry_run_and_dev_are_flags():
+ a = rb.parse(["--out", "/tmp/x", "--dry-run", "--dev"])
+ assert a.out == Path("/tmp/x") and a.dry_run and a.dev
+ a = rb.parse([])
+ assert a.out is None and not a.dry_run and not a.dev
+
+
+def test_the_default_output_folder_is_outside_the_repository(repo):
+ out = rb.default_out(SHA, "0.1.0", "20261014T120000Z")
+ assert out == Path.home() / "statecraft-release" / "v0.1.0-1b7a36cb-20261014T120000Z"
+ assert not out.is_relative_to(rb.REPO)
+
+
+def test_an_output_folder_inside_the_repository_is_refused(repo, editor, monkeypatch):
+ fake = Fake()
+ assert run_main(["--platform", "mac", "--out", str(repo / "builds")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+
+
[email protected]("inside", ["unity/Assets/StreamingAssets/content/r", "unity/Library/out", "unity/Builds/r",
+ ".worktrees/x/out"])
+def test_an_ignored_folder_inside_the_repository_is_refused_too(repo, editor, monkeypatch, inside):
+ """Ignored is not safe: ContentSync deletes StreamingAssets/content on every build (ContentManifest.cs), which would
+ take an earlier platform's player with it (review of #542, item 2 and mutation M4)."""
+ fake = Fake()
+ assert run_main(["--platform", "all", "--out", str(repo / inside)], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+
+
+def test_the_contentsync_wipe_cannot_reach_the_output(repo, editor, monkeypatch):
+ """--platform all into StreamingAssets/content: refused before the first build, so no later build can wipe it."""
+ fake = Fake()
+ out = repo / "unity/Assets/StreamingAssets/content/r"
+ assert run_main(["--platform", "all", "--out", str(out)], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == [] and not out.exists()
+
+
+def test_a_case_variant_of_the_repository_path_is_refused(repo, editor, monkeypatch):
+ """APFS is case-insensitive: /…/REPO/unity/Assets/out is the repository's own unity/Assets."""
+ fake = Fake()
+ variant = Path(str(repo).upper()) / "unity/Assets/out"
+ assert run_main(["--platform", "mac", "--out", str(variant)], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+
+
+def test_a_dotdot_or_symlink_into_the_repository_is_refused(repo, editor, monkeypatch, tmp_path):
+ link = tmp_path / "link"
+ link.symlink_to(repo / "unity")
+ for out in (link / "Assets/out", tmp_path / "elsewhere/../repo/unity/x"):
+ fake = Fake()
+ assert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 1, out
+ assert unity_calls(fake) == []
+
+
+def test_every_checkout_of_the_repository_is_refused(repo, editor, monkeypatch, tmp_path):
+ """The main checkout and every other worktree, from `git worktree list --porcelain`, not only the running one."""
+ main, other = tmp_path / "main-checkout", tmp_path / "wt" / "other"
+ for root in (main, other):
+ (root / "unity/Assets").mkdir(parents=True)
+ for out in (main / "unity/Assets/rel", other / "unity/Assets/rel", main / "x"):
+ fake = Fake(worktrees=[main, repo, other])
+ assert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 1, out
+ assert unity_calls(fake) == []
+
+
+def test_a_non_empty_output_folder_is_refused(repo, editor, monkeypatch, tmp_path):
+ out = tmp_path / "out"
+ (out / "players/linux").mkdir(parents=True)
+ (out / "players/linux/stale.so").write_bytes(b"old")
+ fake = Fake()
+ assert run_main(["--platform", "linux", "--out", str(out)], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+ empty = tmp_path / "empty"
+ empty.mkdir()
+ assert run_main(["--platform", "mac", "--out", str(empty)], repo, editor, Fake(), monkeypatch) == 0
+
+
+# --- a release is main at its tag (spec 6.4 step 1) -------------------------------------------------------------------
+
+def test_a_release_off_main_is_refused(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = Fake(branch="tools/feature", tags=("v0.1.0",))
+ assert run_main(["--platform", "mac", "--tag", "v0.1.0", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == [] and "main" in capsys.readouterr().err
+
+
+def test_a_release_whose_tag_is_not_at_head_is_refused(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = Fake(branch="main", tags=("v0.0.9",))
+ assert run_main(["--platform", "mac", "--tag", "v0.1.0", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == [] and "v0.1.0" in capsys.readouterr().err
+ fake = Fake(branch="main", tags=())
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "p")], repo, editor, fake, monkeypatch) == 1, \
+ "the default tag v<bundleVersion> must be at HEAD too"
+
+
+def test_a_release_on_main_at_its_tag_runs(repo, editor, monkeypatch, tmp_path):
+ fake = Fake(branch="main", tags=("v0.1.0-rc.2", "other"))
+ out = tmp_path / "o"
+ assert run_main(["--platform", "mac", "--tag", "v0.1.0-rc.2", "--out", str(out)], repo, editor, fake, monkeypatch) == 0
+ assert (out / "statecraft-israel-v0.1.0-rc.2-macos-universal.zip").exists()
+
+
+def test_a_dev_build_runs_anywhere_under_a_dev_marked_name(repo, editor, monkeypatch, tmp_path):
+ """--dev: any branch, no tag needed, never a release name: v<bundleVersion>-dev.<commit8>, and no -shareable."""
+ fake = Fake(branch="tools/feature", tags=())
+ out = tmp_path / "o"
+ assert run_main(["--platform", "mac", "--dev", "--out", str(out)], repo, editor, fake, monkeypatch) == 0
+ assert (out / "statecraft-israel-v0.1.0-dev.1b7a36cb-macos-universal.zip").exists()
+ record = json.loads((out / "build-record.json").read_text())
+ assert record["tag"] == "v0.1.0-dev.1b7a36cb" and record["release"] is False and record["branch"] == "tools/feature"
+
+
+def test_a_dev_build_takes_no_release_tag(repo, editor, monkeypatch, tmp_path):
+ fake = Fake(branch="main", tags=("v1.0.0",))
+ assert run_main(["--platform", "mac", "--dev", "--tag", "v1.0.0", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+
+
+# --- the editor must be the project's version -------------------------------------------------------------------------
+
+def test_an_editor_of_another_version_is_refused(repo, editor, monkeypatch, tmp_path, capsys):
+ write_editor_version(editor, "6000.4.1f1 (0123456789ab)")
+ for extra in ([], ["--dev"]):
+ fake = Fake()
+ assert run_main(["--platform", "mac", *extra, "--out", str(tmp_path / f"o{len(extra)}")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+ err = capsys.readouterr().err
+ assert "6000.4.1f1" in err and "6000.3.25f1" in err
+
+
+def test_the_editor_version_is_read_from_its_info_plist(editor):
+ assert rb.editor_version(editor) == ("6000.3.25f1", "e1dba0a9aba4")
+
+
+# --- the mutants that survived the review ------------------------------------------------------------------------------
+
+def test_the_settings_are_restored_when_the_build_call_raises(repo, editor, monkeypatch, tmp_path):
+ """Mutation M2: the try/finally around the build. A Ctrl-C while Unity runs still drops the settings churn."""
+ fake = Fake(build_raises=KeyboardInterrupt())
+ with pytest.raises(KeyboardInterrupt):
+ run_main(["--platform", "mac", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch)
+ build = next(i for i, c in enumerate(fake.calls) if "-executeMethod" in c)
+ assert [c for c in fake.calls[build + 1:] if c[:3] == ["git", "checkout", "--"]]
+
+
+def test_a_failed_unity_exit_fails_even_when_a_player_is_left_behind(repo, editor, monkeypatch, tmp_path):
+ """Mutation M1: Unity's exit code counts, not only whether the target exists."""
+ fake = Fake(build_ok=False)
+ out = tmp_path / "o"
+ assert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 1
+ assert (out / "players/mac/Statecraft.app").exists() and not (out / "build-record.json").exists()
+ assert 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"
+ assert rb.golden_status("", 0, {}) == "fail"
+
+
+# --- the record's tree state ------------------------------------------------------------------------------------------
+
+def test_the_record_says_whether_the_tree_stayed_clean(repo, editor, monkeypatch, tmp_path):
+ fake = Fake(dirty_after=" M unity/Packages/packages-lock.json\n")
+ out = tmp_path / "o"
+ assert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 0
+ record = json.loads((out / "build-record.json").read_text())
+ assert record["tree_clean"] is True, "checked before the builds"
+ assert record["tree_clean_after_builds"] is False
+ assert record["dirty_after_builds"] == ["M unity/Packages/packages-lock.json"]
+ describe = next(i for i, c in enumerate(fake.calls) if c[:2] == ["git", "describe"])
+ assert describe < next(i for i, c in enumerate(fake.calls) if "-executeMethod" in c), "describe is taken before"
+
+
+# --- what the script reads ------------------------------------------------------------------------------------------------
+
+def 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.versions() == {"bundle_version": "0.1.0", "sim_version": "0.1.0"}
+
+
+# --- refusals ---------------------------------------------------------------------------------------------------------
+
+def test_a_dirty_tree_is_refused_before_any_build(repo, editor, monkeypatch, capsys, tmp_path):
+ fake = Fake(dirty=" M unity/ProjectSettings/ProjectSettings.asset\n")
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+ err = capsys.readouterr().err
+ assert "REFUSED" in err and "ProjectSettings.asset" in err
+ assert not (tmp_path / "out").exists()
+
+
+def test_untracked_files_count_as_dirty(repo, editor, monkeypatch, tmp_path):
+ fake = Fake(dirty="?? notes.txt\n")
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 1
+ status = next(c for c in fake.calls if c[:2] == ["git", "status"])
+ assert "--porcelain" in status and "--untracked-files=normal" in status
+
+
+def test_missing_modules_fail_clearly_and_name_what_to_install(repo, editor, monkeypatch, capsys, tmp_path):
+ root = editor.parents[3]
+ for name in ("linux", "windows"):
+ (root / rb.PLATFORMS[name].module_dir).rmdir()
+ fake = Fake()
+ assert run_main(["--platform", "all", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 2
+ assert unity_calls(fake) == [], "no platform is built when any selected module is missing"
+ err = capsys.readouterr().err
+ assert "linux-mono" in err and "windows-mono" in err and "mac-il2cpp" not in err
+ assert "Unity Hub" in err and "install-modules" in err and "-m linux-mono -m windows-mono" in err
+
+
+def test_only_the_selected_platforms_modules_are_required(repo, editor, monkeypatch, tmp_path):
+ root = editor.parents[3]
+ (root / rb.PLATFORMS["windows"].module_dir).rmdir()
+ fake = Fake()
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 0
+
+
+def test_a_missing_editor_fails_clearly(repo, tmp_path, monkeypatch, capsys):
+ monkeypatch.setattr(rb, "REPO", repo)
+ monkeypatch.setattr(rb, "run", Fake())
+ assert rb.main(["--unity", str(tmp_path / "nope/Unity"), "--platform", "mac"]) == 2
+ assert "6000.3.25f1" in capsys.readouterr().err
+
+
+# --- the lock and the commands ----------------------------------------------------------------------------------------------
+
+def test_every_unity_build_runs_under_the_shared_lock_and_waits_for_unity(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ assert run_main(["--platform", "all", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 0
+ builds = unity_calls(fake)
+ assert len(builds) == 3
+ for c in builds:
+ lock = c.index("--")
+ head = c[:lock]
+ assert head[:2] == ["uv", "run"] and head[2].endswith("tools/machine_lock.py")
+ assert "--shared" in head and "--wait-unity" in head
+ assert c[lock + 1] == str(editor), "Unity is the locked command itself"
+ assert "-nographics" not in c, "never -nographics for the editor"
+ for flag in ("-batchmode", "-quit", "-CI", "-GITHUB_ACTIONS", "-TF_BUILD"):
+ assert flag in c
+ methods = [c[c.index("-executeMethod") + 1] for c in builds]
+ assert methods == ["Statecraft.Game.EditorTools.Build.Mac", "Statecraft.Game.EditorTools.Build.LinuxMono",
+ "Statecraft.Game.EditorTools.Build.WindowsMono"]
+ assert [c[c.index("-buildTarget") + 1] for c in builds] == ["OSXUniversal", "Linux64", "Win64"]
+
+
+def test_the_lock_never_times_out_on_its_own_hour(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ run_main(["--platform", "mac", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch)
+ for c in unity_calls(fake):
+ assert int(c[c.index("--timeout") + 1]) >= 7 * 24 * 3600, "a long wait is reported, never cancelled"
+
+
+def test_release_builds_are_shareable_and_dev_builds_are_not(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ run_main(["--platform", "mac", "--out", str(tmp_path / "a")], repo, editor, fake, monkeypatch)
+ assert "-shareable" in unity_calls(fake)[0]
+ fake = Fake()
+ run_main(["--platform", "mac", "--dev", "--out", str(tmp_path / "b")], repo, editor, fake, monkeypatch)
+ assert "-shareable" not in unity_calls(fake)[0]
+ assert json.loads((tmp_path / "b/build-record.json").read_text())["shareable"] is False
+
+
+def test_settings_churn_is_dropped_after_each_build(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ run_main(["--platform", "all", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch)
+ checkouts = [i for i, c in enumerate(fake.calls) if c[:3] == ["git", "checkout", "--"]]
+ builds = [i for i, c in enumerate(fake.calls) if "-executeMethod" in c]
+ assert len(checkouts) == 3 and all(b < k for b, k in zip(builds, checkouts))
+ assert fake.calls[checkouts[0]][3:] == ["unity/ProjectSettings", "unity/Assets/Settings"]
+
+
+def test_the_sim_dlls_are_built_before_unity(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ run_main(["--platform", "mac", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch)
+ sim = next(i for i, c in enumerate(fake.calls) if c[-1].endswith("tools/build_sim_for_unity.py"))
+ assert sim < next(i for i, c in enumerate(fake.calls) if "-executeMethod" in c)
+
+
+def test_no_push_upload_commit_or_network(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ run_main(["--platform", "all", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch)
+ for c in fake.calls:
+ if c[0] == "git":
+ assert c[1] in {"status", "rev-parse", "describe", "checkout", "tag", "worktree", "merge-base"}, c
+ assert c[0] not in {"gh", "curl", "wget", "scp", "rsync", "steamcmd", "xcrun"}, c
+ assert c[:2] not in (["git", "fetch"], ["git", "pull"], ["git", "ls-remote"]), "no network, not even a fetch"
+ assert "push" not in c and "commit" not in c
+ if c[:2] == ["git", "tag"]:
+ assert c[2] == "--points-at", "tags are only read"
+ if c[:2] == ["git", "worktree"]:
+ assert c[2] == "list", "worktrees are only read"
+ source = Path(rb.__file__).read_text()
+ for module in ("urllib", "http.client", "socket", "requests", "ftplib", "smtplib"):
+ assert f"import {module}" not in source and f"from {module}" not in source
+
+
+def test_a_dry_run_builds_nothing_and_writes_nothing(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = Fake()
+ assert run_main(["--platform", "all", "--dry-run", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 0
+ assert unity_calls(fake) == [] and not [c for c in fake.calls if "-golden" in c or c[:2] == ["git", "checkout"]]
+ assert not (tmp_path / "out").exists()
+ out = capsys.readouterr().out
+ assert "Build.Mac" in out and "Build.WindowsMono" in out and "machine_lock.py" in out
+
+
+def test_a_failed_build_stops_with_no_record(repo, editor, monkeypatch, tmp_path):
+ fake = Fake(build_ok=False)
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch) == 1
+ assert not (tmp_path / "out/build-record.json").exists()
+ assert [c for c in fake.calls if c[:2] == ["git", "checkout"]], "the settings are restored even after a failure"
+
+
+# --- the record ----------------------------------------------------------------------------------------------------------
+
+def test_the_record_holds_commit_unity_date_hashes_sizes_and_goldens(repo, editor, monkeypatch, tmp_path, capsys):
+ monkeypatch.setattr(rb, "utc_now", lambda: rb.datetime(2026, 10, 14, 12, 0, 0, tzinfo=rb.timezone.utc))
+ fake = Fake()
+ out = tmp_path / "out"
+ assert run_main(["--platform", "all", "--out", str(out)], repo, editor, fake, monkeypatch) == 0
+ record = json.loads((out / "build-record.json").read_text())
+ assert record["commit"] == SHA and record["tree_clean"] is True
+ assert record["unity"] == {"version": "6000.3.25f1", "revision": "e1dba0a9aba4"}
+ assert record["date_utc"] == "2026-10-14T12:00:00Z"
+ assert record["version"] == {"bundle_version": "0.1.0", "sim_version": "0.1.0"}
+ assert record["shareable"] is True and record["signing"] == "none" and record["tag"] == "v0.1.0"
+ arts = {a["platform"]: a for a in record["artifacts"]}
+ assert set(arts) == {"mac", "linux", "windows"}
+ assert arts["mac"]["backend"] == "IL2CPP" and arts["windows"]["backend"] == "Mono" and arts["linux"]["backend"] == "Mono"
+ assert arts["mac"]["architecture"] == "x86_64 arm64"
+ assert arts["mac"]["unity_build_seconds"] == 321
+
+ mac = arts["mac"]
+ manifest = out / mac["file_list"]
+ lines = manifest.read_text().splitlines()
+ exe = out / "players/mac/Statecraft.app/Contents/MacOS/Statecraft Israel"
+ assert f"{hashlib.sha256(b'player').hexdigest()} Statecraft.app/Contents/MacOS/Statecraft Israel" in lines
+ assert not any(line.endswith("event-photos.json") for line in lines), "the list is exactly what the zip holds"
+ assert all(line.split(" ", 1)[1].startswith("Statecraft.app/") for line in lines)
+ photos = out / mac["photo_manifest"]["file"]
+ assert photos.name == "event-photos-mac.json" and photos.read_text() == "{}\n"
+ assert mac["photo_manifest"]["sha256"] == hashlib.sha256(photos.read_bytes()).hexdigest()
+ assert lines == sorted(lines, key=lambda l: l.split(" ", 1)[1])
+ assert mac["file_list_sha256"] == hashlib.sha256(manifest.read_bytes()).hexdigest()
+ for name, asset in (("mac", "statecraft-israel-v0.1.0-macos-universal.zip"),
+ ("linux", "statecraft-israel-v0.1.0-linux-x64.tar.gz"),
+ ("windows", "statecraft-israel-v0.1.0-windows-x64.zip")):
+ archive = out / asset
+ assert arts[name]["archive"] == {"name": asset, "bytes": archive.stat().st_size,
+ "sha256": hashlib.sha256(archive.read_bytes()).hexdigest()}
+ assert mac["files"] == len(lines)
+ assert mac["bytes"] == sum(p.stat().st_size for p in (out / "players/mac/Statecraft.app").rglob("*") if p.is_file())
+ assert 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"]["exit_code"] == 0
+ for name in ("linux", "windows"):
+ assert arts[name]["golden"]["status"] == "unchecked"
+ assert "CI" in arts[name]["golden"]["note"]
+
+ md = (out / "build-record.md").read_text()
+ assert SHA in md and "6000.3.25f1" in md and mac["archive"]["sha256"] in md and mac["archive"]["name"] in md and "unchecked" in md and "pass" in md
+ printed = capsys.readouterr().out
+ assert str(out / "build-record.json") in printed
+
+
+def test_the_golden_runs_on_the_mac_player_headless_under_the_lock(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ run_main(["--platform", "all", "--out", str(tmp_path / "out")], repo, editor, fake, monkeypatch)
+ goldens = [c for c in fake.calls if "-golden" in c]
+ assert len(goldens) == 1, "only the macOS player can run on the Mac"
+ c = goldens[0]
+ head = c[:c.index("--")]
+ assert head[2].endswith("tools/machine_lock.py") and "--shared" in head
+ player = c[c.index("--") + 1]
+ assert player.endswith("Statecraft.app/Contents/MacOS/Statecraft Israel")
+ assert {"-batchmode", "-nographics", "-golden"} <= set(c), "a player may run -nographics (docs/determinism.md)"
+ assert Path(c[c.index("-logFile") + 1]).is_absolute()
+
+
+def test_a_failed_golden_is_recorded_and_fails_the_run(repo, editor, monkeypatch, tmp_path):
+ fake = Fake(golden_ok=False)
+ out = tmp_path / "out"
+ assert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 1
+ mac = 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"])
+
+
+def test_golden_lines_must_match_the_pinned_hashes_not_just_say_ok():
+ expected = {"1950": H1950, "1952": H1952}
+ assert rb.golden_status(f"GOLDEN OK 1950 {H1950}\nGOLDEN OK 1952 {H1952}\n", 0, expected) == "pass"
+ assert rb.golden_status(f"GOLDEN OK 1950 {H1950}\nGOLDEN OK 1952 {'0' * 64}\n", 0, expected) == "fail"
+ assert rb.golden_status(f"GOLDEN OK 1950 {H1950}\n", 0, expected) == "fail", "both years are required"
+ assert rb.golden_status(f"GOLDEN OK 1950 {H1950}\nGOLDEN OK 1952 {H1952}\n", 1, expected) == "fail"
+
+
+def test_symlinks_are_listed_by_target_not_followed(tmp_path):
+ folder = tmp_path / "p"
+ (folder / "A.app/Contents").mkdir(parents=True)
+ (folder / "A.app/Contents/real").write_bytes(b"x")
+ (folder / "A.app/Contents/link").symlink_to("real")
+ text, files, size = rb.tree_manifest(folder)
+ assert f"{hashlib.sha256(b'x').hexdigest()} A.app/Contents/real" in text.splitlines()
+ assert any(line.endswith("A.app/Contents/link -> real") for line in text.splitlines())
+ assert files == 2 and size == 1
+
+
+# --- the archives (the asset-name contract with the CI player check, PR #533) ----------------------------------------------
+
+def test_archive_names_follow_the_ci_contract():
+ assert rb.archive_name("v0.2.0", "windows") == "statecraft-israel-v0.2.0-windows-x64.zip"
+ assert rb.archive_name("v0.2.0", "linux") == "statecraft-israel-v0.2.0-linux-x64.tar.gz"
+ assert rb.archive_name("v0.2.0-rc.1", "mac") == "statecraft-israel-v0.2.0-rc.1-macos-universal.zip"
+
+
+def test_the_mac_archive_is_made_with_ditto_keeping_the_bundle(repo, editor, monkeypatch, tmp_path):
+ fake = Fake(tags=("v0.1.0",))
+ out = tmp_path / "out"
+ run_main(["--platform", "mac", "--tag", "v0.1.0", "--out", str(out)], repo, editor, fake, monkeypatch)
+ ditto = next(c for c in fake.calls if c[0] == "ditto")
+ assert ditto[1:5] == ["-c", "-k", "--norsrc", "--keepParent"], "no AppleDouble ._* entries the file list lacks"
+ assert ditto[-2] == str(out / "players/mac/Statecraft.app")
+ assert ditto[-1] == str(out / "statecraft-israel-v0.1.0-macos-universal.zip")
+
+
+def test_the_linux_and_windows_archives_hold_the_player_folder(repo, editor, monkeypatch, tmp_path):
+ import tarfile
+ import zipfile
+ out = tmp_path / "out"
+ assert run_main(["--platform", "all", "--out", str(out)], repo, editor, Fake(), monkeypatch) == 0
+ with tarfile.open(out / "statecraft-israel-v0.1.0-linux-x64.tar.gz") as t:
+ assert t.getnames() == ["Statecraft.x86_64"]
+ with zipfile.ZipFile(out / "statecraft-israel-v0.1.0-windows-x64.zip") as z:
+ assert z.namelist() == ["Statecraft.exe"]
+
+
+def test_the_linux_archive_keeps_the_executable_bit(tmp_path):
+ import tarfile
+ folder = tmp_path / "linux"
+ folder.mkdir()
+ exe = folder / "Statecraft.x86_64"
+ exe.write_bytes(b"elf")
+ exe.chmod(0o755)
+ rb.make_archive(rb.PLATFORMS["linux"], folder, exe, tmp_path / "a.tar.gz")
+ with tarfile.open(tmp_path / "a.tar.gz") as t:
+ assert t.getmember("Statecraft.x86_64").mode & 0o111
+
+
+def test_a_bad_tag_is_refused(repo, editor, monkeypatch, tmp_path):
+ fake = Fake()
+ assert run_main(["--platform", "mac", "--tag", "0.1.0", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+
+
+def test_a_folder_with_two_players_breaks_the_contract(tmp_path):
+ folder = tmp_path / "w"
+ folder.mkdir()
+ for name in ("Statecraft.exe", "Other.exe", "UnityCrashHandler64.exe"):
+ (folder / name).write_bytes(b"x")
+ assert "found 2" in rb.player_problem(rb.PLATFORMS["windows"], folder)
+ (folder / "Other.exe").unlink()
+ assert rb.player_problem(rb.PLATFORMS["windows"], folder) is None, "the crash handler does not count"
+
+
+def test_a_boot_fail_line_fails_the_golden_even_with_both_ok_lines():
+ expected = {"1950": H1950, "1952": H1952}
+ log = f"GOLDEN OK 1950 {H1950}\nGOLDEN OK 1952 {H1952}\nBOOT FAIL could not read content\n"
+ assert rb.golden_status(log, 0, expected) == "fail"
+
+
+def test_unitys_do_not_ship_folders_are_left_out_of_the_list_and_the_archives(tmp_path):
+ """IL2CPP and Burst leave Statecraft_BackUpThisFolder_ButDontShipItWithYourGame (2 GB in the first real run) and
+ <product>_BurstDebugInformation_DoNotShip beside the player; neither is part of the release."""
+ import zipfile
+ folder = tmp_path / "w"
+ (folder / "Statecraft_BackUpThisFolder_ButDontShipItWithYourGame").mkdir(parents=True)
+ (folder / "Statecraft_BackUpThisFolder_ButDontShipItWithYourGame/big.cpp").write_bytes(b"x" * 10)
+ (folder / "Statecraft Israel_BurstDebugInformation_DoNotShip").mkdir()
+ (folder / "Statecraft Israel_BurstDebugInformation_DoNotShip/d.pdb").write_bytes(b"y")
+ (folder / "Statecraft.exe").write_bytes(b"exe")
+ text, files, size = rb.tree_manifest(folder)
+ assert text.splitlines() == [f"{hashlib.sha256(b'exe').hexdigest()} Statecraft.exe"] and (files, size) == (1, 3)
+ rb.make_archive(rb.PLATFORMS["windows"], folder, folder / "Statecraft.exe", tmp_path / "w.zip")
+ assert zipfile.ZipFile(tmp_path / "w.zip").namelist() == ["Statecraft.exe"]
+
+
+# --- review of #542, round 3 ----------------------------------------------------------------------------------------------
+
+def test_a_release_tag_must_be_the_bundle_version(repo, editor, monkeypatch, tmp_path, capsys):
+ """A v2.0.0 tag at HEAD with bundleVersion 0.1.0 would name archives after a version the player does not have."""
+ fake = Fake(tags=("v2.0.0",))
+ assert run_main(["--platform", "mac", "--tag", "v2.0.0", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == [] and "0.1.0" in capsys.readouterr().err
+ fake = Fake(tags=("v0.1.0-rc.1",))
+ assert run_main(["--platform", "mac", "--tag", "v0.1.0-rc.1", "--out", str(tmp_path / "p")], repo, editor, fake, monkeypatch) == 0, \
+ "a pre-release suffix on the bundle version is a release of that version"
+
+
+def test_a_malformed_tag_at_head_is_refused(repo, editor, monkeypatch, tmp_path, capsys):
+ """Pins the tag-format check itself: this tag is at HEAD and starts with v<bundleVersion>-."""
+ fake = Fake(tags=("v0.1.0-rc_1",))
+ assert run_main(["--platform", "mac", "--tag", "v0.1.0-rc_1", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == [] and "not a release tag" in capsys.readouterr().err
+
+
+def test_a_release_must_be_on_origin_main(repo, editor, monkeypatch, tmp_path, capsys):
+ """A local main with commits GitHub's main lacks is not a release; the script reads origin/main and never fetches."""
+ fake = Fake(on_origin_main=False)
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ err = capsys.readouterr().err
+ assert unity_calls(fake) == [] and "origin/main" in err and "git fetch" in err
+ check = next(c for c in fake.calls if c[:2] == ["git", "merge-base"])
+ assert check == ["git", "merge-base", "--is-ancestor", "HEAD", "refs/remotes/origin/main"]
+ fake = Fake(on_origin_main=False, branch="tools/x", tags=())
+ assert run_main(["--platform", "mac", "--dev", "--out", str(tmp_path / "d")], repo, editor, fake, monkeypatch) == 0, \
+ "a dev build may be anywhere"
+
+
+def test_a_detached_head_says_so(repo, editor, monkeypatch, tmp_path, capsys):
+ fake = Fake(branch="HEAD")
+ assert run_main(["--platform", "mac", "--out", str(tmp_path / "o")], repo, editor, fake, monkeypatch) == 1
+ assert "HEAD is detached" in capsys.readouterr().err
+
+
+def test_a_dangling_symlink_into_the_repository_is_refused(repo, editor, monkeypatch, tmp_path):
+ link = tmp_path / "dangling"
+ link.symlink_to(repo / "unity/Assets/NotYetThere")
+ for extra in ([], ["--dry-run"]):
+ fake = Fake()
+ assert run_main(["--platform", "mac", "--dev", *extra, "--out", str(link / "x")], repo, editor, fake, monkeypatch) == 1
+ assert unity_calls(fake) == []
+
+
[email protected]("tag", ["v٠.١.٠", "v0.1.0", "v0.1.0-rc.١"])
+def test_a_tag_with_non_ascii_digits_is_not_a_release_tag(tag):
+ """\\d without re.ASCII matches Arabic-Indic and full-width digits; a tag reaches file names and the CI check."""
+ assert rb.TAG.fullmatch(tag) is None
diff --git a/unity/Assets/Editor/Build.cs b/unity/Assets/Editor/Build.cs
index 6ba2dfaf4..f4a0d1913 100644
--- a/unity/Assets/Editor/Build.cs
+++ b/unity/Assets/Editor/Build.cs
@@ -18,7 +18,10 @@ namespace Statecraft.Game.EditorTools
/// (-textureSubtarget: the compressed format of every automatic texture; the default build is DXT, for desktop
/// browsers; astc or etc2 makes a build for browsers without S3TC, as on phones)
/// Mac: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget OSXUniversal -executeMethod Statecraft.Game.EditorTools.Build.Mac
- /// [-out Builds/Mac/Statecraft.app] [-ffp-contract-off]</summary>
+ /// [-out Builds/Mac/Statecraft.app] [-ffp-contract-off]
+ /// Linux (Mono): ... -buildTarget Linux64 -executeMethod Statecraft.Game.EditorTools.Build.LinuxMono [-out Builds/Linux/Statecraft.x86_64]
+ /// Windows (Mono): ... -buildTarget Win64 -executeMethod Statecraft.Game.EditorTools.Build.WindowsMono [-out Builds/Windows/Statecraft.exe]
+ /// Every player takes -shareable (the sensitivity gate). tools/release_build.py runs these under the machine lock.</summary>
public static class Build
{
static string? Arg(string name)
@@ -200,6 +203,26 @@ namespace Statecraft.Game.EditorTools
ExitIfFailed(ok);
}
+ /// <summary>The Linux x64 player on Mono, built from the Mac (decision O7; tools/release_build.py).</summary>
+ public static void LinuxMono() => StandaloneMono(BuildTarget.StandaloneLinux64, "Builds/Linux/Statecraft.x86_64");
+
+ /// <summary>The Windows x64 player on Mono: Unity builds a Windows IL2CPP player only on Windows (decision O8).</summary>
+ public static void WindowsMono() => StandaloneMono(BuildTarget.StandaloneWindows64, "Builds/Windows/Statecraft.exe");
+
+ /// <summary>Builds <paramref name="target"/> with the Mono backend, then puts the committed IL2CPP setting back
+ /// (ProjectSetup.Apply): the Standalone backend is one setting for Mac, Linux and Windows.</summary>
+ static void StandaloneMono(BuildTarget target, string defaultOut)
+ {
+ if (RefuseUnlessShareable()) return;
+ ProjectSetup.Apply();
+ PlayerSettings.SetScriptingBackend(NamedBuildTarget.Standalone, ScriptingImplementation.Mono2x);
+ bool ok;
+ var player = Arg("-out") ?? defaultOut;
+ try { ok = Run(target, player); if (ok) WritePhotoManifest(Path.GetDirectoryName(Path.GetFullPath(player))!); }
+ finally { ProjectSetup.Apply(); AssetDatabase.SaveAssets(); }
+ ExitIfFailed(ok);
+ }
+
/// <summary>Exits with code 1 after the caller's settings have been restored.</summary>
static void ExitIfFailed(bool ok) { if (!ok) EditorApplication.Exit(1); }
diff --git a/unity/Assets/Tests/EditMode/BuildGateTests.cs b/unity/Assets/Tests/EditMode/BuildGateTests.cs
index f0de10c38..61f02f03b 100644
--- a/unity/Assets/Tests/EditMode/BuildGateTests.cs
+++ b/unity/Assets/Tests/EditMode/BuildGateTests.cs
@@ -43,11 +43,30 @@ public class BuildGateTests
foreach (var e in c.Events) if (e.Id == "reparations_claim") e.Status = "fact-checked";
StringAssert.Contains("reparations_claim", (string?)gate.Invoke(null, new object?[] { new[] { "Unity", "-shareable" }, c, null, false, null, null }));
var source = System.IO.File.ReadAllText("Assets/Editor/Build.cs");
- foreach (var method in new[] { "public static void Web()", "public static void Mac()" })
+ foreach (var method in new[] { "public static void Web()", "public static void Mac()", "static void StandaloneMono(" })
{
var body = source.Substring(source.IndexOf(method, StringComparison.Ordinal), 400);
StringAssert.Contains("RefuseUnlessShareable()", body, method + " checks the gate first");
}
+ foreach (var method in new[] { "public static void LinuxMono()", "public static void WindowsMono()" })
+ StringAssert.Contains("=> StandaloneMono(", source.Substring(source.IndexOf(method, StringComparison.Ordinal), 120), method + " goes through the gated Mono build");
+ }
+
+ /// <summary>#482: Linux and Windows are built from the Mac on Mono (decisions O7, O8). The Standalone backend is one
+ /// setting for all three desktop targets, so the Mono build must put the committed IL2CPP back afterwards.</summary>
+ [Test]
+ public void TheMonoPlayersRestoreTheCommittedBackend()
+ {
+ var t = Type.GetType("Statecraft.Game.EditorTools.Build, Assembly-CSharp-Editor")!;
+ foreach (var name in new[] { "Mac", "LinuxMono", "WindowsMono" })
+ Assert.IsNotNull(t.GetMethod(name, BindingFlags.Public | BindingFlags.Static), name + " is an -executeMethod target");
+ var source = System.IO.File.ReadAllText("Assets/Editor/Build.cs");
+ var start = source.IndexOf("static void StandaloneMono(", StringComparison.Ordinal);
+ var body = source.Substring(start, source.IndexOf("ExitIfFailed(ok);", start, StringComparison.Ordinal) - start);
+ StringAssert.Contains("ScriptingImplementation.Mono2x", body);
+ StringAssert.Contains("finally { ProjectSetup.Apply();", body, "IL2CPP is restored even when the build throws");
+ Assert.AreEqual(UnityEditor.ScriptingImplementation.IL2CPP,
+ UnityEditor.PlayerSettings.GetScriptingBackend(UnityEditor.Build.NamedBuildTarget.Standalone), "the committed Standalone backend");
}
// Owner ruling 2026-10-11: the event photographs of sensitive events need the