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.

Post-merge Unity EditMode run on the owner's Mac, and a dotnet compile check in check.sh (T72) (#717)

Eyal Golan79501cde7e74
diff --git a/scripts/check.sh b/scripts/check.sh
index 23b3d6912..42607d973 100755
--- a/scripts/check.sh
+++ b/scripts/check.sh
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# One command for "does my change pass?": the same checks CI runs, in order, cheapest first. Needs dotnet and uv, not
# Unity (Unity edit-mode tests are not run by CI either; CONTRIBUTING.md, "What CI runs").
+# Where a Unity editor and a unity/Library exist, it also compiles unity/ with dotnet (scripts/unity_compile/).
# Stops at the first failure, prints the last lines of that step's output and exits non-zero.
#
# Usage: scripts/check.sh [BASE_REF] BASE_REF defaults to $CHECK_BASE, then origin/main.
@@ -41,6 +42,18 @@ run "policy checker tests" uv run --with pytest==9.1.1 --with pyyaml==6.0.3 --wi
run "repo policy" uv run scripts/oss/check_repo.py
run "rule ids" uv run scripts/oss/rule_ids.py
run "sim build, warnings as errors" dotnet build sim/Statecraft.sln -c Release --nologo -warnaserror
+# Optional (T72): compile unity/ with dotnet, outside Unity, in about 2 s and with no Unity licence. It is skipped only
+# when the project's editor or unity/Library is missing (CI, most contributors), and says so; any other problem fails.
+unity_version="$(sed -n 's/^m_EditorVersion: //p' unity/ProjectSettings/ProjectVersion.txt)"
+[ -n "$unity_version" ] || { echo "FAILED: unity compile: no m_EditorVersion in unity/ProjectSettings/ProjectVersion.txt"; exit 1; }
+unity_contents="${CHECK_UNITY_CONTENTS:-/Applications/Unity/Hub/Editor/$unity_version/Unity.app/Contents}"
+if [ ! -d "$unity_contents" ]; then
+ echo "== unity compile: SKIPPED, no Unity $unity_version editor at $unity_contents"
+elif [ ! -d unity/Library ]; then
+ echo "== unity compile: SKIPPED, no unity/Library (open the project in Unity once, or clone a Library)"
+else
+ run "unity compile (dotnet, outside Unity)" scripts/unity_compile/compile.sh "$unity_contents"
+fi
run "sim and content tests" dotnet test sim/Statecraft.sln -c Release --nologo
run "data tool tests" uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 --with pyproj==3.8.0 pytest tools/tests -q
diff --git a/scripts/unity_compile/Common.props b/scripts/unity_compile/Common.props
new file mode 100644
index 000000000..794f470a7
--- /dev/null
+++ b/scripts/unity_compile/Common.props
@@ -0,0 +1,29 @@
+<Project>
+ <!-- The compile-only check of unity/ that scripts/check.sh runs when a Unity editor and a Library are present
+ (T72, option (a) of the CI proposal). It compiles the two asmdefs, Statecraft.Game and Statecraft.Tests.EditMode,
+ with the settings Unity uses for them: netstandard2.1, C# 9, Unity's own BCL and the editor's define list.
+ Properties set by check.sh: Editor (Unity.app/Contents), Lib (unity/Library), Src (unity/), Sim (the published
+ sim DLLs) and OutputPath. UnityVersion is the editor the define list below was copied from (Unity's generated
+ Statecraft.Game.csproj, 6000.3.25f1); check.sh refuses to run against another version until this file is
+ updated. Not covered: Assets/Editor, Unity's source generators, ILPP and Burst. Needs no Unity licence. -->
+ <PropertyGroup>
+ <UnityVersion>6000.3.25f1</UnityVersion>
+ <TargetFramework>netstandard2.1</TargetFramework>
+ <LangVersion>9.0</LangVersion>
+ <EnableDefaultItems>false</EnableDefaultItems>
+ <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
+ <NoStdLib>true</NoStdLib>
+ <NoConfig>true</NoConfig>
+ <DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ <NoWarn>0169;USG0001;CS1701;CS1702</NoWarn>
+ <MSBuildWarningsAsMessages>MSB3277</MSBuildWarningsAsMessages>
+ <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
+ <UnityDefines>UNITY_6000_3_25;UNITY_6000_3;UNITY_6000;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_2_OR_NEWER;UNITY_2017_3_OR_NEWER;UNITY_2017_4_OR_NEWER;UNITY_2018_1_OR_NEWER;UNITY_2018_2_OR_NEWER;UNITY_2018_3_OR_NEWER;UNITY_2018_4_OR_NEWER;UNITY_2019_1_OR_NEWER;UNITY_2019_2_OR_NEWER;UNITY_2019_3_OR_NEWER;UNITY_2019_4_OR_NEWER;UNITY_2020_1_OR_NEWER;UNITY_2020_2_OR_NEWER;UNITY_2020_3_OR_NEWER;UNITY_2021_1_OR_NEWER;UNITY_2021_2_OR_NEWER;UNITY_2021_3_OR_NEWER;UNITY_2022_1_OR_NEWER;UNITY_2022_2_OR_NEWER;UNITY_2022_3_OR_NEWER;UNITY_2023_1_OR_NEWER;UNITY_2023_2_OR_NEWER;UNITY_2023_3_OR_NEWER;UNITY_6000_0_OR_NEWER;UNITY_6000_1_OR_NEWER;UNITY_6000_2_OR_NEWER;UNITY_6000_3_OR_NEWER;PLATFORM_ARCH_64;UNITY_64;UNITY_INCLUDE_TESTS;ENABLE_AR;ENABLE_AUDIO;ENABLE_AUDIO_SCRIPTABLE_PIPELINE;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_TEXTURE_STREAMING;ENABLE_VIRTUALTEXTURING;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_VR;ENABLE_WEBCAM;ENABLE_UNITYWEBREQUEST;ENABLE_WWW;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_UNITY_CONSENT;ENABLE_UNITY_CLOUD_IDENTIFIERS;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_NATIVE_CRASH_REPORTING;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_EDITOR_GAME_SERVICES;ENABLE_UNITY_GAME_SERVICES_ANALYTICS_SUPPORT;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_HUB_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_GENERATE_NATIVE_PLUGINS_FOR_ASSEMBLIES_API;ENABLE_DIRECTOR_AUDIO;ENABLE_DIRECTOR_TEXTURE;ENABLE_MANAGED_JOBS;ENABLE_MANAGED_TRANSFORM_JOBS;ENABLE_MANAGED_ANIMATION_JOBS;ENABLE_MANAGED_AUDIO_JOBS;ENABLE_MANAGED_UNITYTLS;INCLUDE_DYNAMIC_GI;ENABLE_SCRIPTING_GC_WBARRIERS;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;ENABLE_MARSHALLING_TESTS;ENABLE_VIDEO;ENABLE_NAVIGATION_OFFMESHLINK_TO_NAVMESHLINK;ENABLE_ACCELERATOR_CLIENT_DEBUGGING;ENABLE_ACCESSIBILITY_SCREEN_READER;TEXTCORE_1_0_OR_NEWER;EDITOR_ONLY_NAVMESH_BUILDER_DEPRECATED;PLATFORM_STANDALONE_OSX;PLATFORM_STANDALONE;UNITY_STANDALONE_OSX;UNITY_STANDALONE;ENABLE_GAMECENTER;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_CLOUD_SERVICES_ENGINE_DIAGNOSTICS;ENABLE_CLUSTER_SYNC;ENABLE_CLUSTERINPUT;ENABLE_SPATIALTRACKING;PLATFORM_HAS_CUSTOM_MUTEX;PLATFORM_UPDATES_TIME_OUTSIDE_OF_PLAYER_LOOP;PLATFORM_SUPPORTS_SPLIT_GRAPHICS_JOBS;ENABLE_MONO;ENABLE_PROFILER;ENABLE_PROFILER_ASSISTANT_INTEGRATION;DEBUG;TRACE;UNITY_ASSERTIONS;UNITY_EDITOR;UNITY_EDITOR_64;UNITY_EDITOR_OSX;ENABLE_UNITY_COLLECTIONS_CHECKS;ENABLE_BURST_AOT;UNITY_TEAM_LICENSE;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_DIRECTOR;ENABLE_LOCALIZATION;ENABLE_SPRITES;ENABLE_TERRAIN;ENABLE_TILEMAP;ENABLE_TIMELINE;ENABLE_INPUT_SYSTEM;TEXTCORE_FONT_ENGINE_1_5_OR_NEWER;TEXTCORE_TEXT_ENGINE_1_5_OR_NEWER;TEXTCORE_FONT_ENGINE_1_6_OR_NEWER;CSHARP_7_OR_LATER;CSHARP_7_3_OR_NEWER</UnityDefines>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="$(Editor)/Resources/Scripting/Managed/UnityEngine/*.dll" Private="false" />
+ <Reference Include="$(Sim)/Statecraft.Sim.dll;$(Sim)/YamlDotNet.dll" Private="false" />
+ <Reference Include="$(Lib)/ScriptAssemblies/Unity.RenderPipelines.Core.Runtime.dll;$(Lib)/ScriptAssemblies/Unity.RenderPipelines.Universal.Runtime.dll;$(Lib)/ScriptAssemblies/Unity.InputSystem.dll" Private="false" />
+ </ItemGroup>
+</Project>
diff --git a/scripts/unity_compile/Game.csproj b/scripts/unity_compile/Game.csproj
new file mode 100644
index 000000000..c91c94449
--- /dev/null
+++ b/scripts/unity_compile/Game.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <Import Project="Common.props" />
+ <PropertyGroup>
+ <AssemblyName>Statecraft.Game</AssemblyName>
+ <DefineConstants>$(UnityDefines);NET_STANDARD;NET_STANDARD_2_0;NET_STANDARD_2_1;NETSTANDARD;NETSTANDARD2_1</DefineConstants>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="$(Editor)/Resources/Scripting/NetStandard/ref/2.1.0/netstandard.dll" Private="false" />
+ <Compile Include="$(Src)/Assets/Scripts/**/*.cs" />
+ </ItemGroup>
+</Project>
diff --git a/scripts/unity_compile/Tests.csproj b/scripts/unity_compile/Tests.csproj
new file mode 100644
index 000000000..7586c3bd9
--- /dev/null
+++ b/scripts/unity_compile/Tests.csproj
@@ -0,0 +1,15 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <Import Project="Common.props" />
+ <PropertyGroup>
+ <AssemblyName>Statecraft.Tests.EditMode</AssemblyName>
+ <DefineConstants>$(UnityDefines);NET_4_6;NET_UNITY_4_8;UNITY_EDITOR_ONLY_COMPILATION</DefineConstants>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="$(Editor)/Resources/Scripting/UnityReferenceAssemblies/unity-4.8-api/*.dll" Private="false" />
+ <Reference Include="$(Editor)/Resources/Scripting/UnityReferenceAssemblies/unity-4.8-api/Facades/*.dll" Private="false" />
+ <Reference Include="$(Lib)/ScriptAssemblies/UnityEngine.TestRunner.dll;$(Lib)/ScriptAssemblies/UnityEditor.TestRunner.dll" Private="false" />
+ <Reference Include="$(Lib)/PackageCache/com.unity.ext.nunit@*/net40/unity-custom/nunit.framework.dll" Private="false" />
+ <ProjectReference Include="Game.csproj" />
+ <Compile Include="$(Src)/Assets/Tests/EditMode/**/*.cs" />
+ </ItemGroup>
+</Project>
diff --git a/scripts/unity_compile/compile.sh b/scripts/unity_compile/compile.sh
new file mode 100755
index 000000000..af0530311
--- /dev/null
+++ b/scripts/unity_compile/compile.sh
@@ -0,0 +1,39 @@
+#!/usr/bin/env bash
+# Compile unity/'s two asmdefs with dotnet, outside Unity (T72): catches compile breaks such as a PR calling code another
+# PR deleted, in about 2 seconds and with no Unity licence. scripts/check.sh runs it only where the project's editor
+# and a unity/Library exist. It does not run any test: the EditMode suite still needs Unity.
+#
+# Usage: scripts/unity_compile/compile.sh <path to Unity.app/Contents>
+# Writes nothing into the checkout: the project files, the published sim DLLs and the output go to a temp folder.
+set -euo pipefail
+cd "$(dirname "$0")/../.."
+contents="${1:?usage: compile.sh <Unity.app/Contents>}"
+here=scripts/unity_compile
+version="$(sed -n 's/^m_EditorVersion: //p' unity/ProjectSettings/ProjectVersion.txt)"
+pinned="$(sed -n 's:.*<UnityVersion>\(.*\)</UnityVersion>.*:\1:p' "$here/Common.props")"
+if [ "$version" != "$pinned" ]; then
+ echo "unity/ is on Unity $version, but $here/Common.props has the define list of $pinned."
+ echo "Copy DefineConstants from Unity's generated unity/Statecraft.Game.csproj into UnityDefines and set UnityVersion."
+ exit 1
+fi
+# A Library without these (never opened in Unity, or an import that failed) is an error here, not a skip.
+lib=unity/Library
+for f in "$contents/Resources/Scripting/Managed/UnityEngine/UnityEngine.CoreModule.dll" \
+ "$contents/Resources/Scripting/NetStandard/ref/2.1.0/netstandard.dll" \
+ "$lib"/ScriptAssemblies/{Unity.RenderPipelines.Core.Runtime,Unity.RenderPipelines.Universal.Runtime}.dll \
+ "$lib"/ScriptAssemblies/{Unity.InputSystem,UnityEngine.TestRunner,UnityEditor.TestRunner}.dll; do
+ [ -f "$f" ] || { echo "missing: $f (open the project in Unity once so it builds its Library)"; exit 1; }
+done
+nunit=("$lib"/PackageCache/com.unity.ext.nunit@*/net40/unity-custom/nunit.framework.dll)
+[ -f "${nunit[0]}" ] || { echo "missing: Unity's nunit.framework.dll under $lib/PackageCache"; exit 1; }
+tmp="$(mktemp -d)"
+trap 'rm -rf "$tmp"' EXIT
+cp "$here"/Common.props "$here"/Game.csproj "$here"/Tests.csproj "$tmp/"
+dotnet publish sim/Statecraft.Sim -c Release -o "$tmp/sim" --nologo -v q
+if ! dotnet build "$tmp/Tests.csproj" --nologo -v q -p:Editor="$contents" -p:Lib="$PWD/unity/Library" \
+ -p:Src="$PWD/unity" -p:Sim="$tmp/sim" -p:OutputPath="$tmp/bin/"; then
+ echo "unity/ does not compile. If the error names a package type (URP, Input System, the test framework),"
+ echo "unity/Library may be older than unity/Packages: open the project in Unity once and run this again."
+ exit 1
+fi
+echo "unity compile: Statecraft.Game and Statecraft.Tests.EditMode build with 0 errors and 0 warnings"
diff --git a/tools/README.md b/tools/README.md
index 161bf6ae9..bb636e3b4 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -74,6 +74,9 @@ Offline data tools (uv inline-script Python). Run from the repo root.
shots, against bands set from promo 03 (#388).
- `machine_lock.py` serialises frame-time measurements against every other Unity job on the machine (all worktrees,
batch runs and open editors).
+- `unity_postmerge.py` runs the full Unity EditMode suite on each new `main` commit, on the owner's Mac, and reports a
+ failure as one issue while `main` stays broken, with a comment for each newly failing commit (T72; details in
+ "Post-merge Unity run" below).
- `headed.py` drives a WebGL build in a headed Chrome for Testing over CDP (real GPU, real mouse events, a temporary
profile deleted on exit): `boot` (?bootlog phase timings, optional CPU throttling), `navpairs` (same-frame click pairs
under ?navlog), `loadshot` (screenshots during the load) and `profile` (visual v1's `?vprofile` in a headed window at a
@@ -136,3 +139,49 @@ Repeated paths do not satisfy the count. It does not compare image contents: cop
what each screenshot shows and records the build commit/zip SHA-256 and capture date. This does not capture anything,
change a release gate or submit a store page. Steam's [official screenshot requirements](https://partner.steamgames.com/doc/store/assets/standard)
were checked 11 October 2026; re-check before submission. These are not itch.io requirements.
+
+## Post-merge Unity run (T72)
+
+CI cannot run Unity (CONTRIBUTING.md, "What CI runs"), so two pull requests can each pass and still break Unity once
+both are on `main`. `tools/unity_postmerge.py` closes that gap after the merge, on the owner's Mac, from a launchd job
+(`tools/unity_postmerge.plist.in`, every 15 minutes).
+- launchd starts `unity_postmerge_launch.py` (a copy in the job folder, `~/.cache/statecraft/unity-postmerge`). It
+ fetches `origin/main`, moves the job's own worktree (`~/.cache/statecraft/unity-postmerge/worktree`) to the tip and
+ runs `tools/unity_postmerge.py` from there. So a merged change to the script takes effect on the next run, and no
+ checkout's working tree is used or changed.
+- When the tip is not the commit it last tested, the script cleans the worktree (keeping the Library, capped at 6 GB),
+ runs the whole EditMode suite under `machine_lock.py --shared --wait-unity` and reverts the settings churn. A Unity
+ still running 90 minutes after it started (`--unity-timeout-min`) is stopped by the PID `machine_lock.py` recorded
+ for it (SIGTERM, then SIGKILL), and the run counts as timed out.
+- A pass adds one line to `~/.cache/statecraft/unity-postmerge/results.log`. Anything else, 0 tests included, is
+ reported once per commit with the failing tests and the log tail: as a new issue (label `area: unity`), or, while an
+ issue it opened is still open, as a comment on that issue. It tests the tip only; the report lists the commits since
+ the last tested one.
+- Before the log tail, compile errors, test messages, the broken-run reason (git's stderr, for one) and the commit
+ list go into the public issue, email addresses, the home folder (to `~`), any `/Users/<name>`, Unity's
+ `LicenseClient-<name>` and the user name are redacted. If redacting fails, the report says "Log withheld" and
+ carries none of them.
+- Fetch and `gh` failures, and a launcher that cannot start the script, are written to `launchd.log` in the job folder.
+ When `main`'s tip still has no PASS or FAIL line in `results.log` 6 hours after it was committed (the 4 h lock wait,
+ 90 min of Unity and 30 min to spare), the job appends one `STALE` line for that commit to `results.log`, so a
+ stuck job or an expired `gh` login shows there. A job that does not run at all (launchd, `uv` or the fetch broken)
+ writes nothing: a `results.log` whose last line is older than `main`'s tip by more than 6 hours means that.
+
+Install (owner's Mac only, from a checkout of `main` that has these files):
+
+```bash
+job=~/.cache/statecraft/unity-postmerge
+mkdir -p "$job" && cp tools/unity_postmerge_launch.py "$job/"
+sed -e "s#@UV@#$(command -v uv)#g" -e "s#@REPO@#$HOME/israel-game#g" -e "s#@HOME@#$job#g" \
+ -e "s#@PATH@#$(dirname "$(command -v uv)"):$(dirname "$(command -v gh)"):$(dirname "$(command -v dotnet)"):/usr/bin:/bin:/usr/sbin:/sbin#g" \
+ tools/unity_postmerge.plist.in > ~/Library/LaunchAgents/com.statecraft.unity-postmerge.plist
+plutil -lint ~/Library/LaunchAgents/com.statecraft.unity-postmerge.plist
+launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.statecraft.unity-postmerge.plist
+```
+
+`@REPO@` is the main checkout: the launcher only fetches there and clones its Library once. A change to the launcher
+itself needs the `cp` again; a change to `unity_postmerge.py` does not.
+
+Uninstall: `launchctl bootout gui/$(id -u)/com.statecraft.unity-postmerge`, then delete the plist. To remove the
+worktree too: `git worktree remove --force ~/.cache/statecraft/unity-postmerge/worktree`. A trial without opening an
+issue or moving the state: `uv run tools/unity_postmerge.py --dry-run --home <scratch folder>`.
diff --git a/tools/machine_lock.py b/tools/machine_lock.py
index 4f2598e64..258c39066 100644
--- a/tools/machine_lock.py
+++ b/tools/machine_lock.py
@@ -16,7 +16,10 @@ Unity processes are recognised by their executable (`ps -o comm=`), never by arg
name Unity in their command line do not count (review C1). macOS flock does not queue fairly, so every request first
passes a gate (the same path plus ".gate"): it takes the gate exclusively, then the machine lock, then releases the gate.
A waiting exclusive request holds the gate until it has the lock, so no new shared holder gets in ahead of it and the
-running ones drain (issue #207; before, a stream of shared jobs starved a profile, review M9)."""
+running ones drain (issue #207; before, a stream of shared jobs starved a profile, review M9).
+
+When STATECRAFT_LOCK_HOLDER names a file, it writes "<this pid> <command pid>" there once the command has started:
+the holder record tools/unity_postmerge.py uses to stop a hung Unity by its PID (T72)."""
import argparse
import fcntl
import os
@@ -28,6 +31,7 @@ from pathlib import Path
LOCK = Path(os.environ.get("STATECRAFT_MACHINE_LOCK", str(Path.home() / ".cache" / "statecraft" / "machine.lock")))
GATE = LOCK.with_name(LOCK.name + ".gate")
UNITY_EXE = "/Unity.app/Contents/MacOS/Unity"
+HOLDER_ENV = "STATECRAFT_LOCK_HOLDER"
def parse(argv: list[str]) -> argparse.Namespace:
@@ -112,7 +116,17 @@ def main(argv: list[str] | None = None) -> int:
if a.wait_unity and not wait_for_unity(a.timeout):
print("machine_lock: timed out waiting for Unity")
return 3
- return subprocess.call(a.command)
+ child = subprocess.Popen(a.command)
+ if record := os.environ.get(HOLDER_ENV):
+ tmp = Path(record + ".tmp")
+ tmp.write_text(f"{os.getpid()} {child.pid}\n")
+ os.replace(tmp, record)
+ try:
+ return child.wait()
+ except BaseException:
+ child.kill()
+ child.wait()
+ raise
if __name__ == "__main__":
diff --git a/tools/tests/test_machine_lock.py b/tools/tests/test_machine_lock.py
index 7c672b385..2ea6cd918 100644
--- a/tools/tests/test_machine_lock.py
+++ b/tools/tests/test_machine_lock.py
@@ -117,3 +117,22 @@ def test_a_waiting_exclusive_request_runs_before_a_later_shared_one(tmp_path):
p.terminate()
p.wait(10)
p.stdout.close()
+
+
+def test_the_holder_record_names_this_lock_and_the_command_it_started(tmp_path):
+ """T72: unity_postmerge.py stops a hung Unity by the PID this record gives, never by name."""
+ record = tmp_path / "holder"
+ env = {**os.environ, "STATECRAFT_MACHINE_LOCK": str(tmp_path / "machine.lock"), ml.HOLDER_ENV: str(record)}
+ p = subprocess.run([sys.executable, ml.__file__, "--shared", "--", sys.executable, "-c",
+ "import os; print(os.getpid(), os.getppid())"], env=env, capture_output=True, text=True)
+ assert p.returncode == 0
+ child, parent = p.stdout.split()[-2:]
+ assert record.read_text().split() == [parent, child]
+
+
+def test_no_holder_record_is_written_unless_asked(tmp_path):
+ env = {k: v for k, v in os.environ.items() if k != ml.HOLDER_ENV}
+ env["STATECRAFT_MACHINE_LOCK"] = str(tmp_path / "machine.lock")
+ assert subprocess.run([sys.executable, ml.__file__, "--shared", "--", sys.executable, "-c", "pass"],
+ env=env).returncode == 0
+ assert sorted(p.name for p in tmp_path.iterdir()) == ["machine.lock", "machine.lock.gate"]
diff --git a/tools/tests/test_unity_postmerge.py b/tools/tests/test_unity_postmerge.py
new file mode 100644
index 000000000..7cae46b28
--- /dev/null
+++ b/tools/tests/test_unity_postmerge.py
@@ -0,0 +1,512 @@
+import fcntl
+import json
+import os
+import plistlib
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+import unity_postmerge as up
+
+SHA = "0123456789abcdef0123456789abcdef01234567"
+PREV = "fedcba9876543210fedcba9876543210fedcba98"
+
+
+def results_xml(tmp_path: Path, cases: list[tuple[str, str, str]]) -> Path:
+ """An NUnit 3 result file as Unity's -testResults writes it: (fullname, result, message) per test case."""
+ failed = sum(1 for _, r, _ in cases if r == "Failed")
+ rows = []
+ for name, result, message in cases:
+ body = f"<failure><message><![CDATA[{message}]]></message></failure>" if result == "Failed" else ""
+ rows.append(f'<test-case fullname="{name}" name="{name.split(".")[-1]}" result="{result}">{body}</test-case>')
+ xml = (f'<?xml version="1.0" encoding="utf-8"?>\n<test-run id="2" testcasecount="{len(cases)}" '
+ f'result="{"Failed" if failed else "Passed"}" total="{len(cases)}" passed="{len(cases) - failed}" '
+ f'failed="{failed}" inconclusive="0" skipped="0"><test-suite type="TestSuite" name="Statecraft Israel">'
+ + "".join(rows) + "</test-suite></test-run>")
+ p = tmp_path / "results.xml"
+ p.write_text(xml, encoding="utf-8")
+ return p
+
+
+# --- change detection -------------------------------------------------------------------------------------------
+
+def test_a_tip_the_job_has_not_tested_is_new():
+ assert up.commit_to_test(SHA, {}) == SHA
+ assert up.commit_to_test(SHA, {"last_tested": PREV}) == SHA
+
+
+def test_the_tip_already_tested_is_not_run_again():
+ assert up.commit_to_test(SHA, {"last_tested": SHA}) is None
+
+
+def test_state_round_trips_and_a_missing_or_corrupt_file_is_empty(tmp_path):
+ p = tmp_path / "state.json"
+ assert up.load_state(p) == {}
+ up.save_state(p, {"last_tested": SHA, "issued": {SHA: "https://example.invalid/1"}})
+ assert up.load_state(p)["last_tested"] == SHA
+ p.write_text("{not json", encoding="utf-8")
+ assert up.load_state(p) == {}
+
+
+def test_the_tip_is_read_after_fetching_main():
+ calls = []
+
+ def git(*args):
+ calls.append(args)
+ return SHA + "\n" if args[0] == "rev-parse" else ""
+
+ assert up.fetch_tip(git) == SHA
+ assert calls[0] == ("fetch", "--quiet", "origin", "+refs/heads/main:refs/remotes/origin/main")
+ assert calls[1] == ("rev-parse", "--verify", "refs/remotes/origin/main^{commit}")
+
+
+def test_a_tip_that_is_not_a_full_sha_is_refused():
+ with pytest.raises(RuntimeError):
+ up.fetch_tip(lambda *a: "" if a[0] == "fetch" else "garbage\n")
+
+
+# --- results: 0 tests ran is a broken run, never a pass ---------------------------------------------------------
+
+def test_a_full_green_run_passes(tmp_path):
+ r = up.parse_results(results_xml(tmp_path, [("A.One", "Passed", ""), ("A.Two", "Passed", "")]))
+ assert (r.total, r.passed, r.failed, r.failures, r.broken) == (2, 2, 0, [], None)
+ assert up.passed(r, unity_exit=0)
+
+
+def test_zero_tests_ran_is_a_broken_run(tmp_path):
+ r = up.parse_results(results_xml(tmp_path, []))
+ assert r.total == 0 and r.broken and "0 tests" in r.broken
+ assert not up.passed(r, unity_exit=0)
+
+
+def test_a_missing_or_unreadable_result_file_is_a_broken_run(tmp_path):
+ assert up.parse_results(tmp_path / "absent.xml").broken
+ bad = tmp_path / "bad.xml"
+ bad.write_text("<test-run", encoding="utf-8")
+ r = up.parse_results(bad)
+ assert r.broken and not up.passed(r, unity_exit=0)
+
+
+def test_failing_tests_are_named_with_their_message(tmp_path):
+ r = up.parse_results(results_xml(tmp_path, [("HudTests.TheGddGameShowsItsScore", "Failed", "Expected 9 but was 11"),
+ ("A.Two", "Passed", "")]))
+ assert r.failed == 1 and r.failures == [("HudTests.TheGddGameShowsItsScore", "Expected 9 but was 11")]
+ assert not up.passed(r, unity_exit=2)
+
+
+def test_a_green_file_with_a_non_zero_unity_exit_is_not_a_pass(tmp_path):
+ r = up.parse_results(results_xml(tmp_path, [("A.One", "Passed", "")]))
+ assert not up.passed(r, unity_exit=1)
+
+
+def test_a_failed_count_without_a_named_case_still_fails(tmp_path):
+ p = results_xml(tmp_path, [("A.One", "Passed", "")])
+ p.write_text(p.read_text(encoding="utf-8").replace('failed="0"', 'failed="1"'), encoding="utf-8")
+ r = up.parse_results(p)
+ assert not up.passed(r, unity_exit=0)
+
+
+# --- duplicate-issue guard --------------------------------------------------------------------------------------
+
+def test_an_open_issue_for_the_same_sha_is_found_by_its_marker_or_title():
+ by_marker = [{"number": 7, "title": "something", "body": f"x\n{up.marker(SHA)}\n", "url": "u7"}]
+ by_title = [{"number": 8, "title": up.issue_title(SHA), "body": "", "url": "u8"}]
+ assert up.existing_issue(by_marker, SHA) == "u7"
+ assert up.existing_issue(by_title, SHA) == "u8"
+
+
+def test_an_issue_for_another_sha_is_not_a_duplicate():
+ other = [{"number": 9, "title": up.issue_title(PREV), "body": up.marker(PREV), "url": "u9"}]
+ assert up.existing_issue(other, SHA) is None
+ assert up.existing_issue([], SHA) is None
+
+
+class FakeGh:
+ def __init__(self, open_issues=(), labels=("area: unity", "bug"), fail_create=False):
+ self.open_issues, self.labels, self.fail_create = list(open_issues), list(labels), fail_create
+ self.created, self.comments = [], []
+
+ def __call__(self, args, stdin=None):
+ if args[:2] == ["issue", "list"]:
+ return json.dumps(self.open_issues)
+ if args[:2] == ["label", "list"]:
+ return json.dumps([{"name": n} for n in self.labels])
+ if args[:2] == ["issue", "comment"]:
+ if self.fail_create:
+ raise RuntimeError("gh failed")
+ self.comments.append((args, stdin))
+ return f"https://github.com/{up.REPO_SLUG}/issues/{args[2]}#issuecomment-{len(self.comments)}\n"
+ if args[:2] == ["issue", "create"]:
+ if self.fail_create:
+ raise RuntimeError("gh failed")
+ self.created.append((args, stdin))
+ url = f"https://github.com/{up.REPO_SLUG}/issues/{100 + len(self.created)}"
+ self.open_issues.append({"number": 100 + len(self.created), "title": args[args.index("--title") + 1],
+ "body": stdin, "url": url})
+ return url + "\n"
+ raise AssertionError(args)
+
+
+def test_report_opens_one_issue_with_the_label_and_records_it():
+ gh, state = FakeGh(), {}
+ url = up.report(gh, state, SHA, "title", f"body\n{up.marker(SHA)}")
+ assert url.endswith("/issues/101") and state["issued"][SHA] == url
+ args, body = gh.created[0]
+ assert args[args.index("--label") + 1] == "area: unity" and args[args.index("--repo") + 1] == up.REPO_SLUG
+ assert "--body-file" in args and body.startswith("body")
+
+
+def test_report_skips_the_label_when_the_repo_has_none():
+ gh = FakeGh(labels=("bug",))
+ up.report(gh, {}, SHA, "t", "b")
+ assert "--label" not in gh.created[0][0]
+
+
+def test_report_never_opens_a_second_issue_for_a_commit():
+ gh = FakeGh(open_issues=[{"number": 5, "title": up.issue_title(SHA), "body": "", "url": "u5"}])
+ state = {}
+ assert up.report(gh, state, SHA, "t", "b") == "u5" and gh.created == []
+ gh2 = FakeGh() # the first issue was closed, but this job already opened one for the commit
+ assert up.report(gh2, {"issued": {SHA: "u1"}}, SHA, "t", "b") == "u1" and gh2.created == []
+
+
+def test_a_new_failure_while_a_post_merge_issue_is_open_comments_on_it():
+ open_issue = {"number": 42, "title": up.issue_title(PREV), "body": f"b\n{up.marker(PREV)}", "url": "u42"}
+ unrelated = {"number": 7, "title": "a bug", "body": "no marker", "url": "u7"}
+ gh, state = FakeGh(open_issues=[unrelated, open_issue]), {}
+ url = up.report(gh, state, SHA, up.issue_title(SHA), f"body {SHA}\n{up.marker(SHA)}")
+ assert gh.created == [] and len(gh.comments) == 1
+ args, body = gh.comments[0]
+ assert args[2] == "42" and args[args.index("--repo") + 1] == up.REPO_SLUG and SHA in body
+ assert url.endswith("#issuecomment-1") and state["issued"][SHA] == url
+ assert up.report(gh, state, SHA, "t", "b") == url and len(gh.comments) == 1 # never twice for one commit
+
+
+def test_the_oldest_open_post_merge_issue_gets_the_comment():
+ issues = [{"number": n, "title": "x", "body": up.marker(f"{n:040x}"), "url": f"u{n}"} for n in (50, 12, 31)]
+ gh = FakeGh(open_issues=issues)
+ up.report(gh, {}, SHA, "t", "b")
+ assert gh.comments[0][0][2] == "12"
+
+
+def test_a_failed_comment_raises_and_records_nothing():
+ gh = FakeGh(open_issues=[{"number": 42, "title": "x", "body": up.marker(PREV), "url": "u42"}], fail_create=True)
+ state = {}
+ with pytest.raises(RuntimeError):
+ up.report(gh, state, SHA, "t", "b")
+ assert SHA not in state.get("issued", {})
+
+
+def test_a_failed_create_raises_and_records_nothing():
+ gh, state = FakeGh(fail_create=True), {}
+ with pytest.raises(RuntimeError):
+ up.report(gh, state, SHA, "t", "b")
+ assert SHA not in state.get("issued", {})
+
+
+# --- issue body -------------------------------------------------------------------------------------------------
+
+def test_the_issue_body_has_the_sha_failing_tests_log_tail_and_marker(tmp_path):
+ r = up.parse_results(results_xml(tmp_path, [("HudTests.TheGddGameShowsItsScore", "Failed", "Expected 9 but was 11"),
+ ("A.Two", "Passed", "")]))
+ log = "\n".join(f"line {i}" for i in range(500)) + "\nAssets/X.cs(81,48): error CS0103: The name 'MvpSlice'\n"
+ body = up.issue_body(SHA, PREV, r, unity_exit=2, log_text=log, commits="abc1234 Merge #600")
+ assert SHA in body and up.marker(SHA) in body
+ assert "HudTests.TheGddGameShowsItsScore" in body and "Expected 9 but was 11" in body
+ assert "line 499" in body and "line 10\n" not in body # the tail, not the whole log
+ assert "error CS0103" in body # compile errors are pulled out
+ assert f"{PREV[:12]}..{SHA[:12]}" in body and "abc1234 Merge #600" in body
+ assert "1 failed of 2" in body and "Unity exit code: 2" in body
+ assert len(body) < 60000
+
+
+def test_a_broken_run_body_says_why_and_never_claims_a_pass(tmp_path):
+ r = up.parse_results(results_xml(tmp_path, []))
+ body = up.issue_body(SHA, None, r, unity_exit=0, log_text="Scripts have compiler errors.", commits="")
+ assert "Broken run" in body and "0 tests" in body and "compiler errors" in body
+ assert "passed" not in up.issue_title(SHA).lower()
+
+
+def test_a_huge_failure_list_is_cut_to_fit_an_issue(tmp_path):
+ cases = [(f"T.Case{i}", "Failed", "m" * 2000) for i in range(400)]
+ r = up.parse_results(results_xml(tmp_path, cases))
+ body = up.issue_body(SHA, PREV, r, unity_exit=2, log_text="x\n" * 5000, commits="")
+ assert len(body) < 60000 and "T.Case0" in body and "more" in body
+
+
+# --- the Unity command and the plist ----------------------------------------------------------------------------
+
+def test_unity_runs_under_the_shared_lock_with_graphics_and_ci_flags_off(tmp_path):
+ cmd = up.unity_command(Path("/wt"), "6000.3.25f1", tmp_path / "r.xml", tmp_path / "u.log")
+ lock = cmd.index("--shared")
+ assert cmd[:3] == ["uv", "run", str(up.TOOLS / "machine_lock.py")]
+ assert cmd[lock + 1:lock + 4] == ["--wait-unity", "--timeout", "14400"] and "--" in cmd
+ unity = cmd[cmd.index("--") + 1:]
+ assert unity[0] == "/Applications/Unity/Hub/Editor/6000.3.25f1/Unity.app/Contents/MacOS/Unity"
+ assert "-nographics" not in cmd
+ for flag in ("-CI", "-GITHUB_ACTIONS", "-TF_BUILD"):
+ assert unity[unity.index(flag) + 1] == "false"
+ assert unity[unity.index("-testPlatform") + 1] == "EditMode" and "-runTests" in unity
+ assert unity[unity.index("-projectPath") + 1] == "/wt/unity"
+ assert unity[unity.index("-testResults") + 1] == str(tmp_path / "r.xml")
+
+
+def test_the_plist_template_polls_no_more_often_than_every_ten_minutes():
+ text = (up.TOOLS / "unity_postmerge.plist.in").read_text(encoding="utf-8")
+ filled = up.fill_plist(text, uv="/opt/uv", repo="/r", home="/h", path="/usr/bin:/bin")
+ plist = plistlib.loads(filled.encode())
+ assert plist["StartInterval"] >= 600
+ assert plist["Label"] == up.LABEL_ID and "@" not in filled
+
+
+# --- a hung Unity is stopped by the PID machine_lock recorded ----------------------------------------------------
+
+def _locked(tmp_path, *code):
+ return [sys.executable, str(up.TOOLS / "machine_lock.py"), "--shared", "--", sys.executable, "-c", *code]
+
+
+def _alive(pid):
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ # a zombie (exited, not yet reaped) counts as gone
+ st = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True).stdout.strip()
+ return bool(st) and not st.startswith("Z")
+
+
+def _lock_is_free(lock):
+ with open(lock, "a+") as f:
+ try:
+ fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ return False
+ fcntl.flock(f, fcntl.LOCK_UN)
+ return True
+
+
[email protected]("ignores_term", [False, True])
+def test_a_hung_unity_is_stopped_by_pid_and_the_lock_is_released(tmp_path, monkeypatch, ignores_term):
+ lock = tmp_path / "machine.lock"
+ monkeypatch.setenv("STATECRAFT_MACHINE_LOCK", str(lock))
+ hang = ("import signal, time\n" + ("signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" if ignores_term else "")
+ + "time.sleep(600)")
+ started = time.monotonic()
+ with open(tmp_path / "out.log", "w") as out:
+ code, stopped = up.run_with_timeout(_locked(tmp_path, hang), tmp_path / "holder", timeout=1.5, grace=1.0,
+ poll=0.1, cwd=tmp_path, stdout=out)
+ assert stopped is not None and not _alive(stopped)
+ assert code != 0 and time.monotonic() - started < 60
+ assert _lock_is_free(lock), "machine_lock still holds the lock after the timeout"
+
+
+def test_a_unity_that_finishes_in_time_is_left_alone(tmp_path, monkeypatch):
+ monkeypatch.setenv("STATECRAFT_MACHINE_LOCK", str(tmp_path / "machine.lock"))
+ with open(tmp_path / "out.log", "w") as out:
+ code, stopped = up.run_with_timeout(_locked(tmp_path, "import sys; sys.exit(2)"), tmp_path / "holder",
+ timeout=30, grace=1, poll=0.1, cwd=tmp_path, stdout=out)
+ assert (code, stopped) == (2, None)
+
+
+def test_the_clock_starts_when_unity_starts_not_while_waiting_for_the_lock(tmp_path, monkeypatch):
+ lock = tmp_path / "machine.lock"
+ monkeypatch.setenv("STATECRAFT_MACHINE_LOCK", str(lock))
+ with open(lock, "a+") as held:
+ fcntl.flock(held, fcntl.LOCK_EX) # someone else holds the machine for 2 s, longer than the timeout
+ timer = threading.Timer(2.0, lambda: fcntl.flock(held, fcntl.LOCK_UN))
+ timer.start()
+ with open(tmp_path / "out.log", "w") as out:
+ code, stopped = up.run_with_timeout(_locked(tmp_path, "import time; time.sleep(0.5)"), tmp_path / "holder",
+ timeout=1.5, grace=1, poll=0.1, cwd=tmp_path, stdout=out)
+ timer.join()
+ assert (code, stopped) == (0, None)
+
+
+def test_a_timed_out_run_is_reported_as_a_timeout():
+ r = up.timed_out(4242, 90)
+ assert r.broken and "timed out" in r.broken and "4242" in r.broken and not up.passed(r, unity_exit=0)
+
+
+# --- the launcher runs the script from the worktree, at origin/main ---------------------------------------------
+
+STUB = """import json, os, sys
+from pathlib import Path
+Path(sys.argv[sys.argv.index("--home") + 1], "ran.json").write_text(json.dumps(
+ {"version": VERSION, "argv": sys.argv[1:], "file": __file__, "locked": os.environ.get("UNITY_POSTMERGE_LOCKED")}))
+"""
+
+
+def _git(cwd, *args):
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
+
+
+def _push_stub(src, version):
+ (src / "tools").mkdir(exist_ok=True)
+ (src / "tools" / "unity_postmerge.py").write_text(f"VERSION = {version}\n" + STUB)
+ _git(src, "add", "-A")
+ _git(src, "-c", "user.name=t", "-c", "[email protected]", "commit", "-qm", f"v{version}")
+ _git(src, "push", "-q", "origin", "HEAD:main")
+ return _git(src, "rev-parse", "HEAD")
+
+
+def test_the_launcher_runs_the_merged_script_from_the_worktree(tmp_path):
+ origin, src, repo, home = (tmp_path / n for n in ("origin.git", "src", "repo", "home"))
+ _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(origin))
+ _git(tmp_path, "clone", "-q", str(origin), str(src))
+ first = _push_stub(src, 1)
+ _git(tmp_path, "clone", "-q", str(origin), str(repo))
+ home.mkdir()
+ fake_uv = tmp_path / "uv"
+ fake_uv.write_text(f"#!/bin/sh\nshift\nexec {sys.executable} \"$@\"\n")
+ fake_uv.chmod(0o755)
+ launch = [sys.executable, str(up.TOOLS / "unity_postmerge_launch.py"), "--uv", str(fake_uv), "--repo", str(repo),
+ "--home", str(home)]
+
+ assert subprocess.run(launch).returncode == 0
+ ran = json.loads((home / "ran.json").read_text())
+ wt = home / "worktree"
+ assert ran["version"] == 1 and Path(ran["file"]).resolve() == (wt / "tools" / "unity_postmerge.py").resolve()
+ assert ran["locked"] == "1" and _git(wt, "rev-parse", "HEAD") == first
+ assert ran["argv"] == ["--repo", str(repo), "--home", str(home)]
+
+ second = _push_stub(src, 2) # a merged change to the script takes effect on the next run
+ assert subprocess.run(launch).returncode == 0
+ assert json.loads((home / "ran.json").read_text())["version"] == 2 and _git(wt, "rev-parse", "HEAD") == second
+ assert _git(repo, "status", "--porcelain") == "" # the main checkout's working tree is never touched
+
+ (home / "ran.json").unlink()
+ with open(home / "run.lock", "a+") as held: # a run in progress: the launcher leaves the worktree alone
+ fcntl.flock(held, fcntl.LOCK_EX)
+ _push_stub(src, 3)
+ assert subprocess.run(launch).returncode == 0
+ assert not (home / "ran.json").exists() and _git(wt, "rev-parse", "HEAD") == second
+
+
+def test_the_plist_runs_the_launcher_from_the_job_folder():
+ text = (up.TOOLS / "unity_postmerge.plist.in").read_text(encoding="utf-8")
+ plist = plistlib.loads(up.fill_plist(text, uv="/opt/uv", repo="/r", home="/h", path="/usr/bin").encode())
+ assert plist["ProgramArguments"] == ["/opt/uv", "run", "/h/unity_postmerge_launch.py", "--uv", "/opt/uv",
+ "--repo", "/r", "--home", "/h"]
+
+
+# --- privacy: the log tail goes into a public issue -------------------------------------------------------------
+
+# Assembled at run time so the repo's own home-path and email checks (scripts/oss/check_repo.py) pass on this file.
+USERS, HOME_ROOT, AT = "/" + "Users", "/" + "home", "@"
+LOG_WITH_IDENTIFIERS = f"""\
+Built from '6000.3/staging' branch; Version is '6000.3.25f1'; mode is 'batchmode'
+Command line arguments:
+ /Applications/Unity/Hub/Editor/6000.3.25f1/Unity.app/Contents/MacOS/Unity -batchmode -projectPath {USERS}/someone/israel-game/unity
+[Licensing::Module] Trying to connect to existing licensing client channel...
+[Licensing::IpcConnector] LicenseClient-someone channel disconnected successfully.
+Launching external process: /Applications/Unity/Hub/Editor/6000.3.25f1/Unity.app/Contents/Frameworks/UnityLicensingClient.app --namedPipe Unity-LicenseClient-someone-6000.3.25
+[Licensing::Client] Successfully resolved entitlement details for Someone.Person+unity{AT}example.co.il
+Loading package cache from {USERS}/someone/Library/Unity/cache/packages
+Assets/Scripts/Hud/WhyPresenter.cs(81,48): error CS0103: The name 'MvpSlice' does not exist
+{USERS}/someone/.cache/statecraft/unity-postmerge/worktree/unity/Assets/X.cs(3,1): error CS1002: ; expected
+Saved to ~/x by SOMEONE (owner: someone{AT}gmail.com)
+"""
+
+
+def someone(monkeypatch):
+ """The machine's user is `someone`, with its home folder under /Users."""
+ monkeypatch.setenv("HOME", f"{USERS}/someone")
+ monkeypatch.setenv("USER", "someone")
+ monkeypatch.setattr(up.getpass, "getuser", lambda: "someone")
+
+
+def test_redaction_leaves_no_home_user_name_or_email(someone):
+ out = up.redact(LOG_WITH_IDENTIFIERS)
+ assert "someone" not in out.lower() and "@" not in out
+ assert "~/israel-game/unity" in out and "LicenseClient-<user>" in out and "<email>" in out
+ assert "error CS0103" in out and "6000.3.25f1" in out # the useful part survives
+
+
+def test_redaction_also_covers_another_users_home_and_licence_pipe(monkeypatch):
+ monkeypatch.setenv("HOME", f"{USERS}/owner")
+ monkeypatch.setenv("USER", "owner")
+ monkeypatch.setattr(up.getpass, "getuser", lambda: "owner")
+ out = up.redact(f"{USERS}/someone/x LicenseClient-someone-6000.3.25 {HOME_ROOT}/someone/y")
+ assert "someone" not in out and "LicenseClient-<user>-6000.3.25" in out
+
+
+def test_the_issue_body_carries_no_identifier_from_the_log_or_test_messages(tmp_path, someone):
+ r = up.parse_results(results_xml(tmp_path, [("A.One", "Failed", f"at {USERS}/someone/israel-game/unity/A.cs:3 "
+ f"mail someone{AT}example.com")]))
+ body = up.issue_body(SHA, PREV, r, unity_exit=2, log_text=LOG_WITH_IDENTIFIERS, commits="abc1234 Merge #600")
+ assert "someone" not in body.lower() and "@" not in body
+ assert "error CS0103" in body and "A.One" in body and "Last 80 lines" in body
+
+
+def test_a_redaction_that_raises_withholds_the_log(tmp_path, someone, monkeypatch):
+ def boom(text):
+ raise ValueError("redaction broke")
+ monkeypatch.setattr(up, "redact", boom)
+ r = up.parse_results(results_xml(tmp_path, [("A.One", "Failed", f"at {USERS}/someone/A.cs someone{AT}example.com")]))
+ body = up.issue_body(SHA, PREV, r, unity_exit=2, log_text=LOG_WITH_IDENTIFIERS, commits="abc1234 Merge #600")
+ assert "someone" not in body.lower() and "@" not in body
+ assert "log withheld" in body.lower() and "error CS" not in body and "Last 80 lines" not in body
+ assert "A.One" in body and SHA in body and up.marker(SHA) in body # still a usable report
+
+
+def test_the_report_says_what_the_job_does_now_not_one_issue_per_commit(tmp_path):
+ body = up.issue_body(SHA, PREV, up.Results(broken="x"), unity_exit=1, log_text="", commits="")
+ assert "one issue per commit" not in body
+ assert "comment" in body
+
+
+# --- fail-silent: no result for main's tip within the bound -----------------------------------------------------
+
+def test_the_stale_bound_covers_the_lock_wait_and_the_unity_timeout():
+ assert up.STALE_AFTER == up.LOCK_TIMEOUT + up.UNITY_TIMEOUT_MIN * 60 + 30 * 60 == 6 * 3600
+
+
+def test_a_tip_with_no_result_past_the_bound_is_stale():
+ t0 = 1_800_000_000
+ log = f"2026-10-16T00:00:00Z {PREV} PASS exit=0 total=9\n"
+ assert up.stale_note(log, SHA, t0, t0 + up.STALE_AFTER + 1, {}) is not None
+ assert up.stale_note(log, SHA, t0, t0 + up.STALE_AFTER - 1, {}) is None # still inside the bound
+ assert up.stale_note(log + f"x {SHA} FAIL exit=2\n", SHA, t0, t0 + 10**6, {}) is None # it has a result
+ assert up.stale_note(log, SHA, t0, t0 + 10**6, {"last_tested": SHA}) is None
+ assert up.stale_note(log + f"x {SHA} STALE no result\n", SHA, t0, t0 + 10**6, {}) is None # said once
+
+
+def test_an_expired_gh_login_makes_the_job_log_stale_instead_of_staying_silent(tmp_path, monkeypatch):
+ home = tmp_path / "job"
+ home.mkdir()
+ up.save_state(home / "state.json", {"last_tested": PREV, "pending": {"sha": PREV, "title": "t", "body": "b"}})
+ (home / "results.log").write_text(f"2026-10-16T00:00:00Z {PREV} FAIL exit=2\n")
+ monkeypatch.setattr(up, "fetch_tip", lambda git: SHA)
+ monkeypatch.setattr(up, "commit_time", lambda git, sha: time.time() - up.STALE_AFTER - 60)
+
+ def gh(args, stdin=None):
+ raise RuntimeError("gh: authentication required")
+ monkeypatch.setattr(up, "_gh", gh)
+ assert up.main(["--repo", str(tmp_path), "--home", str(home)]) == 1
+ log = (home / "results.log").read_text()
+ assert f" {SHA} STALE " in log and "6 h" in log
+ assert up.main(["--repo", str(tmp_path), "--home", str(home)]) == 1
+ assert (home / "results.log").read_text().count("STALE") == 1 # once per tip, not every 15 minutes
+
+
+def test_a_broken_run_reason_with_git_stderr_carries_no_identifier(someone):
+ r = up.Results(broken=f"the worktree could not be prepared: fatal: cannot lock ref in {USERS}/someone/.cache/"
+ f"statecraft/unity-postmerge/worktree (committer someone{AT}example.com)")
+ body = up.issue_body(SHA, PREV, r, unity_exit=-1, log_text="", commits=f"abc1234 Fix by someone{AT}example.com")
+ assert "someone" not in body.lower() and "@" not in body
+ assert "Broken run" in body and "could not be prepared" in body and "~/.cache/statecraft" in body
+
+
+def test_a_redaction_that_raises_withholds_the_broken_run_reason_too(someone, monkeypatch):
+ def boom(text):
+ raise ValueError("redaction broke")
+ monkeypatch.setattr(up, "redact", boom)
+ r = up.Results(broken=f"the worktree could not be prepared: {USERS}/someone/x someone{AT}example.com")
+ body = up.issue_body(SHA, PREV, r, unity_exit=-1, log_text="", commits="")
+ assert "someone" not in body.lower() and "@" not in body
+ assert "Broken run" in body and "log withheld" in body.lower()
diff --git a/tools/unity_postmerge.plist.in b/tools/unity_postmerge.plist.in
new file mode 100644
index 000000000..fbd096300
--- /dev/null
+++ b/tools/unity_postmerge.plist.in
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!-- launchd job for tools/unity_postmerge.py (T72). Filled in and installed by hand, outside the repository:
+ see the "Post-merge Unity run" section of tools/README.md. @UV@, @REPO@, @HOME@ and @PATH@ are replaced
+ on install. It runs the launcher copied into the job folder (@HOME@), which runs tools/unity_postmerge.py from
+ the job's worktree at origin/main. launchd never starts a second copy while one is running. -->
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.statecraft.unity-postmerge</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>@UV@</string>
+ <string>run</string>
+ <string>@HOME@/unity_postmerge_launch.py</string>
+ <string>--uv</string>
+ <string>@UV@</string>
+ <string>--repo</string>
+ <string>@REPO@</string>
+ <string>--home</string>
+ <string>@HOME@</string>
+ </array>
+ <key>WorkingDirectory</key>
+ <string>@HOME@</string>
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PATH</key>
+ <string>@PATH@</string>
+ </dict>
+ <!-- Every 15 minutes (never under 10). -->
+ <key>StartInterval</key>
+ <integer>900</integer>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>StandardOutPath</key>
+ <string>@HOME@/launchd.log</string>
+ <key>StandardErrorPath</key>
+ <string>@HOME@/launchd.log</string>
+</dict>
+</plist>
diff --git a/tools/unity_postmerge.py b/tools/unity_postmerge.py
new file mode 100644
index 000000000..a8556a983
--- /dev/null
+++ b/tools/unity_postmerge.py
@@ -0,0 +1,525 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""Post-merge Unity EditMode watcher for the owner's Mac (T72; owner, 16 October 2026: "Approve, failures to issue").
+
+CI cannot run Unity (CONTRIBUTING.md, "What CI runs"), so two PRs can each be green and still break Unity together on
+`main`. A launchd job (tools/unity_postmerge.plist.in) runs this script every 15 minutes. Each run:
+
+1. fetches origin/main in the main checkout and reads its tip. If the tip is the commit this job last tested, it stops.
+ Only the tip is tested: when several commits landed since the last run, the issue lists them all (`prev..tip`).
+2. checks the tip out in its own worktree (~/.cache/statecraft/unity-postmerge/worktree, forced, `git clean -ffdx`
+ except unity/Library and the Unity-MCP NuGet download). The first run APFS-clones the main checkout's Library.
+ launchd starts tools/unity_postmerge_launch.py, which moves this worktree to origin/main and runs this script from
+ it, so a merged change to the script takes effect on the next run.
+3. builds the sim DLLs (tools/build_sim_for_unity.py), then runs the full EditMode suite through
+ `machine_lock.py --shared --wait-unity --timeout 14400`, never with -nographics, and afterwards reverts
+ unity/ProjectSettings and unity/Assets/Settings (also on an exception). A Unity still running after
+ --unity-timeout-min (90) minutes, counted from its start, is stopped by the PID machine_lock recorded for it
+ (SIGTERM, then SIGKILL after 60 s), never by name, and the run is reported as timed out.
+4. passes only when Unity exits 0 and its result file names at least one test and no failure. A pass appends one line
+ to results.log and nothing else. Anything else (failing tests, 0 tests, no result file, a compile error, a sim build
+ failure, a lock or Unity timeout) is reported once for that commit, with the SHA, the range since the last tested
+ commit, the failing test names and the log tail. When an issue this job opened is still open (main is still
+ broken), the report is a comment on it; otherwise it is a new issue, labelled `area: unity` when the label exists.
+ An open issue that already names the commit, or the job's own record of every commit it reported, means no report.
+ The log tail, compile errors, test messages, broken-run reason and commit list are redacted first (redact():
+ email addresses, the home folder, the user name); if redacting raises, the report says "Log withheld" and
+ carries none of them.
+5. deletes unity/Builds, Temp and Logs in the worktree, keeps the last KEEP_RUNS run folders, and deletes the
+ worktree's Library when it grows past --cap-gb (the next run clones it again).
+
+If main's tip has no PASS or FAIL line in results.log STALE_AFTER (6 h) after it was committed, each run until then
+appends one STALE line for it to results.log (and launchd.log), so a job that is stuck or cannot report is visible.
+
+If opening the issue fails, the report is kept in the state file and retried on the next run without running Unity
+again. The state is advanced only after a pass is logged or the issue exists. It uses the existing `gh` login and
+never reads, prints or stores a token.
+
+Usage: uv run tools/unity_postmerge.py [--repo PATH] [--home DIR] [--cap-gb N] [--unity-timeout-min N] [--dry-run]
+--dry-run runs everything but prints the issue instead of opening it and leaves the state file alone.
+Exit 0 when nothing was new, the commit passed or its issue exists; 1 when fetching or reporting failed."""
+from __future__ import annotations
+
+import argparse
+import fcntl
+import getpass
+import json
+import os
+import re
+import shutil
+import subprocess
+import signal
+import sys
+import time
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+
+import machine_lock # tools/: the holder record that names the Unity process to stop on a timeout
+
+TOOLS = Path(__file__).resolve().parent
+REPO_SLUG = "eyalgolan/statecraft-israel"
+LABEL = "area: unity"
+LABEL_ID = "com.statecraft.unity-postmerge"
+LOCK_TIMEOUT = 14400
+UNITY_TIMEOUT_MIN = 90 # from Unity's start, not counting the lock wait
+UNITY_GRACE = 60 # seconds between SIGTERM and SIGKILL
+LOCKED_ENV = "UNITY_POSTMERGE_LOCKED" # set by unity_postmerge_launch.py, which already holds run.lock
+KEEP_RUNS = 10
+LOG_TAIL = 80
+MAX_FAILURES = 50
+MAX_MESSAGE = 500
+# Kept between runs: Unity's import cache, and the Unity-MCP plugin's NuGet download (it fetches it on first open).
+KEEP = ("/unity/Library/", "/unity/Assets/Plugins/NuGet/", "/unity/Assets/Plugins/NuGet.meta")
+SHA_RE = re.compile(r"^[0-9a-f]{40}$")
+# No result (PASS or FAIL) for main's tip this long after the commit means the job is stuck or failing quietly: the
+# longest legitimate run is the lock wait (LOCK_TIMEOUT), Unity (UNITY_TIMEOUT_MIN) and 30 min for the poll and build.
+STALE_AFTER = LOCK_TIMEOUT + UNITY_TIMEOUT_MIN * 60 + 30 * 60 # 6 h
+EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+")
+HOME_RE = re.compile(r"(/Users/|/home/)[^/\s'\"]+")
+PIPE_RE = re.compile(r"(LicenseClient-)[^\s/'\"]+?(?=-\d|[\s/'\"]|$)")
+
+
+# --- change detection -------------------------------------------------------------------------------------------
+
+def load_state(path: Path) -> dict:
+ try:
+ state = json.loads(path.read_text(encoding="utf-8"))
+ return state if isinstance(state, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def save_state(path: Path, state: dict) -> None:
+ tmp = path.with_name(path.name + ".tmp")
+ tmp.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ os.replace(tmp, path)
+
+
+def fetch_tip(git) -> str:
+ git("fetch", "--quiet", "origin", "+refs/heads/main:refs/remotes/origin/main")
+ tip = git("rev-parse", "--verify", "refs/remotes/origin/main^{commit}").strip()
+ if not SHA_RE.match(tip):
+ raise RuntimeError(f"origin/main did not resolve to a commit: {tip!r}")
+ return tip
+
+
+def commit_to_test(tip: str, state: dict) -> str | None:
+ return None if state.get("last_tested") == tip else tip
+
+
+def commit_time(git, sha: str) -> int:
+ return int(git("show", "-s", "--format=%ct", sha).strip())
+
+
+def stale_note(log_text: str, tip: str, tip_epoch: float, now: float, state: dict) -> str | None:
+ """A results.log line when main's tip has no PASS or FAIL line STALE_AFTER after it was committed (and none was
+ logged for it yet), so a job that is stuck or failing quietly shows in results.log, not only in launchd.log."""
+ if state.get("last_tested") == tip or re.search(rf" {tip} (PASS|FAIL|STALE) ", log_text + " "):
+ return None
+ age = now - tip_epoch
+ if age <= STALE_AFTER:
+ return None
+ return (f"{tip} STALE no PASS or FAIL logged {age / 3600:.1f} h after the commit (bound {STALE_AFTER // 3600} h); "
+ "see launchd.log")
+
+
+# --- results ----------------------------------------------------------------------------------------------------
+
+@dataclass
+class Results:
+ total: int = 0
+ passed: int = 0
+ failed: int = 0
+ failures: list[tuple[str, str]] = field(default_factory=list)
+ broken: str | None = None
+
+
+def parse_results(path: Path) -> Results:
+ """Unity's NUnit 3 result file. A missing or unreadable file, or one with 0 tests, is a broken run (never a pass)."""
+ if not path.is_file():
+ return Results(broken=f"no result file was written ({path.name}): Unity did not run the tests")
+ try:
+ root = ET.parse(path).getroot()
+ except ET.ParseError as e:
+ return Results(broken=f"the result file could not be read: {e}")
+ r = Results(total=int(root.get("total", 0)), passed=int(root.get("passed", 0)), failed=int(root.get("failed", 0)))
+ for case in root.iter("test-case"):
+ if case.get("result") == "Failed":
+ message = (case.findtext("failure/message") or "").strip()
+ r.failures.append((case.get("fullname") or case.get("name") or "?", message))
+ if r.total == 0:
+ r.broken = "0 tests ran: a broken run (the suite did not load, or the filter matched nothing)"
+ return r
+
+
+def timed_out(pid: int, minutes: float) -> Results:
+ return Results(broken=f"timed out: Unity (PID {pid}) ran longer than {minutes:g} min and was stopped")
+
+
+def passed(r: Results, unity_exit: int) -> bool:
+ return unity_exit == 0 and r.broken is None and r.total > 0 and r.failed == 0 and not r.failures
+
+
+# --- issues -----------------------------------------------------------------------------------------------------
+
+MARKER_PREFIX = "<!-- unity-postmerge sha="
+
+
+def marker(sha: str) -> str:
+ return f"{MARKER_PREFIX}{sha} -->"
+
+
+def issue_title(sha: str) -> str:
+ return f"Unity EditMode broken on main at {sha[:12]} ({sha})"
+
+
+def existing_issue(issues: list[dict], sha: str) -> str | None:
+ for i in issues:
+ if marker(sha) in (i.get("body") or "") or sha in (i.get("title") or ""):
+ return i.get("url") or f"#{i.get('number')}"
+ return None
+
+
+def redact(text: str) -> str:
+ """Strip what identifies the Mac's owner before text goes into a public issue: every email address, the home
+ folder (to ~), any /Users/<name> or /home/<name>, Unity's LicenseClient-<name> pipe, and the user name itself."""
+ text = EMAIL_RE.sub("<email>", text)
+ for home in {os.environ.get("HOME", ""), str(Path.home())}:
+ if len(home.rstrip("/")) > 1:
+ text = text.replace(home.rstrip("/"), "~")
+ text = HOME_RE.sub(r"\1<user>", text)
+ text = PIPE_RE.sub(r"\1<user>", text)
+ for user in {getpass.getuser(), os.environ.get("USER", "")}:
+ if user:
+ text = re.sub(re.escape(user), "<user>", text, flags=re.IGNORECASE)
+ return text
+
+
+def _tail(text: str, n: int) -> str:
+ return "\n".join(text.splitlines()[-n:])
+
+
+def _fence(text: str) -> str:
+ return "```\n" + text.replace("```", "'''") + "\n```"
+
+
+def issue_body(sha: str, prev: str | None, r: Results, unity_exit: int, log_text: str, commits: str) -> str:
+ rng = f"{prev[:12]}..{sha[:12]}" if prev else sha[:12]
+ try: # fail closed: if redacting fails, no log text and no test message leaves the Mac
+ log_text, commits = redact(log_text), redact(commits)
+ broken = redact(r.broken) if r.broken else None # e.g. git's stderr when the worktree can't be prepared
+ failures, withheld = [(redact(n), redact(m)) for n, m in r.failures], None
+ except Exception as e: # noqa: BLE001 (any error withholds; only its type is shown, never its text)
+ log_text, failures = "", [(n, "") for n, _ in r.failures]
+ broken = "details withheld (see below)" if r.broken else None
+ withheld = (f"Log withheld: redacting it failed ({type(e).__name__}), so the log tail, compile errors, "
+ "test messages and the broken-run reason stay in the run folder on the Mac.")
+ out = [f"The post-merge Unity EditMode run (tools/unity_postmerge.py, on the owner's Mac) did not pass on `main` "
+ f"at {sha}.", "", f"- Commit: https://github.com/{REPO_SLUG}/commit/{sha}"]
+ if prev:
+ out.append(f"- Untested since the last run: {rng} (https://github.com/{REPO_SLUG}/compare/{prev}...{sha})")
+ out.append(f"- Unity exit code: {unity_exit}")
+ if broken:
+ out.append(f"- **Broken run:** {broken}")
+ else:
+ out.append(f"- Result: {r.failed} failed of {r.total} ({r.passed} passed)")
+ if commits.strip():
+ out += ["", f"Commits in {rng}:", _fence(_tail(commits.strip(), 30))]
+ if failures:
+ out += ["", "Failing tests:"]
+ for name, message in failures[:MAX_FAILURES]:
+ msg = " ".join(message.split())
+ msg = msg[:MAX_MESSAGE] + ("..." if len(msg) > MAX_MESSAGE else "")
+ out.append(f"- `{name}`" + (f": {msg}" if msg else ""))
+ if len(r.failures) > MAX_FAILURES:
+ out.append(f"- ... and {len(r.failures) - MAX_FAILURES} more (see the result file on the Mac)")
+ errors = [line for line in log_text.splitlines() if "error CS" in line]
+ if errors:
+ out += ["", "Compile errors:", _fence("\n".join(dict.fromkeys(errors))[:8000])]
+ if withheld:
+ out += ["", withheld]
+ else:
+ out += ["", f"Last {LOG_TAIL} lines of the Unity log (home folder, user name and email addresses redacted):",
+ _fence(_tail(log_text, LOG_TAIL)[-20000:])]
+ out += ["", "Run on the commit itself, in a clean worktree. While `main` stays broken, each newly failing commit "
+ "is a comment on this issue, not a new issue. Close this when `main` is green again.", marker(sha)]
+ return "\n".join(out)
+
+
+def open_postmerge_issue(issues: list[dict]) -> dict | None:
+ """The oldest open issue this job opened (its body carries a marker), the one a still-broken main is reported on."""
+ ours = [i for i in issues if MARKER_PREFIX in (i.get("body") or "")]
+ return min(ours, key=lambda i: int(i["number"])) if ours else None
+
+
+def report(gh, state: dict, sha: str, title: str, body: str) -> str:
+ """Report a commit once: nothing when this job already reported it or an open issue names it; a comment on the open
+ post-merge issue when there is one (main is still broken); otherwise a new issue."""
+ issued = state.setdefault("issued", {})
+ if sha in issued:
+ return issued[sha]
+ issues = json.loads(gh(["issue", "list", "--repo", REPO_SLUG, "--state", "open", "--limit", "1000",
+ "--json", "number,title,body,url"]))
+ found = existing_issue(issues, sha)
+ if found:
+ issued[sha] = found
+ return found
+ if still_open := open_postmerge_issue(issues):
+ url = gh(["issue", "comment", str(still_open["number"]), "--repo", REPO_SLUG, "--body-file", "-"],
+ stdin=f"Still broken at {sha}.\n\n{body}").strip().splitlines()[-1]
+ issued[sha] = url
+ return url
+ labels = {lab["name"] for lab in json.loads(gh(["label", "list", "--repo", REPO_SLUG, "--limit", "500",
+ "--json", "name"]))}
+ args = ["issue", "create", "--repo", REPO_SLUG, "--title", title, "--body-file", "-"]
+ if LABEL in labels:
+ args += ["--label", LABEL]
+ url = gh(args, stdin=body).strip().splitlines()[-1]
+ issued[sha] = url
+ return url
+
+
+# --- running ----------------------------------------------------------------------------------------------------
+
+def unity_path(version: str) -> str:
+ return f"/Applications/Unity/Hub/Editor/{version}/Unity.app/Contents/MacOS/Unity"
+
+
+def unity_command(wt: Path, version: str, xml: Path, log: Path) -> list[str]:
+ return ["uv", "run", str(TOOLS / "machine_lock.py"), "--shared", "--wait-unity", "--timeout", str(LOCK_TIMEOUT),
+ "--", unity_path(version), "-batchmode", "-CI", "false", "-GITHUB_ACTIONS", "false", "-TF_BUILD", "false",
+ "-projectPath", str(wt / "unity"), "-buildTarget", "OSXUniversal", "-runTests", "-testPlatform", "EditMode",
+ "-testResults", str(xml), "-logFile", str(log)]
+
+
+def fill_plist(text: str, *, uv: str, repo: str, home: str, path: str) -> str:
+ for key, value in (("UV", uv), ("REPO", repo), ("HOME", home), ("PATH", path)):
+ text = text.replace(f"@{key}@", value)
+ return text
+
+
+def _parent(pid: int) -> int | None:
+ out = subprocess.run(["ps", "-o", "ppid=", "-p", str(pid)], capture_output=True, text=True).stdout.strip()
+ return int(out) if out.isdigit() else None
+
+
+def _holder(record: Path) -> tuple[int, int] | None:
+ try:
+ lock_pid, child = (int(x) for x in record.read_text().split())
+ return lock_pid, child
+ except (OSError, ValueError):
+ return None
+
+
+def run_with_timeout(cmd: list[str], record: Path, *, timeout: float, grace: float, poll: float = 5.0, cwd: Path,
+ stdout) -> tuple[int, int | None]:
+ """Run `cmd` (machine_lock.py wrapping Unity). The clock starts when machine_lock records the command it started
+ (machine_lock.HOLDER_ENV), so waiting for the lock never counts. Past `timeout` seconds, that recorded PID gets
+ SIGTERM, then SIGKILL after `grace` seconds, each only while its parent is still the recorded machine_lock (so a
+ reused PID is never signalled). machine_lock then returns and its lock is released when it exits. Returns the
+ exit code and the PID that was stopped, or None when the command finished in time."""
+ record.unlink(missing_ok=True)
+ proc = subprocess.Popen(cmd, cwd=cwd, stdout=stdout, stderr=subprocess.STDOUT,
+ env={**os.environ, machine_lock.HOLDER_ENV: str(record)})
+ started = holder = None
+ while (code := proc.poll()) is None:
+ if started is None and (holder := _holder(record)):
+ started = time.monotonic()
+ if started is not None and time.monotonic() - started > timeout:
+ break
+ time.sleep(poll)
+ else:
+ return code, None
+ lock_pid, child = holder
+ for sig, wait in ((signal.SIGTERM, grace), (signal.SIGKILL, grace)):
+ if _parent(child) != lock_pid:
+ break
+ os.kill(child, sig)
+ deadline = time.monotonic() + wait
+ while _parent(child) == lock_pid and time.monotonic() < deadline:
+ time.sleep(min(poll, 0.5))
+ try:
+ proc.wait(grace + 60)
+ except subprocess.TimeoutExpired: # machine_lock did not return: stop it (and so its lock) by its own PID
+ proc.kill()
+ proc.wait()
+ return proc.returncode, child
+
+
+def _git(cwd: Path):
+ def run(*args: str) -> str:
+ return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=True).stdout
+ return run
+
+
+def _gh(args: list[str], stdin: str | None = None) -> str:
+ p = subprocess.run(["gh", *args], input=stdin, capture_output=True, text=True)
+ if p.returncode:
+ raise RuntimeError(f"gh {args[0]} {args[1]} failed (exit {p.returncode}): {p.stderr.strip()[-500:]}")
+ return p.stdout
+
+
+def prepare_worktree(repo: Path, wt: Path, sha: str) -> None:
+ git = _git(repo)
+ if not (wt / ".git").exists():
+ git("worktree", "prune")
+ wt.parent.mkdir(parents=True, exist_ok=True)
+ git("worktree", "add", "--detach", "--force", str(wt), sha)
+ w = _git(wt)
+ w("checkout", "--force", "--detach", sha)
+ w("clean", "-ffdx", *[x for k in KEEP for x in ("-e", k)])
+ if w("status", "--porcelain").strip():
+ raise RuntimeError("the worktree is not clean after checkout and clean")
+ lib, src = wt / "unity" / "Library", repo / "unity" / "Library"
+ if not lib.exists() and src.is_dir():
+ subprocess.run(["cp", "-c", "-R", str(src), str(lib)], check=True)
+
+
+def du_bytes(path: Path) -> int:
+ if not path.exists():
+ return 0
+ out = subprocess.run(["du", "-sk", str(path)], capture_output=True, text=True).stdout.split()
+ return int(out[0]) * 1024 if out and out[0].isdigit() else 0
+
+
+def tidy(wt: Path, runs: Path, cap_bytes: int) -> str:
+ for d in ("Builds", "Temp", "Logs"):
+ shutil.rmtree(wt / "unity" / d, ignore_errors=True)
+ old = sorted((p for p in runs.iterdir() if p.is_dir()), key=lambda p: p.stat().st_mtime)[:-KEEP_RUNS]
+ for p in old:
+ shutil.rmtree(p, ignore_errors=True)
+ lib = wt / "unity" / "Library"
+ size = du_bytes(lib)
+ if size > cap_bytes:
+ shutil.rmtree(lib, ignore_errors=True)
+ return f"library {size >> 20} MiB > cap, deleted"
+ return f"library {size >> 20} MiB"
+
+
+def run_suite(repo: Path, wt: Path, sha: str, run_dir: Path, timeout_min: float) -> tuple[Results, int, str]:
+ xml, log, build_log = run_dir / "editmode.xml", run_dir / "unity.log", run_dir / "build-sim.log"
+ try:
+ prepare_worktree(repo, wt, sha)
+ except (subprocess.CalledProcessError, RuntimeError) as e:
+ detail = getattr(e, "stderr", "") or str(e)
+ return Results(broken=f"the worktree could not be prepared: {detail.strip()[-500:]}"), -1, ""
+ with open(build_log, "w") as f:
+ b = subprocess.run(["uv", "run", "tools/build_sim_for_unity.py"], cwd=wt, stdout=f, stderr=subprocess.STDOUT)
+ if b.returncode:
+ text = build_log.read_text(errors="replace")
+ return Results(broken=f"building the sim DLLs failed (exit {b.returncode})"), b.returncode, text
+ m = re.search(r"m_EditorVersion: (\S+)", (wt / "unity/ProjectSettings/ProjectVersion.txt").read_text())
+ version = m.group(1) if m else "?"
+ if not Path(unity_path(version)).is_file():
+ return Results(broken=f"Unity {version} (unity/ProjectSettings/ProjectVersion.txt) is not installed"), -1, ""
+ try:
+ with open(run_dir / "machine-lock.log", "w") as f:
+ code, stopped = run_with_timeout(unity_command(wt, version, xml, log), run_dir / "lock-holder", cwd=wt,
+ stdout=f, timeout=timeout_min * 60, grace=UNITY_GRACE)
+ finally:
+ subprocess.run(["git", "checkout", "--", "unity/ProjectSettings", "unity/Assets/Settings"], cwd=wt,
+ capture_output=True)
+ text = log.read_text(errors="replace") if log.is_file() else ""
+ if stopped is not None:
+ return timed_out(stopped, timeout_min), code, text
+ if code == 3 and not log.is_file():
+ lock_text = (run_dir / "machine-lock.log").read_text(errors="replace")
+ return Results(broken=f"machine_lock timed out after {LOCK_TIMEOUT} s waiting for Unity"), code, lock_text
+ return parse_results(xml), code, text
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("--repo", type=Path, default=TOOLS.parent, help="the main checkout (default: this script's)")
+ ap.add_argument("--home", type=Path, default=Path.home() / ".cache" / "statecraft" / "unity-postmerge")
+ ap.add_argument("--cap-gb", type=float, default=6.0, help="delete the worktree's Library above this size")
+ ap.add_argument("--unity-timeout-min", type=float, default=UNITY_TIMEOUT_MIN,
+ help="stop Unity (by its recorded PID) after this many minutes of running")
+ ap.add_argument("--dry-run", action="store_true")
+ a = ap.parse_args(argv)
+ repo, home = a.repo.resolve(), a.home
+ runs = home / "runs"
+ runs.mkdir(parents=True, exist_ok=True)
+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ with open(home / "run.lock", "a+") as lock:
+ if os.environ.get(LOCKED_ENV) != "1": # the launcher holds run.lock for this run
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ print("unity_postmerge: another run is in progress")
+ return 0
+ state_path = home / "state.json"
+ state = load_state(state_path)
+ try:
+ tip = fetch_tip(_git(repo))
+ except (subprocess.CalledProcessError, RuntimeError) as e:
+ print(f"unity_postmerge: fetching origin/main failed: {getattr(e, 'stderr', '') or e}", file=sys.stderr)
+ return 1
+ results_log = home / "results.log"
+ logged = results_log.read_text() if results_log.is_file() else ""
+ try:
+ note = stale_note(logged, tip, commit_time(_git(repo), tip), time.time(), state)
+ except (subprocess.CalledProcessError, ValueError) as e: # fail loud: a check that cannot run says so
+ note = None if f" {tip} STALE " in logged else f"{tip} STALE check failed: {e}"
+ if note:
+ with open(results_log, "a") as f:
+ f.write(f"{stamp} {note}\n")
+ print(f"unity_postmerge: {note}", file=sys.stderr)
+ if (pending := state.get("pending")) and not a.dry_run: # a report that could not be opened last time
+ try:
+ url = report(_gh, state, pending["sha"], pending["title"], pending["body"])
+ except (RuntimeError, ValueError, OSError) as e:
+ print(f"unity_postmerge: reporting {pending['sha'][:12]} failed again: {e}", file=sys.stderr)
+ return 1
+ state["last_tested"] = state.pop("pending")["sha"]
+ save_state(state_path, state)
+ print(f"unity_postmerge: reported {state['last_tested'][:12]}: {url}")
+ sha = commit_to_test(tip, state)
+ if sha is None:
+ return 0
+ prev = state.get("last_tested")
+ run_dir = runs / f"{stamp.replace(':', '')}-{sha[:12]}"
+ run_dir.mkdir()
+ r, code, log_text = run_suite(repo, home / "worktree", sha, run_dir, a.unity_timeout_min)
+ disk = tidy(home / "worktree", runs, int(a.cap_gb * 2**30))
+ ok = passed(r, code)
+ line = (f"{stamp} {sha} {'PASS' if ok else 'FAIL'} exit={code} total={r.total} passed={r.passed} "
+ f"failed={r.failed}{' broken' if r.broken else ''} {disk} run={run_dir.name}")
+ with open(results_log, "a") as f:
+ f.write(line + "\n")
+ print(line)
+ if a.dry_run:
+ if not ok:
+ print(issue_title(sha) + "\n\n" + issue_body(sha, prev, r, code, log_text, ""))
+ return 0
+ if ok:
+ state["last_tested"] = sha
+ save_state(state_path, state)
+ return 0
+ commits = ""
+ if prev:
+ try:
+ commits = _git(repo)("log", "--oneline", "--no-decorate", f"{prev}..{sha}")
+ except subprocess.CalledProcessError:
+ commits = ""
+ title, body = issue_title(sha), issue_body(sha, prev, r, code, log_text, commits)
+ try:
+ url = report(_gh, state, sha, title, body)
+ except (RuntimeError, ValueError, OSError) as e:
+ state["pending"] = {"sha": sha, "title": title, "body": body}
+ save_state(state_path, state)
+ print(f"unity_postmerge: opening the issue failed, kept for the next run: {e}", file=sys.stderr)
+ return 1
+ state["last_tested"] = sha
+ save_state(state_path, state)
+ print(f"unity_postmerge: {url}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/unity_postmerge_launch.py b/tools/unity_postmerge_launch.py
new file mode 100644
index 000000000..61fd8888f
--- /dev/null
+++ b/tools/unity_postmerge_launch.py
@@ -0,0 +1,54 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""launchd's entry point for the post-merge Unity run (T72). Installed as a copy in the job folder, so it depends on no
+checkout's working tree. It takes the job's run lock, fetches origin/main in the main checkout, moves the job's
+worktree to that tip (creating it on the first run) and runs tools/unity_postmerge.py from the worktree, so a merged
+change to the script takes effect on the next run. The script, told by UNITY_POSTMERGE_LOCKED that the lock is held,
+does the rest. When a run is in progress the launcher exits 0 and touches nothing.
+
+Usage: uv run unity_postmerge_launch.py --uv PATH --repo MAIN_CHECKOUT --home JOB_FOLDER"""
+import argparse
+import fcntl
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+
+def git(cwd: Path, *args: str) -> str:
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--uv", required=True)
+ ap.add_argument("--repo", type=Path, required=True)
+ ap.add_argument("--home", type=Path, required=True)
+ a = ap.parse_args(argv)
+ a.home.mkdir(parents=True, exist_ok=True)
+ wt = a.home / "worktree"
+ with open(a.home / "run.lock", "a+") as lock:
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ print("unity_postmerge_launch: a run is in progress")
+ return 0
+ try:
+ git(a.repo, "fetch", "--quiet", "origin", "+refs/heads/main:refs/remotes/origin/main")
+ tip = git(a.repo, "rev-parse", "--verify", "refs/remotes/origin/main^{commit}")
+ if not (wt / ".git").exists():
+ git(a.repo, "worktree", "prune")
+ git(a.repo, "worktree", "add", "--detach", "--force", str(wt), tip)
+ else:
+ git(wt, "checkout", "--quiet", "--force", "--detach", tip)
+ except subprocess.CalledProcessError as e:
+ print(f"unity_postmerge_launch: git {e.cmd[1]} failed: {e.stderr.strip()[-500:]}", file=sys.stderr)
+ return 1
+ return subprocess.call([a.uv, "run", str(wt / "tools" / "unity_postmerge.py"), "--repo", str(a.repo),
+ "--home", str(a.home)], env={**os.environ, "UNITY_POSTMERGE_LOCKED": "1"})
+
+
+if __name__ == "__main__":
+ sys.exit(main())