A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
test(editor): UnityMcpGuardTests fail if the plugin is missing; warm-up launch before batch tests (#1559)
Eyal Golan51d51d822554
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 071758a4d..60db6c11a 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -51,7 +51,8 @@ Follow [docs/dev-setup.md](docs/dev-setup.md). In short:`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`;- the repository policy checks:`uv run --with pytest==9.1.1 --with pyyaml==6.0.3 --with requests==2.32.5 pytest scripts/oss/tests -q` and `uv run scripts/oss/check_repo.py` (the command CI runs);- - Unity EditMode tests, if you touched `unity/` (`-buildTarget OSXUniversal` keeps an earlier WebGL build from leaving the editor on the wrong platform):+ - Unity EditMode tests, if you touched `unity/` (`-buildTarget OSXUniversal` keeps an earlier WebGL build from leaving the editor on the wrong platform). First the Unity-MCP warm-up, every time (it exits by itself, so no `-quit`; it fetches the plugin's DLLs and adds its defines, which the tests need loaded and the post-build cleanup removes):+ `"$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath unity -buildTarget OSXUniversal -executeMethod Statecraft.Game.EditorTools.UnityMcpGuard.WarmUp -logFile unity-warmup.log`, then`"$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath unity -buildTarget OSXUniversal -runTests -testPlatform EditMode -testResults "$PWD/unity-editmode.xml" -logFile unity-tests.log`. There must be 0 `warning CS` in the log.4. **Text the player sees** has no internal ids, gives dates as "15 May 1948", and shows money as "IL 1.2m" or "$1.2m". The tests enforce this.5. **Keep the pull request focused:** one change per PR, and no unrelated refactors.@@ -88,7 +89,7 @@ AI-assisted work is welcome. Say so in the pull request: which parts, and how yo- **Security:** the local server lets the agent run editor actions, including editing files and executing code in the editor. It listens on loopback only and rejects browser pages from other sites, and the token keeps other local programs out. Keep it local: never expose the server's port (no port forwarding, tunnels or `0.0.0.0` binds), and stop the server when you're done.- **Not connecting?** Connect only works in an interactive editor: in batch mode (tests and builds) the plugin is held offline on purpose, and its windows don't open. Check that the server shows Running on the port in the Server URL, then click Connect. The first attempt can fail while the server is still starting; the plugin retries. If the editor is stopped without quitting, `gamedev-mcp-server` can stay behind on the port: stop it with the window's Stop button or by its PID.- **Batch mode and builds:** `UnityMcpGuard` (`unity/Assets/Editor/UnityMcpGuard.cs`) keeps the plugin from connecting, starting its server or opening a window in batch mode (tests and builds), and drops its assemblies from every player build. The browser build's golden hashes don't change. Run batch Unity with `-CI false -GITHUB_ACTIONS false -TF_BUILD false` (as every command in these docs does): the plugin treats `CI`, `GITHUB_ACTIONS` or `TF_BUILD` set to `true` in the environment as CI (every CI runner sets at least one of them, and so do some agent shells), and then it skips its NuGet download but still adds its defines, and a fresh clone fails to compile. The update popup is off for the team (`unity/ProjectSettings/AI-Game-Developer-UpdateSettings.asset`); version bumps come by pull request. On every Unity-MCP version bump, run the Unity EditMode tests in batch mode and paste the `UnityMcpGuardTests` result in the pull request.-- **Leave one change uncommitted:** the plugin adds `UNITY_MCP_READY;UNITY_MCP_DEPS_7` to the scripting defines in `unity/ProjectSettings/ProjectSettings.asset` once its DLLs are in place. Don't commit that change: on a fresh clone the defines would arrive before the DLLs, and the plugin wouldn't compile. A policy test refuses it. The post-build cleanup (`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`) drops the defines too; the plugin adds them back on the next open, at the cost of one extra compile.+- **Leave one change uncommitted:** the plugin adds `UNITY_MCP_READY;UNITY_MCP_DEPS_7` to the scripting defines in `unity/ProjectSettings/ProjectSettings.asset` once its DLLs are in place. Don't commit that change: on a fresh clone the defines would arrive before the DLLs, and the plugin wouldn't compile. A policy test refuses it. The post-build cleanup (`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`) drops the defines too; the plugin adds them back on the next open, at the cost of one extra compile. A batch test run that starts without them runs its tests before the plugin loads, and the `UnityMcpGuardTests` fail ("its editor assembly must be loaded"): run the warm-up above first.- **Per-user state the plugin keeps:** besides the settings file, it stores `Unity-MCP.MainWindow.Initialized` and `Unity_MCP_SelectedAiAgent` in this project's editor PlayerPrefs, and the server's PID and update-check state in EditorPrefs.## Pull requestsdiff --git a/changelog.d/unity-mcp-warm-up.md b/changelog.d/unity-mcp-warm-up.mdnew file mode 100644index 000000000..078c80444--- /dev/null+++ b/changelog.d/unity-mcp-warm-up.md@@ -0,0 +1,3 @@+- Unity EditMode runs start with a warm-up launch (`UnityMcpGuard.WarmUp`, in CONTRIBUTING.md and the post-merge job),+ so the Unity-MCP plugin is loaded when the tests start, and the `UnityMcpGuardTests` that need it now fail instead of+ passing when it is missing.diff --git a/tools/tests/test_unity_postmerge.py b/tools/tests/test_unity_postmerge.pyindex 65d1a64f9..96dbd5b4c 100644--- a/tools/tests/test_unity_postmerge.py+++ b/tools/tests/test_unity_postmerge.py@@ -257,6 +257,49 @@ def test_unity_runs_under_the_shared_lock_with_graphics_and_ci_flags_off(tmp_patassert unity[unity.index("-testResults") + 1] == str(tmp_path / "r.xml")+def test_the_warm_up_launch_runs_the_guard_method_under_the_same_lock_without_quit(tmp_path):+ cmd = up.warmup_command(Path("/wt"), "6000.3.25f1", tmp_path / "w.log")+ test = up.unity_command(Path("/wt"), "6000.3.25f1", tmp_path / "r.xml", tmp_path / "u.log")+ # Same lock, Unity, flags and project as the test launch; only the method and log differ.+ assert cmd[:cmd.index("-executeMethod")] == test[:test.index("-runTests")]+ assert cmd[cmd.index("-executeMethod") + 1] == "Statecraft.Game.EditorTools.UnityMcpGuard.WarmUp"+ # -quit would exit before the plugin's resolver runs on the first editor update.+ assert "-quit" not in cmd and "-runTests" not in cmd+ assert cmd[cmd.index("-logFile") + 1] == str(tmp_path / "w.log")+++def _suite(tmp_path, monkeypatch, warm_code):+ """run_suite with git, the sim build and Unity faked; returns its result and the Unity launches in order."""+ wt, run_dir = tmp_path / "wt", tmp_path / "run"+ (wt / "unity/ProjectSettings").mkdir(parents=True)+ (wt / "unity/ProjectSettings/ProjectVersion.txt").write_text("m_EditorVersion: 6000.3.25f1\n")+ run_dir.mkdir()+ launches = []++ def fake_run(cmd, record, **kw):+ launches.append("warm-up" if "-executeMethod" in cmd else "tests")+ if "-runTests" in cmd:+ results_xml(tmp_path, [("T.A", "Passed", "")]).replace(run_dir / "editmode.xml")+ return 0, None+ return warm_code, None++ monkeypatch.setattr(up, "prepare_worktree", lambda *a: None)+ monkeypatch.setattr(up.subprocess, "run", lambda *a, **k: subprocess.CompletedProcess(a, 0))+ monkeypatch.setattr(up, "unity_path", lambda version: sys.executable) # an existing file stands in for Unity+ monkeypatch.setattr(up, "run_with_timeout", fake_run)+ return up.run_suite(tmp_path, wt, SHA, run_dir, 90), launches+++def test_the_warm_up_runs_before_the_tests(tmp_path, monkeypatch):+ (r, code, _), launches = _suite(tmp_path, monkeypatch, 0)+ assert launches == ["warm-up", "tests"] and code == 0 and r.broken is None and r.total == 1+++def test_a_failed_warm_up_is_a_broken_run_and_the_tests_never_start(tmp_path, monkeypatch):+ (r, code, _), launches = _suite(tmp_path, monkeypatch, 1)+ assert launches == ["warm-up"] and code == 1 and "warm-up" in r.broken and not up.passed(r, code)++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")diff --git a/tools/unity_postmerge.py b/tools/unity_postmerge.pyindex a8556a983..cc516a150 100644--- a/tools/unity_postmerge.py+++ b/tools/unity_postmerge.py@@ -13,7 +13,8 @@ CI cannot run Unity (CONTRIBUTING.md, "What CI runs"), so two PRs can each be grexcept 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 fromit, 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+3. builds the sim DLLs (tools/build_sim_for_unity.py), then the Unity-MCP warm-up launch (UnityMcpGuard.WarmUp; a+ failed warm-up is a broken run and the tests do not start), then runs the full EditMode suite through`machine_lock.py --shared --wait-unity --timeout 14400`, never with -nographics, and afterwards revertsunity/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@@ -74,6 +75,9 @@ MAX_FAILURES = 50MAX_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")+# The launch before the tests that leaves the Unity-MCP plugin's gate defines in ProjectSettings, so the test launch+# compiles and loads the plugin (CONTRIBUTING.md); the defines are reverted after every run, so it runs every time.+WARM_UP = "Statecraft.Game.EditorTools.UnityMcpGuard.WarmUp"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.@@ -289,11 +293,19 @@ 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]:+def _unity(wt: Path, version: str) -> 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)]+ "-projectPath", str(wt / "unity"), "-buildTarget", "OSXUniversal"]+++def warmup_command(wt: Path, version: str, log: Path) -> list[str]:+ # No -quit: the warm-up exits by itself once the plugin's resolver has run (UnityMcpGuard.WarmUp).+ return _unity(wt, version) + ["-executeMethod", WARM_UP, "-logFile", str(log)]+++def unity_command(wt: Path, version: str, xml: Path, log: Path) -> list[str]:+ return _unity(wt, version) + ["-runTests", "-testPlatform", "EditMode", "-testResults", str(xml), "-logFile", str(log)]def fill_plist(text: str, *, uv: str, repo: str, home: str, path: str) -> str:@@ -402,6 +414,7 @@ def tidy(wt: Path, runs: Path, cap_bytes: int) -> str: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"+ warm_log = run_dir / "warmup.log"try:prepare_worktree(repo, wt, sha)except (subprocess.CalledProcessError, RuntimeError) as e:@@ -418,8 +431,12 @@ def run_suite(repo: Path, wt: Path, sha: str, run_dir: Path, timeout_min: float)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,+ warm, stopped = run_with_timeout(warmup_command(wt, version, warm_log), run_dir / "lock-holder", cwd=wt,stdout=f, timeout=timeout_min * 60, grace=UNITY_GRACE)+ code = warm+ if warm == 0 and stopped is None:+ 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)@@ -429,6 +446,9 @@ def run_suite(repo: Path, wt: Path, sha: str, run_dir: Path, timeout_min: float)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+ if warm != 0:+ warm_text = warm_log.read_text(errors="replace") if warm_log.is_file() else ""+ return Results(broken=f"the Unity-MCP warm-up launch failed (exit {warm})"), warm, warm_textreturn parse_results(xml), code, textdiff --git a/unity/Assets/Editor/UnityMcpGuard.cs b/unity/Assets/Editor/UnityMcpGuard.csindex 1d6d567c1..36ab30651 100644--- a/unity/Assets/Editor/UnityMcpGuard.cs+++ b/unity/Assets/Editor/UnityMcpGuard.cs@@ -50,6 +50,25 @@ namespace Statecraft.Game.EditorToolspublic static Type? LoadedPluginEditorType() =>AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == PluginEditorAssembly)?.GetType(PluginEditorType);+ /// <summary>The warm-up launch before batch tests (CONTRIBUTING.md). The plugin compiles only when its gate defines+ /// (UNITY_MCP_READY) are in ProjectSettings when Unity starts. Its resolver fetches the DLLs and adds the defines on+ /// the first editor update, after -executeMethod, so a -quit launch would exit before it ran, and a test run that+ /// adds them starts its tests without a reload. This waits one editor update (the resolver's runs first: it+ /// subscribed at load), saves the defines and exits, 1 when they are still missing. No -quit:+ /// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath unity -executeMethod Statecraft.Game.EditorTools.UnityMcpGuard.WarmUp</summary>+ public static void WarmUp()+ {+ EditorApplication.update += Exit;+ static void Exit()+ {+ EditorApplication.update -= Exit;+ AssetDatabase.SaveAssets();+ var ready = PlayerSettings.GetScriptingDefineSymbols(NamedBuildTarget.Standalone).Split(';').Contains("UNITY_MCP_READY");+ Debug.Log("UnityMcpGuard warm-up: gate defines " + (ready ? "in place" : "missing"));+ EditorApplication.Exit(ready ? 0 : 1);+ }+ }+/// <summary>Where the guard reads command-line arguments from: "plugin ArgsUtils" (the plugin's own parser and key/// comparer, so an argument counts for the guard exactly when it counts for the plugin) or "fallback parser".</summary>public static string ArgSource = "not read";diff --git a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.csindex 75af8b26e..f67aebea5 100644--- a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs+++ b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs@@ -27,8 +27,13 @@ namespace Statecraft.Tests.EditModestatic string[] Filter(params string[] assemblies) =>(string[])Guard().GetMethod("Filter", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object[] { assemblies })!;- static Type? PluginEditor() =>- (Type?)Guard().GetMethod("LoadedPluginEditorType", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, null);+ static Type PluginEditor()+ {+ var editor = (Type?)Guard().GetMethod("LoadedPluginEditorType", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, null);+ Assert.IsNotNull(editor,+ "com.ivanmurzak.unity.mcp is a direct dependency in Packages/manifest.json; its editor assembly must be loaded for UnityMcpGuard integration tests");+ return editor!;+ }static string Status() => (string)Guard().GetField("Status", Any)!.GetValue(null)!;@@ -72,7 +77,7 @@ namespace Statecraft.Tests.EditMode[Test]public void TheGuardReadsArgumentsThroughThePluginsOwnParser(){- if (PluginEditor() == null) { Assert.AreEqual("plugin not loaded", Status()); return; }+ PluginEditor();// Same dictionary as the plugin (its key comparer included), so -unity_mcp_auth_option or -AUTH match exactly// when, and only when, they match for the plugin.Assert.AreEqual("plugin ArgsUtils", Guard().GetField("ArgSource", Any)!.GetValue(null));@@ -103,7 +108,7 @@ namespace Statecraft.Tests.EditMode[Test]public void PlayerBuildsDropEveryRealPluginAssemblyAndDll(){- if (PluginEditor() == null) { Assert.AreEqual("plugin not loaded", Status()); return; }+ PluginEditor();// Every player assembly compiled from the plugin's packages, and every managed plugin DLL a WebGL build would// take that is not ours, must be dropped by the filter (by its real output name and asset path).var fromPackages = CompilationPipeline.GetAssemblies(AssembliesType.PlayerWithoutTestAssemblies)@@ -133,13 +138,6 @@ namespace Statecraft.Tests.EditModepublic void ThePluginIsHeldToLocalCustomModeWithTokenAuth(){var editor = PluginEditor();-#if UNITY_MCP_READY- // The gate defines are in place, so the plugin compiled and must be loaded; a renamed type or assembly would- // otherwise turn every check below into a silent pass.- Assert.IsNotNull(editor, "UNITY_MCP_READY is defined but the plugin editor type is not loaded");-#endif- // On a fresh clone's first run the plugin compiles after its resolver, so the tests run before a reload loads it.- if (editor == null) { Assert.AreEqual("plugin not loaded", Status()); return; }Assert.AreEqual(Application.isBatchMode ? "held offline" : "held local", Status());var instance = editor.GetProperty("Instance", Any)!.GetValue(null);var config = editor.GetField("unityConnectionConfig", Any)!.GetValue(instance)!;@@ -164,7 +162,7 @@ namespace Statecraft.Tests.EditModepublic void InBatchModeThePluginOpensNoWindowStartsNoServerAndSkipsItsUpdateCheck(){var editor = PluginEditor();- if (!Application.isBatchMode || editor == null) { CollectionAssert.Contains(new[] { "held local", "plugin not loaded" }, Status()); return; }+ if (!Application.isBatchMode) { Assert.AreEqual("held local", Status()); return; }// The first-run window opened on screen in a batch test run (2026-10-10) and its server panel started the// local server; the update popup is the same kind of window.var windows = Resources.FindObjectsOfTypeAll<EditorWindow>().Where(w => w.GetType().Assembly == editor.Assembly);@@ -180,7 +178,7 @@ namespace Statecraft.Tests.EditModepublic void ABatchHoldStillAppliesWhenTheCustomOrTokenOverrideFails(){var editor = PluginEditor();- if (!Application.isBatchMode || editor == null) { CollectionAssert.Contains(new[] { "held local", "plugin not loaded" }, Status()); return; }+ if (!Application.isBatchMode) { Assert.AreEqual("held local", Status()); return; }var instance = editor.GetProperty("Instance", Any)!.GetValue(null);var config = editor.GetField("unityConnectionConfig", Any)!.GetValue(instance)!;var keep = config.GetType().GetProperty("KeepConnected")!;@@ -208,7 +206,7 @@ namespace Statecraft.Tests.EditModepublic void EveryBatchProtectionStillAppliesWhenAnEarlierStepThrows(){var editor = PluginEditor();- if (!Application.isBatchMode || editor == null) { CollectionAssert.Contains(new[] { "held local", "plugin not loaded" }, Status()); return; }+ if (!Application.isBatchMode) { Assert.AreEqual("held local", Status()); return; }var instance = editor.GetProperty("Instance", Any)!.GetValue(null);var config = editor.GetField("unityConnectionConfig", Any)!.GetValue(instance)!;var keep = config.GetType().GetProperty("KeepConnected")!;@@ -245,7 +243,6 @@ namespace Statecraft.Tests.EditModepublic void SavingTheConfigNeverWritesTheOverrides(){var editor = PluginEditor();- if (editor == null) { Assert.AreEqual("plugin not loaded", Status()); return; }var instance = editor.GetProperty("Instance", Any)!.GetValue(null)!;var config = editor.GetField("unityConnectionConfig", Any)!.GetValue(instance)!;var record = editor.GetProperty("RuntimeOverrides", Any)!.GetValue(instance)!;@@ -281,7 +278,6 @@ namespace Statecraft.Tests.EditModepublic void TheTeamKillSwitchForTheUpdatePopupIsOn(){var editor = PluginEditor();- if (editor == null) { Assert.AreEqual("plugin not loaded", Status()); return; }var checker = editor.Assembly.GetType("com.IvanMurzak.Unity.MCP.Editor.Utils.UpdateChecker")!;Assert.IsTrue((bool)checker.GetProperty("IsDisabledForProject")!.GetValue(null)!,"ProjectSettings/AI-Game-Developer-UpdateSettings.asset turns the update popup off for the team");