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): batch protections independent of the Custom/token override; plugin opt-out semantics
eyalgolanf4425d46de5a
diff --git a/unity/Assets/Editor/UnityMcpGuard.cs b/unity/Assets/Editor/UnityMcpGuard.csindex a5af60e8e..8e611891b 100644--- a/unity/Assets/Editor/UnityMcpGuard.cs+++ b/unity/Assets/Editor/UnityMcpGuard.cs@@ -50,12 +50,59 @@ namespace Statecraft.Game.EditorToolspublic static Type? LoadedPluginEditorType() =>AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == PluginEditorAssembly)?.GetType(PluginEditorType);- /// <summary>True when the plugin's own knob for this field is set, as an env var or a -NAME command-line argument.</summary>- static bool ExplicitKnob(string name) =>- !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(name))- || Environment.GetCommandLineArgs().Any(a => a.TrimStart('-').Split('=')[0] == name);+ /// <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";- static string Hold(bool batch)+ /// <summary>The plugin's own value for an opt-out knob, or null when there is none: the first non-blank of the flag+ /// alias argument (-auth), the -KEY argument and the KEY env var, trimmed with quotes stripped, and only if it parses+ /// as an enum name (case-insensitive). This mirrors EnvironmentUtils.ApplyEnvironmentOverrides: an invalid first+ /// value overrides nothing there, so it is no opt-out here either.</summary>+ public static string? KnobValue(string envKey, string? flagAlias, Type enumType, Func<string, string?> arg, Func<string, string?> env)+ {+ string? raw = null;+ if (flagAlias != null && !string.IsNullOrWhiteSpace(arg(flagAlias))) raw = arg(flagAlias);+ else if (!string.IsNullOrWhiteSpace(arg(envKey))) raw = arg(envKey);+ else if (!string.IsNullOrWhiteSpace(env(envKey))) raw = env(envKey);+ if (raw == null) return null;+ var value = raw.Trim().Trim('"');+ var name = Enum.GetNames(enumType).FirstOrDefault(n => string.Equals(n, value, StringComparison.OrdinalIgnoreCase));+ return name;+ }++ /// <summary>KnobValue for this process: arguments through the plugin's ArgsUtils.ParseCommandLineArguments.</summary>+ public static string? ExplicitKnob(string envKey, string? flagAlias, Type enumType)+ {+ var args = PluginArgs();+ return KnobValue(envKey, flagAlias, enumType, k => args.Contains(k) ? args[k] as string : null, Environment.GetEnvironmentVariable);+ }++ static System.Collections.IDictionary PluginArgs()+ {+ var utils = AppDomain.CurrentDomain.GetAssemblies()+ .Select(a => a.GetType("com.IvanMurzak.McpPlugin.Common.Utils.ArgsUtils")).FirstOrDefault(t => t != null);+ if (utils?.GetMethod("ParseCommandLineArguments", BindingFlags.Public | BindingFlags.Static, null, Type.EmptyTypes, null)?+ .Invoke(null, null) is System.Collections.IDictionary parsed)+ {+ ArgSource = "plugin ArgsUtils";+ return parsed;+ }+ // Same shape as the plugin's resolver parser: -key value, -key=value, keys case-insensitive.+ ArgSource = "fallback parser";+ var d = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);+ var argv = Environment.GetCommandLineArgs();+ for (var i = 0; i < argv.Length; i++)+ {+ if (!argv[i].StartsWith("-")) continue;+ var key = argv[i].TrimStart('-');+ var eq = key.IndexOf('=');+ if (eq >= 0) { d[key.Substring(0, eq)] = key.Substring(eq + 1); continue; }+ d[key] = i + 1 < argv.Length && !argv[i + 1].StartsWith("-") ? argv[++i] : null;+ }+ return d;+ }++ public static string Hold(bool batch, string? simulateOverrideFailure = null){var editor = LoadedPluginEditorType();if (editor == null) return "plugin not loaded";@@ -80,21 +127,36 @@ namespace Statecraft.Game.EditorToolsreturn null;}- var failed = (ExplicitKnob("UNITY_MCP_CONNECTION_MODE") ? null : Override("ConnectionMode", t => Enum.Parse(t, "Custom")))- ?? (ExplicitKnob("UNITY_MCP_AUTH_OPTION") ? null : Override("AuthOption", t => Enum.Parse(t, "token")));- if (failed != null) return failed;- if (!batch) return "held local";-- failed = Override("KeepConnected", _ => false) ?? Override("KeepServerRunning", _ => false);- if (failed != null) return failed;- // Run each static constructor first (it queues the callback), or the unhook could come before the queueing.- failed = Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.UI.MainWindowInitializer", "PerformInitialization", runCctorOf: null, update: true)- ?? Unhook(editor.Assembly, "com.IvanMurzak.Unity.MCP.Editor.Utils.UpdateChecker", "CheckForUpdatesOnStartup",- runCctorOf: "com.IvanMurzak.Unity.MCP.Editor.Startup", update: false);- if (failed != null) return failed;- foreach (var w in Resources.FindObjectsOfTypeAll<EditorWindow>().Where(w => w.GetType().Assembly == editor.Assembly).ToList())- w.Close();- return "held offline";+ var failures = new List<string>();+ if (batch)+ {+ // 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";}catch (Exception e){diff --git a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.csindex 1337fd80e..c3c3e8b34 100644--- a/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs+++ b/unity/Assets/Tests/EditMode/UnityMcpGuardTests.cs@@ -32,6 +32,52 @@ namespace Statecraft.Tests.EditModestatic string Status() => (string)Guard().GetField("Status", Any)!.GetValue(null)!;+ /// <summary>The guard's reading of the plugin's own knob in this process (real args and env).</summary>+ static string? Knob(string envKey, string? alias, Type enumType) =>+ (string?)Guard().GetMethod("ExplicitKnob", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object?[] { envKey, alias, enumType });++ /// <summary>The pure rule, with given args and env: the plugin's precedence (flag alias, then the -KEY arg, then the+ /// env var; blank values skipped) and its parse (trimmed, quotes stripped, enum name case-insensitive).</summary>+ static string? KnobValue(string envKey, string? alias, Type enumType, Dictionary<string, string?> args, Dictionary<string, string?> env) =>+ (string?)Guard().GetMethod("KnobValue", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object?[]+ {+ envKey, alias, enumType,+ new Func<string, string?>(k => args.TryGetValue(k, out var v) ? v : null),+ new Func<string, string?>(k => env.TryGetValue(k, out var v) ? v : null),+ });++ enum Mode { Custom, Cloud }+ enum Auth { none, token, oauth }++ static Dictionary<string, string?> D(params (string k, string? v)[] kv) => kv.ToDictionary(x => x.k, x => x.v);++ [Test]+ public void TheOptOutMatchesThePluginsOwnKnob()+ {+ // env var only, any case of the value+ Assert.AreEqual("Cloud", KnobValue("UNITY_MCP_CONNECTION_MODE", null, typeof(Mode), D(), D(("UNITY_MCP_CONNECTION_MODE", " \"cloud\" "))));+ // an invalid value is no opt-out: the plugin's TryParse fails and keeps the disk value, so the guard still holds+ Assert.IsNull(KnobValue("UNITY_MCP_CONNECTION_MODE", null, typeof(Mode), D(), D(("UNITY_MCP_CONNECTION_MODE", "Clowd"))));+ // a -KEY argument beats the env var, even when the argument is invalid (the plugin stops at the first non-blank)+ Assert.AreEqual("Custom", KnobValue("UNITY_MCP_CONNECTION_MODE", null, typeof(Mode), D(("UNITY_MCP_CONNECTION_MODE", "Custom")), D(("UNITY_MCP_CONNECTION_MODE", "Cloud"))));+ Assert.IsNull(KnobValue("UNITY_MCP_CONNECTION_MODE", null, typeof(Mode), D(("UNITY_MCP_CONNECTION_MODE", "Clowd")), D(("UNITY_MCP_CONNECTION_MODE", "Cloud"))));+ // a blank argument is skipped+ Assert.AreEqual("Cloud", KnobValue("UNITY_MCP_CONNECTION_MODE", null, typeof(Mode), D(("UNITY_MCP_CONNECTION_MODE", " ")), D(("UNITY_MCP_CONNECTION_MODE", "Cloud"))));+ // the -auth alias beats -UNITY_MCP_AUTH_OPTION and the env var+ Assert.AreEqual("none", KnobValue("UNITY_MCP_AUTH_OPTION", "auth", typeof(Auth), D(("auth", "None"), ("UNITY_MCP_AUTH_OPTION", "token")), D(("UNITY_MCP_AUTH_OPTION", "oauth"))));+ Assert.AreEqual("oauth", KnobValue("UNITY_MCP_AUTH_OPTION", "auth", typeof(Auth), D(), D(("UNITY_MCP_AUTH_OPTION", "OAUTH"))));+ Assert.IsNull(KnobValue("UNITY_MCP_AUTH_OPTION", "auth", typeof(Auth), D(), D()));+ }++ [Test]+ public void TheGuardReadsArgumentsThroughThePluginsOwnParser()+ {+ if (PluginEditor() == null) { Assert.AreEqual("plugin not loaded", Status()); return; }+ // 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));+ }+[Test]public void PlayerBuildsDropThePluginAndTheDllsItsResolverDownloaded(){@@ -66,15 +112,19 @@ namespace Statecraft.Tests.EditMode.Select(a => "Library/Bee/PlayerScriptAssemblies/" + System.IO.Path.GetFileName(a.outputPath)).ToList();CollectionAssert.IsNotEmpty(fromPackages, "the plugin compiles player assemblies");- var dlls = PluginImporter.GetAllImporters()- .Where(p => !p.isNativePlugin && p.assetPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)- && (p.GetCompatibleWithPlatform(BuildTarget.WebGL)- || (p.GetCompatibleWithAnyPlatform() && !p.GetExcludeFromAnyPlatform(BuildTarget.WebGL)))- && p.assetPath.StartsWith("Assets/", StringComparison.Ordinal)- && !p.assetPath.StartsWith("Assets/Plugins/Statecraft/", StringComparison.Ordinal))- .Select(p => p.assetPath)- .ToList();- CollectionAssert.IsNotEmpty(dlls, "the resolver's runtime DLLs are WebGL-compatible");+ bool WebGl(PluginImporter p) => !p.isNativePlugin && p.assetPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)+ && (p.GetCompatibleWithPlatform(BuildTarget.WebGL) || (p.GetCompatibleWithAnyPlatform() && !p.GetExcludeFromAnyPlatform(BuildTarget.WebGL)));+ var importers = PluginImporter.GetAllImporters().Where(WebGl).Select(p => p.assetPath).ToList();+ // The resolver's install folder (NuGetConfig.InstallPath). If upstream moves it, this list empties and fails.+ var dlls = importers.Where(a => a.StartsWith("Assets/Plugins/NuGet/", StringComparison.Ordinal)).ToList();+ CollectionAssert.IsNotEmpty(dlls, "the resolver's runtime DLLs in Assets/Plugins/NuGet are WebGL-compatible");+ // Any other managed DLL a WebGL build would take must be ours or explicitly allowed; a new one is either the+ // plugin's (the filter must drop it) or a deliberate third-party addition (add it here, with its provenance).+ var allowed = new[] { "Assets/Plugins/Statecraft/" };+ var unexpected = importers.Where(a => a.StartsWith("Assets/", StringComparison.Ordinal)+ && !a.StartsWith("Assets/Plugins/NuGet/", StringComparison.Ordinal)+ && !allowed.Any(x => a.StartsWith(x, StringComparison.Ordinal))).ToList();+ CollectionAssert.IsEmpty(unexpected, "a managed DLL outside Assets/Plugins/NuGet and the allow-list would ship in WebGL builds");var all = fromPackages.Concat(dlls).ToArray();CollectionAssert.IsEmpty(Filter(all), "kept by the player-build filter");}@@ -95,15 +145,15 @@ namespace Statecraft.Tests.EditModevar config = editor.GetField("unityConnectionConfig", Any)!.GetValue(instance)!;object Get(string name) => config.GetType().GetProperty(name)!.GetValue(config)!;// The plugin's own UNITY_MCP_CONNECTION_MODE / UNITY_MCP_AUTH_OPTION knobs are an explicit opt-out the guard respects.- if (Environment.GetEnvironmentVariable("UNITY_MCP_CONNECTION_MODE") == null)- Assert.AreEqual("Custom", Get("ConnectionMode").ToString(), "never the plugin's cloud service");- if (Environment.GetEnvironmentVariable("UNITY_MCP_AUTH_OPTION") == null)- Assert.AreEqual("token", Get("AuthOption").ToString(), "the local server checks a token");+ var modeKnob = Knob("UNITY_MCP_CONNECTION_MODE", null, Get("ConnectionMode").GetType());+ var authKnob = Knob("UNITY_MCP_AUTH_OPTION", "auth", Get("AuthOption").GetType());+ Assert.AreEqual(modeKnob ?? "Custom", Get("ConnectionMode").ToString(), "never the plugin's cloud service, unless its own knob says so");+ Assert.AreEqual(authKnob ?? "token", Get("AuthOption").ToString(), "the local server checks a token, unless the plugin's own knob says otherwise");// Recorded as runtime overrides, so the plugin never writes them into the user's own settings file.var record = editor.GetProperty("RuntimeOverrides", Any)!.GetValue(instance)!;bool Tracked(string name) => (bool)record.GetType().GetMethod("Contains")!.Invoke(record, new object[] { name })!;- if (Environment.GetEnvironmentVariable("UNITY_MCP_CONNECTION_MODE") == null) Assert.IsTrue(Tracked("ConnectionMode"));- if (Environment.GetEnvironmentVariable("UNITY_MCP_AUTH_OPTION") == null) Assert.IsTrue(Tracked("AuthOption"));+ if (modeKnob == null) Assert.IsTrue(Tracked("ConnectionMode"));+ if (authKnob == null) Assert.IsTrue(Tracked("AuthOption"));if (!Application.isBatchMode) return; // the interactive editor keeps the user's connect and server choicesAssert.IsFalse((bool)Get("KeepConnected"), "no connection");Assert.IsFalse((bool)Get("KeepServerRunning"), "no local server");@@ -126,6 +176,57 @@ namespace Statecraft.Tests.EditModeCollectionAssert.IsSupersetOf(unhooked, new[] { "MainWindowInitializer.PerformInitialization", "UpdateChecker.CheckForUpdatesOnStartup" });}+ [Test]+ public void ABatchHoldStillAppliesWhenTheCustomOrTokenOverrideFails()+ {+ 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")!;+ keep.SetValue(config, true);+ server.SetValue(config, true);+ try+ {+ // 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" })!;+ 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");+ }+ finally+ {+ keep.SetValue(config, false);+ server.SetValue(config, false);+ Guard().GetMethod("Hold", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object?[] { true, null });+ }+ }++ [Test]+ public 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)!;+ 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") })+ {+ 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");+ }+ 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");+ }+[Test]public void TheTeamKillSwitchForTheUpdatePopupIsOn(){