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.

fix(editor): every UnityMcpGuard step runs on its own; the Save test restores the user's file

eyalgolan8665b33c65d7
diff --git a/unity/Assets/Editor/UnityMcpGuard.cs b/unity/Assets/Editor/UnityMcpGuard.cs
index 8e611891b..1d6d567c1 100644
--- a/unity/Assets/Editor/UnityMcpGuard.cs
+++ b/unity/Assets/Editor/UnityMcpGuard.cs
@@ -102,66 +102,87 @@ namespace Statecraft.Game.EditorTools
return d;
}
- public static string Hold(bool batch, string? simulateOverrideFailure = null)
+ /// <summary>Applies the hold and returns the status. Every step runs on its own (a throw or a "plugin internals
+ /// changed" result in one step never skips a later one) and the failures are joined. In batch mode the protections
+ /// (no connection, no server, no window, no update check) come before the Custom/token override. The two simulate
+ /// parameters exist for the tests only.</summary>
+ public static string Hold(bool batch, string? simulateOverrideFailure = null, string? simulateThrowInStep = null)
{
var editor = LoadedPluginEditorType();
if (editor == null) return "plugin not loaded";
- try
+ var failures = new List<string>();
+
+ void Step(string name, Func<string?> body)
{
- var instance = editor.GetProperty("Instance", Any)?.GetValue(null);
- var config = editor.GetField("unityConnectionConfig", Any)?.GetValue(instance);
- var record = editor.GetProperty("RuntimeOverrides", Any)?.GetValue(instance);
- var track = record?.GetType().GetMethod("Track", Any);
- var baselines = record?.GetType().GetProperty("BaselineValues")?.GetValue(record) as System.Collections.IDictionary;
- if (config == null || record == null || track == null) return "plugin internals changed";
-
- string? Override(string name, Func<Type, object> value)
+ try
{
- var p = config.GetType().GetProperty(name);
- if (p == null) return "plugin internals changed: no " + name;
- var target = value(p.PropertyType);
- // Keep the on-disk value as the baseline the plugin saves, even if an env var already overrode it.
- var baseline = baselines != null && baselines.Contains(name) ? baselines[name] : p.GetValue(config);
- track.Invoke(record, new[] { name, baseline, target });
- p.SetValue(config, target);
- return null;
+ if (name == simulateThrowInStep) throw new InvalidOperationException("simulated throw in " + name);
+ var f = body();
+ if (f != null) failures.Add(f);
+ }
+ catch (Exception e)
+ {
+ var inner = e is TargetInvocationException t && t.InnerException != null ? t.InnerException : e;
+ failures.Add($"{name}: {inner.GetType().Name}: {inner.Message}");
}
+ }
+
+ object? instance = null, config = null, record = null;
+ MethodInfo? track = null;
+ System.Collections.IDictionary? baselines = null;
+ Step("plugin config", () =>
+ {
+ instance = editor.GetProperty("Instance", Any)?.GetValue(null);
+ config = editor.GetField("unityConnectionConfig", Any)?.GetValue(instance);
+ record = editor.GetProperty("RuntimeOverrides", Any)?.GetValue(instance);
+ track = record?.GetType().GetMethod("Track", Any);
+ baselines = record?.GetType().GetProperty("BaselineValues")?.GetValue(record) as System.Collections.IDictionary;
+ return config == null || record == null || track == null ? "plugin internals changed: config or RuntimeOverrides" : null;
+ });
+
+ string? Override(string name, Func<Type, object> value)
+ {
+ if (config == null || record == null || track == null) return "plugin internals changed: cannot override " + name;
+ var p = config.GetType().GetProperty(name);
+ if (p == null) return "plugin internals changed: no " + name;
+ var target = value(p.PropertyType);
+ // Keep the on-disk value as the baseline the plugin saves, even if an env var already overrode it.
+ var baseline = baselines != null && baselines.Contains(name) ? baselines[name] : p.GetValue(config);
+ track.Invoke(record, new[] { name, baseline, target });
+ p.SetValue(config, target);
+ return null;
+ }
- var failures = new List<string>();
- if (batch)
+ if (batch)
+ {
+ Step("KeepConnected", () => Override("KeepConnected", _ => false));
+ Step("KeepServerRunning", () => Override("KeepServerRunning", _ => false));
+ // Run each static constructor first (it queues the callback), or the unhook could come before the queueing.
+ Step("MainWindowInitializer", () => Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.UI.MainWindowInitializer",
+ "PerformInitialization", runCctorOf: null, update: true));
+ Step("UpdateChecker", () => Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.Utils.UpdateChecker",
+ "CheckForUpdatesOnStartup", runCctorOf: "com.IvanMurzak.Unity.MCP.Editor.Startup", update: false));
+ Step("plugin windows", () =>
{
- // Batch protections first and on their own: a failed Custom/token override must not skip them.
- var f = Override("KeepConnected", _ => false) ?? Override("KeepServerRunning", _ => false);
- if (f != null) failures.Add(f);
- // Run each static constructor first (it queues the callback), or the unhook could come before the queueing.
- f = Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.UI.MainWindowInitializer", "PerformInitialization", runCctorOf: null, update: true);
- if (f != null) failures.Add(f);
- f = Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.Utils.UpdateChecker", "CheckForUpdatesOnStartup",
- runCctorOf: "com.IvanMurzak.Unity.MCP.Editor.Startup", update: false);
- if (f != null) failures.Add(f);
foreach (var w in Resources.FindObjectsOfTypeAll<EditorWindow>().Where(w => w.GetType().Assembly == editor.Assembly).ToList())
w.Close();
- }
- if (simulateOverrideFailure != null) failures.Add(simulateOverrideFailure);
- else
- {
- foreach (var (name, knob, alias, value) in new[] { ("ConnectionMode", "UNITY_MCP_CONNECTION_MODE", (string?)null, "Custom"),
- ("AuthOption", "UNITY_MCP_AUTH_OPTION", "auth", "token") })
- {
- var type = config.GetType().GetProperty(name)?.PropertyType;
- if (type == null) { failures.Add("plugin internals changed: no " + name); continue; }
- if (ExplicitKnob(knob, alias, type) != null) continue; // the plugin's own opt-out, respected
- var f = Override(name, t => Enum.Parse(t, value));
- if (f != null) failures.Add(f);
- }
- }
- if (failures.Count > 0) return string.Join("; ", failures);
- return batch ? "held offline" : "held local";
+ return null;
+ });
}
- catch (Exception e)
+ if (simulateOverrideFailure != null) failures.Add(simulateOverrideFailure);
+ else
{
- return e.GetType().Name + ": " + e.Message;
+ foreach (var (name, knob, alias, value) in new[] { ("ConnectionMode", "UNITY_MCP_CONNECTION_MODE", (string?)null, "Custom"),
+ ("AuthOption", "UNITY_MCP_AUTH_OPTION", "auth", "token") })
+ Step(name, () =>
+ {
+ var type = config?.GetType().GetProperty(name)?.PropertyType;
+ if (type == null) return "plugin internals changed: no " + name;
+ return ExplicitKnob(knob, alias, type) != null ? null : Override(name, t => Enum.Parse(t, value)); // the plugin's own opt-out is respected
+ });
}
+ if (failures.Count > 0) return string.Join("; ", failures);
+ return batch ? "held offline" : "held local";
}
/// <summary>Takes a plugin callback off EditorApplication.update (or delayCall), after running the static
diff --git a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs
index c3c3e8b34..75af8b26e 100644
--- a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs
+++ b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs
@@ -191,7 +191,7 @@ namespace Statecraft.Tests.EditMode
{
// A plugin bump that renames ConnectionMode/AuthOption must not take the batch protections down with it.
var status = (string)Guard().GetMethod("Hold", BindingFlags.Public | BindingFlags.Static)!
- .Invoke(null, new object?[] { true, "simulated override failure" })!;
+ .Invoke(null, new object?[] { true, "simulated override failure", null })!;
StringAssert.Contains("simulated override failure", status);
Assert.IsFalse((bool)keep.GetValue(config)!, "no connection even when the Custom/token override failed");
Assert.IsFalse((bool)server.GetValue(config)!, "no local server even when the Custom/token override failed");
@@ -200,7 +200,44 @@ namespace Statecraft.Tests.EditMode
{
keep.SetValue(config, false);
server.SetValue(config, false);
- Guard().GetMethod("Hold", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object?[] { true, null });
+ Guard().GetMethod("Hold", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object?[] { true, null, null });
+ }
+ }
+
+ [Test]
+ public void EveryBatchProtectionStillAppliesWhenAnEarlierStepThrows()
+ {
+ var editor = PluginEditor();
+ if (!Application.isBatchMode || editor == null) { CollectionAssert.Contains(new[] { "held local", "plugin not loaded" }, Status()); return; }
+ var instance = editor.GetProperty("Instance", Any)!.GetValue(null);
+ var config = editor.GetField("unityConnectionConfig", Any)!.GetValue(instance)!;
+ var keep = config.GetType().GetProperty("KeepConnected")!;
+ var server = config.GetType().GetProperty("KeepServerRunning")!;
+ var unhooked = (List<string>)Guard().GetField("Unhooked", Any)!.GetValue(null)!;
+ var hold = Guard().GetMethod("Hold", BindingFlags.Public | BindingFlags.Static)!;
+ try
+ {
+ foreach (var step in new[] { "KeepConnected", "MainWindowInitializer" })
+ {
+ keep.SetValue(config, true);
+ server.SetValue(config, true);
+ unhooked.Clear();
+ var status = (string)hold.Invoke(null, new object?[] { true, null, step })!;
+ StringAssert.Contains("simulated throw in " + step, status, step);
+ if (step != "KeepConnected") Assert.IsFalse((bool)keep.GetValue(config)!, step + ": KeepConnected still forced off");
+ Assert.IsFalse((bool)server.GetValue(config)!, step + ": KeepServerRunning still forced off");
+ CollectionAssert.Contains(unhooked, "UpdateChecker.CheckForUpdatesOnStartup", step + ": the update check is still unhooked");
+ if (step != "MainWindowInitializer")
+ CollectionAssert.Contains(unhooked, "MainWindowInitializer.PerformInitialization", step + ": the first-run window is still unhooked");
+ var mode = config.GetType().GetProperty("ConnectionMode")!;
+ Assert.AreEqual(Knob("UNITY_MCP_CONNECTION_MODE", null, mode.PropertyType) ?? "Custom", mode.GetValue(config)!.ToString(), step + ": still held to Custom");
+ }
+ }
+ finally
+ {
+ keep.SetValue(config, false);
+ server.SetValue(config, false);
+ hold.Invoke(null, new object?[] { true, null, null });
}
}
@@ -214,15 +251,28 @@ namespace Statecraft.Tests.EditMode
var record = editor.GetProperty("RuntimeOverrides", Any)!.GetValue(instance)!;
var baselines = (System.Collections.IDictionary)record.GetType().GetProperty("BaselineValues")!.GetValue(record)!;
var path = (string)editor.GetProperty("AssetsFileAbsolutePath", Any)!.GetValue(null)!;
- // The plugin's own Save: it writes the baselines and keeps the overrides in memory.
- instance.GetType().GetMethod("Save", Any)!.Invoke(instance, new object[] { false });
- var json = System.IO.File.ReadAllText(path);
- string OnDisk(string key) => System.Text.RegularExpressions.Regex.Match(json, "\"" + key + "\":\\s*\"(\\w+)\"").Groups[1].Value;
- foreach (var (field, key) in new[] { ("ConnectionMode", "connectionMode"), ("AuthOption", "authOption") })
+ // The test writes through the plugin's real Save, so it snapshots the user's file (or its absence) and puts it
+ // back byte for byte afterwards, also when an assertion fails.
+ var before = System.IO.File.Exists(path) ? System.IO.File.ReadAllBytes(path) : null;
+ try
+ {
+ // The plugin's own Save: it writes the baselines and keeps the overrides in memory.
+ instance.GetType().GetMethod("Save", Any)!.Invoke(instance, new object[] { false });
+ var json = System.IO.File.ReadAllText(path);
+ string OnDisk(string key) => System.Text.RegularExpressions.Regex.Match(json, "\"" + key + "\":\\s*\"(\\w+)\"").Groups[1].Value;
+ foreach (var (field, key) in new[] { ("ConnectionMode", "connectionMode"), ("AuthOption", "authOption") })
+ {
+ if (!baselines.Contains(field)) continue; // the plugin's own knob is in charge of this field
+ Assert.AreEqual(baselines[field]!.ToString(), OnDisk(key), field + " on disk is the user's own value");
+ }
+ }
+ finally
{
- if (!baselines.Contains(field)) continue; // the plugin's own knob is in charge of this field
- Assert.AreEqual(baselines[field]!.ToString(), OnDisk(key), field + " on disk is the user's own value");
+ if (before == null) System.IO.File.Delete(path);
+ else System.IO.File.WriteAllBytes(path, before);
}
+ if (before == null) Assert.IsFalse(System.IO.File.Exists(path), "no settings file is left behind");
+ else CollectionAssert.AreEqual(before, System.IO.File.ReadAllBytes(path), "the user's settings file is restored byte-identical");
var modeKnob = Knob("UNITY_MCP_CONNECTION_MODE", null, config.GetType().GetProperty("ConnectionMode")!.PropertyType);
Assert.AreEqual(modeKnob ?? "Custom", config.GetType().GetProperty("ConnectionMode")!.GetValue(config)!.ToString(), "still held in memory after Save");
}