From 12f2d426b11367448fd6ac9496ca12fed5c868b3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 29 Sep 2026 14:44:31 +0200 Subject: [PATCH] A4: admission policy and the editor lifecycle actions BrokkrCommandPolicy (Runtime, pure, tested outside Unity) is consulted by BrokkrEditorService before every BrokkrUnityCommandExecutor.Execute; it is the only call path into the executor. The per-project allowed-action list defaults to scene mutation plus lifecycle; createScriptableObject, createPrefabVariant and saveScene are shipped denied (parked Q4 = A), and an action the list does not name is denied. A denial gets a receipt with status denied and a reason. The window's buttons write intents like any other caller, so operator and agent share the gate. Re-landed from the donor as fresh code: refreshAssets, setEditorPlayState, setEditorPaused, captureEditorView, and the play-state fields on the host snapshot (keys 14-17). The donor's captureEditorView wrote to any rooted outputPath; it now resolves the path through one function that accepts only a plain relative .png path under /.brokkr/captures and refuses drive letters, rooted or UNC paths, stream suffixes and any .. segment on every host OS, and dimensions are bounded to 8192. requestedBy joins the intent (key 17) and is echoed on the receipt (key 6). saveScene is new. The window gains an Allowed Actions field bound to a per-project preference. Co-Authored-By: Claude Sonnet 5 --- brokkr-command/Program.cs | 4 +- .../BrokkrCommandCliTests.cs | 7 +- .../BrokkrCommandPolicyTests.cs | 145 ++++++++++++++++++ docs/provider-contract.md | 24 +++ .../Editor/BrokkrEditorService.cs | 10 +- .../Editor/BrokkrSettings.cs | 10 ++ .../Editor/BrokkrUnityCommandExecutor.cs | 108 +++++++++++++ .../Editor/BrokkrUnitySnapshotBuilder.cs | 7 + .../Editor/BrokkrWindow.cs | 5 + .../Runtime/BrokkrCommandPolicy.cs | 134 ++++++++++++++++ .../Runtime/BrokkrCommandPolicy.cs.meta | 2 + .../Runtime/BrokkrHostSnapshot.cs | 10 +- 12 files changed, 459 insertions(+), 7 deletions(-) create mode 100644 brokkr-contracts.Tests/BrokkrCommandPolicyTests.cs create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs create mode 100644 surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs.meta diff --git a/brokkr-command/Program.cs b/brokkr-command/Program.cs index e3f2185..8b81482 100644 --- a/brokkr-command/Program.cs +++ b/brokkr-command/Program.cs @@ -36,7 +36,8 @@ internal static class Cli ["--view"] = (command, value) => command.viewKind = value, ["--output"] = (command, value) => command.outputPath = value, ["--width"] = (command, value) => command.width = Integer("--width", value), - ["--height"] = (command, value) => command.height = Integer("--height", value) + ["--height"] = (command, value) => command.height = Integer("--height", value), + ["--requested-by"] = (command, value) => command.requestedBy = value }; internal static async Task RunAsync(string[] args) @@ -63,6 +64,7 @@ internal static class Cli Console.WriteLine($"observed: {host.observedAt}"); Console.WriteLine($"scene: {host.activeScenePath}"); Console.WriteLine($"agent-commands: {(host.agentCommandsEnabled ? "on" : "off")}"); + Console.WriteLine($"state: playing={host.isPlaying} paused={host.isPaused} compiling={host.isCompiling} updating={host.isUpdating}"); Console.WriteLine($"objects: {host.sceneObjects.Length}"); foreach (var sceneObject in host.sceneObjects.OrderBy(item => item.path, StringComparer.Ordinal)) { diff --git a/brokkr-contracts.Tests/BrokkrCommandCliTests.cs b/brokkr-contracts.Tests/BrokkrCommandCliTests.cs index f400d87..0d905e7 100644 --- a/brokkr-contracts.Tests/BrokkrCommandCliTests.cs +++ b/brokkr-contracts.Tests/BrokkrCommandCliTests.cs @@ -42,7 +42,7 @@ public sealed class BrokkrCommandCliTests "--target-object-id", "obj-1", "--name", "Widget", "--component-type", "Light", "--property-path", "m_Range", "--value", "12", "--asset-path", "Assets/x.prefab", "--parent-object-id", "parent-1", "--local-position", "1,2,3", "--local-euler-angles", "4,5,6", "--local-scale", "7,8,9", - "--view", "scene", "--output", "artifacts/shot.png", "--width", "640", "--height", "480"); + "--view", "scene", "--output", "shot.png", "--width", "640", "--height", "480", "--requested-by", "tester"); Assert.Equal(0, exit); Assert.Equal("all-fields", output.Trim()); @@ -51,13 +51,13 @@ public sealed class BrokkrCommandCliTests new[] { "all-fields", "setGameObjectTransform", "obj-1", "Widget", "Light", "m_Range", "12", "Assets/x.prefab", - "parent-1", "1,2,3", "4,5,6", "7,8,9", "scene", "artifacts/shot.png" + "parent-1", "1,2,3", "4,5,6", "7,8,9", "scene", "shot.png", "tester" }, new[] { intent.commandId, intent.action, intent.targetObjectId, intent.name, intent.componentType, intent.propertyPath, intent.value, intent.assetPath, intent.parentObjectId, intent.localPosition, - intent.localEulerAngles, intent.localScale, intent.viewKind, intent.outputPath + intent.localEulerAngles, intent.localScale, intent.viewKind, intent.outputPath, intent.requestedBy }); Assert.Equal((640, 480), (intent.width, intent.height)); } @@ -142,6 +142,7 @@ public sealed class BrokkrCommandCliTests Assert.Equal(0, result.Exit); Assert.Contains("agent-commands: on", result.Out); Assert.Contains("project: probe", result.Out); + Assert.Contains("state: playing=False paused=False compiling=False updating=False", result.Out); } [Theory] diff --git a/brokkr-contracts.Tests/BrokkrCommandPolicyTests.cs b/brokkr-contracts.Tests/BrokkrCommandPolicyTests.cs new file mode 100644 index 0000000..8a8de76 --- /dev/null +++ b/brokkr-contracts.Tests/BrokkrCommandPolicyTests.cs @@ -0,0 +1,145 @@ +using GameCult.Brokkr; + +namespace Brokkr.Contracts.Tests; + +public sealed class BrokkrCommandPolicyTests +{ + private static readonly string ProjectRoot = Path.Combine(Path.GetTempPath(), "brokkr-policy-project"); + + private static BrokkrCommandPolicy Default() => + new(ProjectRoot, BrokkrCommandPolicy.DefaultAllowedActions); + + private static BrokkrUnityCommand Capture(string outputPath, int width = 0, int height = 0) => new() + { + commandId = "c", action = "captureEditorView", viewKind = "scene", outputPath = outputPath, width = width, + height = height + }; + + [Theory] + [InlineData("createScriptableObject")] + [InlineData("createPrefabVariant")] + [InlineData("saveScene")] + public void DefaultPolicyDeniesAssetWritingAndSave(string action) + { + var admission = Default().Decide(new BrokkrUnityCommand { commandId = "c", action = action }); + + Assert.False(admission.Allowed); + Assert.Contains(action, admission.Reason); + } + + [Theory] + [InlineData("createGameObject")] + [InlineData("attachComponent")] + [InlineData("setGameObjectTransform")] + [InlineData("setGameObjectActive")] + [InlineData("setGameObjectParent")] + [InlineData("setComponentProperty")] + [InlineData("instantiatePrefab")] + [InlineData("assignMaterial")] + [InlineData("refreshAssets")] + [InlineData("setEditorPlayState")] + [InlineData("setEditorPaused")] + public void DefaultPolicyAllowsSceneMutationAndLifecycle(string action) + { + Assert.True(Default().Decide(new BrokkrUnityCommand { commandId = "c", action = action }).Allowed); + } + + [Fact] + public void UnknownActionIsDenied() + { + Assert.False(Default().Decide(new BrokkrUnityCommand { commandId = "c", action = "formatDisk" }).Allowed); + Assert.False(Default().Decide(new BrokkrUnityCommand { commandId = "c", action = "" }).Allowed); + } + + [Fact] + public void TheProjectAllowlistDecidesNotTheDefaults() + { + var policy = new BrokkrCommandPolicy(ProjectRoot, new[] { "saveScene" }); + + Assert.True(policy.Decide(new BrokkrUnityCommand { commandId = "c", action = "saveScene" }).Allowed); + Assert.False(policy.Decide(new BrokkrUnityCommand { commandId = "c", action = "createGameObject" }).Allowed); + } + + [Fact] + public void AllowlistTextParsesCommaSeparatedNames() + { + Assert.Equal( + new[] { "saveScene", "refreshAssets" }, + BrokkrCommandPolicy.ParseAllowedActions(" saveScene, ,refreshAssets;").ToArray()); + } + + [Theory] + [InlineData("shot.png")] + [InlineData("views/scene 1.png")] + [InlineData("a/./b.PNG")] + public void CaptureInsideTheCaptureDirectoryIsAdmittedAndResolvedThere(string outputPath) + { + Assert.True(Default().Decide(Capture(outputPath)).Allowed); + + var resolved = BrokkrCommandPolicy.ResolveCapturePath(ProjectRoot, outputPath); + Assert.StartsWith(BrokkrCommandPolicy.CaptureDirectory(ProjectRoot) + Path.DirectorySeparatorChar, resolved); + } + + [Theory] + [InlineData("C:/Windows/x.png")] + [InlineData("C:\\Windows\\x.png")] + [InlineData("/etc/x.png")] + [InlineData("\\\\server\\share\\x.png")] + [InlineData("../../x.png")] + [InlineData("..\\x.png")] + [InlineData("a/../../x.png")] + [InlineData("shot.png:stream")] + [InlineData("x.txt")] + [InlineData("x.cs")] + [InlineData("noextension")] + [InlineData("")] + [InlineData(" ")] + public void CaptureOutsideTheCaptureDirectoryOrNotAPngIsDenied(string outputPath) + { + var admission = Default().Decide(Capture(outputPath)); + + Assert.False(admission.Allowed); + Assert.NotEmpty(admission.Reason); + Assert.Throws(() => BrokkrCommandPolicy.ResolveCapturePath(ProjectRoot, outputPath)); + } + + [Theory] + [InlineData(-1, 0)] + [InlineData(0, -5)] + [InlineData(8193, 100)] + [InlineData(100, 100000)] + public void CaptureDimensionsAreBounded(int width, int height) + { + Assert.False(Default().Decide(Capture("shot.png", width, height)).Allowed); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(640, 480)] + [InlineData(8192, 8192)] + public void ReasonableCaptureDimensionsAreAdmitted(int width, int height) + { + Assert.True(Default().Decide(Capture("shot.png", width, height)).Allowed); + } + + [Fact] + public void OnlyCaptureIsHeldToTheCapturePathRule() + { + var command = new BrokkrUnityCommand { commandId = "c", action = "refreshAssets", outputPath = "/anything" }; + + Assert.True(Default().Decide(command).Allowed); + } + + [Fact] + public void DenialGetsAReceiptThatNamesTheIdAndTheReason() + { + var command = new BrokkrUnityCommand { commandId = "denied-1", action = "createScriptableObject" }; + var admission = Default().Decide(command); + + var receipt = admission.DeniedReceipt(command); + + Assert.Equal("denied", receipt.status); + Assert.Equal("denied-1", receipt.commandId); + Assert.Equal(admission.Reason, receipt.message); + } +} diff --git a/docs/provider-contract.md b/docs/provider-contract.md index e8cd2ff..b231a38 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -142,6 +142,11 @@ All Unity writes use `brokkr.unity.command_intent.v0` and receive - `createPrefabVariant` - `assignMaterial` - `createScriptableObject` +- `refreshAssets` +- `setEditorPlayState` +- `setEditorPaused` +- `captureEditorView` +- `saveScene` Unity owns the mutation. Brokkr advertises the command surface; Verse clients write typed command intents; Unity executes recognized intents and publishes @@ -157,6 +162,25 @@ optional instance name, and `parentObjectId` as the optional parent. destination prefab path. `createScriptableObject` uses `componentType` as the ScriptableObject type and `assetPath` as the destination asset path. +`refreshAssets` forces an AssetDatabase refresh. `setEditorPlayState` and +`setEditorPaused` take boolean `value`; the editor service restarts from +`[InitializeOnLoad]` after the resulting domain reload and keeps draining. +`captureEditorView` renders `viewKind` (`scene` or `game`) to a PNG at `width` +by `height` (0 means the camera size, at most 8192). `outputPath` is a plain +relative path ending in `.png`, resolved under `/.brokkr/captures/`; +anything else is denied. `saveScene` saves the open scenes. + +### Admission + +Before any intent runs, `BrokkrCommandPolicy` checks it against the project's +allowed-action list (window field "Allowed Actions", per project). By default +scene mutation and editor lifecycle actions are allowed; the asset-writing +actions `createScriptableObject` and `createPrefabVariant`, and `saveScene`, +are not, and an action the list does not name is denied. A denied intent gets a +receipt with `status: denied` and the reason in `message`, so a refusal is as +visible as an acceptance. `requestedBy` on the intent names the caller and is +echoed on the receipt; admission never reads it. The window's buttons write +intents like any other caller, so the operator and an agent pass the same gate. ## Unity Command Transport diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorService.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorService.cs index 4dabd50..6139c33 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorService.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorService.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Threading.Tasks; using UnityEditor; using UnityEngine; @@ -111,12 +112,19 @@ namespace GameCult.Brokkr.Editor private static void DrainCommands() { + var projectRoot = Directory.GetParent(Application.dataPath)?.FullName ?? Application.dataPath; + var policy = new BrokkrCommandPolicy(projectRoot, BrokkrSettings.AllowedAgentActions); var drained = false; while (MirrorInstance.Ledger.TryNextPending(out var command)) { - var receipt = BrokkrUnityCommandExecutor.Execute(command); + // The one call path into the executor, and admission is its precondition. + var admission = policy.Decide(command); + var receipt = admission.Allowed + ? BrokkrUnityCommandExecutor.Execute(command) + : admission.DeniedReceipt(command); // The receipt answers exactly the id it ran, or the ledger would offer the intent again. receipt.commandId = command.commandId; + receipt.requestedBy = command.requestedBy; MirrorInstance.PublishReceiptAsync(receipt).GetAwaiter().GetResult(); drained = true; } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs index adc8ecd..c9b84ec 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrSettings.cs @@ -1,3 +1,4 @@ +using System.Linq; using UnityEditor; using UnityEngine; @@ -31,6 +32,15 @@ namespace GameCult.Brokkr.Editor private static string ProjectKey(string name) => $"GameCult.Brokkr.{name}.{Application.dataPath}"; + // The actions this project lets an agent run (comma separated). Asset-writing actions and saveScene are + // absent until the operator adds them. + internal static string[] AllowedAgentActions + { + get => BrokkrCommandPolicy.ParseAllowedActions(EditorPrefs.GetString( + ProjectKey("AllowedAgentActions"), string.Join(",", BrokkrCommandPolicy.DefaultAllowedActions))).ToArray(); + set => EditorPrefs.SetString(ProjectKey("AllowedAgentActions"), string.Join(",", value)); + } + internal static string CultMeshCachePath { get => EditorPrefs.GetString(ProjectKey("CultMeshCachePath"), BrokkrCultMeshMirror.DefaultCachePath()); diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnityCommandExecutor.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnityCommandExecutor.cs index d071672..37e7085 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnityCommandExecutor.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnityCommandExecutor.cs @@ -1,5 +1,6 @@ using System; using System.Globalization; +using System.IO; using System.Linq; using GameCult.Brokkr; using UnityEditor; @@ -26,6 +27,11 @@ namespace GameCult.Brokkr.Editor "createPrefabVariant" => CreatePrefabVariant(command), "assignMaterial" => AssignMaterial(command), "createScriptableObject" => CreateScriptableObject(command), + "refreshAssets" => RefreshAssets(command), + "setEditorPlayState" => SetEditorPlayState(command), + "setEditorPaused" => SetEditorPaused(command), + "captureEditorView" => CaptureEditorView(command), + "saveScene" => SaveScene(command), _ => Failed(command, $"Unsupported Unity command action: {command.action}") }; } @@ -35,6 +41,108 @@ namespace GameCult.Brokkr.Editor } } + private static BrokkrUnityCommandReceipt RefreshAssets(BrokkrUnityCommand command) + { + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); + return Accepted(command, "Asset database refreshed.", ""); + } + + private static BrokkrUnityCommandReceipt SetEditorPlayState(BrokkrUnityCommand command) + { + if (!bool.TryParse(command.value, out var shouldPlay)) + { + return Failed(command, "Play state value must be true or false."); + } + + EditorApplication.isPlaying = shouldPlay; + return Accepted(command, shouldPlay ? "Entering Play mode." : "Leaving Play mode.", ""); + } + + private static BrokkrUnityCommandReceipt SetEditorPaused(BrokkrUnityCommand command) + { + if (!bool.TryParse(command.value, out var shouldPause)) + { + return Failed(command, "Pause state value must be true or false."); + } + + EditorApplication.isPaused = shouldPause; + return Accepted(command, shouldPause ? "Editor paused." : "Editor resumed.", ""); + } + + // Shipped denied by BrokkrCommandPolicy; a project that allows it saves every open scene. + private static BrokkrUnityCommandReceipt SaveScene(BrokkrUnityCommand command) + { + return EditorSceneManager.SaveOpenScenes() + ? Accepted(command, "Open scenes saved.", "") + : Failed(command, "Saving the open scenes failed."); + } + + private static BrokkrUnityCommandReceipt CaptureEditorView(BrokkrUnityCommand command) + { + var camera = ResolveCaptureCamera(command.viewKind); + if (camera == null) + { + return Failed(command, $"No {command.viewKind} camera is available."); + } + + var projectRoot = Directory.GetParent(Application.dataPath)?.FullName ?? Application.dataPath; + // The policy admitted this path; the same resolver names the file, so there is no second rule. + var outputPath = BrokkrCommandPolicy.ResolveCapturePath(projectRoot, command.outputPath); + var directory = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + var width = command.width > 0 ? command.width : Math.Max(camera.pixelWidth, 1); + var height = command.height > 0 ? command.height : Math.Max(camera.pixelHeight, 1); + var target = RenderTexture.GetTemporary(width, height, 24, RenderTextureFormat.ARGB32, + RenderTextureReadWrite.sRGB); + var previousTarget = camera.targetTexture; + var previousActive = RenderTexture.active; + try + { + camera.targetTexture = target; + camera.Render(); + RenderTexture.active = target; + var image = new Texture2D(width, height, TextureFormat.RGBA32, false); + try + { + image.ReadPixels(new Rect(0, 0, width, height), 0, 0); + image.Apply(false, false); + File.WriteAllBytes(outputPath, image.EncodeToPNG()); + } + finally + { + UnityEngine.Object.DestroyImmediate(image); + } + } + finally + { + camera.targetTexture = previousTarget; + RenderTexture.active = previousActive; + RenderTexture.ReleaseTemporary(target); + } + + return Accepted(command, $"Captured {command.viewKind} view.", outputPath); + } + + private static Camera ResolveCaptureCamera(string viewKind) + { + if (string.Equals(viewKind, "scene", StringComparison.OrdinalIgnoreCase)) + { + return SceneView.lastActiveSceneView != null ? SceneView.lastActiveSceneView.camera : null; + } + + if (string.Equals(viewKind, "game", StringComparison.OrdinalIgnoreCase)) + { + return Camera.main ?? UnityEngine.Object.FindObjectsOfType() + .FirstOrDefault(candidate => candidate.enabled); + } + + return null; + } + private static BrokkrUnityCommandReceipt CreateGameObject(BrokkrUnityCommand command) { var gameObject = new GameObject(string.IsNullOrWhiteSpace(command.name) diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs index 0af936f..45ae610 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrUnitySnapshotBuilder.cs @@ -21,6 +21,9 @@ namespace GameCult.Brokkr.Editor "scene.tree.read", "selection.read", "asset.catalog.read", + "editor.assets.refresh", + "editor.lifecycle.write", + "editor.view.capture", "command.palette.read", "command.execute", "receipt.read" @@ -42,6 +45,10 @@ namespace GameCult.Brokkr.Editor .ToArray(), assetCount = AssetDatabase.GetAllAssetPaths().Length, agentCommandsEnabled = BrokkrSettings.AgentCommandsEnabled, + isPlaying = EditorApplication.isPlaying, + isPaused = EditorApplication.isPaused, + isCompiling = EditorApplication.isCompiling, + isUpdating = EditorApplication.isUpdating, capabilities = Capabilities, sceneObjects = CaptureSceneObjects(), assets = CaptureAssets() diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs index 76d70f3..4b446fb 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrWindow.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using GameCult.Brokkr; using UnityEditor; using UnityEngine; @@ -10,6 +11,7 @@ namespace GameCult.Brokkr.Editor private string brokerUri = BrokkrSettings.DefaultBrokerUri; private string cultMeshCachePath = ""; private bool autoPublish; + private string allowedAgentActions = ""; private BrokkrHostSnapshot lastSnapshot; private BrokkrSyncReceipt lastSyncReceipt; private string lastReceipt = "No snapshot published yet."; @@ -65,6 +67,7 @@ namespace GameCult.Brokkr.Editor brokerUri = BrokkrSettings.BrokerUri; cultMeshCachePath = BrokkrSettings.CultMeshCachePath; autoPublish = BrokkrSettings.AutoPublish; + allowedAgentActions = string.Join(",", BrokkrSettings.AllowedAgentActions); syncSessionId = BrokkrSettings.SyncSessionId; syncDisplayName = BrokkrSettings.SyncDisplayName; blenderObjectName = BrokkrSettings.BlenderObjectName; @@ -126,12 +129,14 @@ namespace GameCult.Brokkr.Editor BrokkrSettings.AgentCommandsEnabled ? (Mirror.IsRunning ? $"executing intents from {Mirror.CachePath}" : "enabled, mirror not running") : "off: no intent written into .brokkr will run"); + allowedAgentActions = EditorGUILayout.TextField("Allowed Actions", allowedAgentActions); if (GUILayout.Button("Save Settings")) { BrokkrSettings.BrokerUri = brokerUri; BrokkrSettings.CultMeshCachePath = cultMeshCachePath; BrokkrSettings.AutoPublish = autoPublish; + BrokkrSettings.AllowedAgentActions = BrokkrCommandPolicy.ParseAllowedActions(allowedAgentActions).ToArray(); BrokkrSettings.SyncSessionId = syncSessionId; BrokkrSettings.SyncDisplayName = syncDisplayName; BrokkrSettings.BlenderObjectName = blenderObjectName; diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs new file mode 100644 index 0000000..d484739 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs @@ -0,0 +1,134 @@ +#nullable disable +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace GameCult.Brokkr +{ + // Admission: decides whether the editor may run an intent at all. BrokkrEditorService asks before every + // BrokkrUnityCommandExecutor.Execute; the window's buttons write intents like any other caller, so the operator + // and an agent pass through this one gate. Pure logic, so it is tested outside Unity. + public sealed class BrokkrCommandPolicy + { + // Scene mutation and editor lifecycle. Actions that write assets into the project (createScriptableObject, + // createPrefabVariant) and saveScene are absent: the operator opts in per project. + public static readonly string[] DefaultAllowedActions = + { + "createGameObject", "attachComponent", "setGameObjectTransform", "setGameObjectActive", + "setGameObjectParent", "setComponentProperty", "instantiatePrefab", "assignMaterial", + "refreshAssets", "setEditorPlayState", "setEditorPaused", "captureEditorView" + }; + + public const string CaptureAction = "captureEditorView"; + public const int MaxCaptureDimension = 8192; + + private readonly HashSet allowed; + private readonly string projectRoot; + + public BrokkrCommandPolicy(string projectRoot, IEnumerable allowedActions) + { + this.projectRoot = projectRoot ?? throw new ArgumentNullException(nameof(projectRoot)); + allowed = new HashSet(allowedActions ?? throw new ArgumentNullException(nameof(allowedActions)), + StringComparer.Ordinal); + } + + public static IEnumerable ParseAllowedActions(string commaSeparated) => + (commaSeparated ?? "") + .Split(new[] { ',', ';', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(action => action.Trim()) + .Where(action => action.Length > 0); + + // The only directory captureEditorView writes to; an intent's outputPath is relative to it. + public static string CaptureDirectory(string projectRoot) => + Path.GetFullPath(Path.Combine(projectRoot, ".brokkr", "captures")); + + // The one place that turns an intent's outputPath into a file path. It refuses every spelling that could + // leave the capture directory, whatever the host OS thinks a rooted path is, and writes only PNG names. + public static string ResolveCapturePath(string projectRoot, string outputPath) + { + if (string.IsNullOrWhiteSpace(outputPath)) + { + throw new ArgumentException("Capture outputPath is required."); + } + + var separators = new[] { '/', '\\' }; + if (outputPath.IndexOf(':') >= 0 + || separators.Contains(outputPath[0]) + || outputPath.Split(separators).Any(segment => segment == "..") + || outputPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0) + { + throw new ArgumentException( + "Capture outputPath must be a plain relative path inside .brokkr/captures."); + } + + if (!outputPath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("Capture outputPath must name a .png file."); + } + + var directory = CaptureDirectory(projectRoot); + var full = Path.GetFullPath(Path.Combine(directory, outputPath)); + if (!full.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { + throw new ArgumentException("Capture outputPath resolves outside .brokkr/captures."); + } + + return full; + } + + public BrokkrCommandAdmission Decide(BrokkrUnityCommand command) + { + if (!allowed.Contains(command.action ?? "")) + { + return BrokkrCommandAdmission.Deny($"Action '{command.action}' is not allowed for this project."); + } + + if (command.action == CaptureAction) + { + try + { + ResolveCapturePath(projectRoot, command.outputPath); + } + catch (ArgumentException error) + { + return BrokkrCommandAdmission.Deny(error.Message); + } + + if (command.width < 0 || command.height < 0 + || command.width > MaxCaptureDimension || command.height > MaxCaptureDimension) + { + return BrokkrCommandAdmission.Deny( + $"Capture width and height must be between 0 and {MaxCaptureDimension}."); + } + } + + return BrokkrCommandAdmission.Allow; + } + } + + public sealed class BrokkrCommandAdmission + { + public static readonly BrokkrCommandAdmission Allow = new BrokkrCommandAdmission(true, ""); + + public bool Allowed { get; } + public string Reason { get; } + + private BrokkrCommandAdmission(bool allowed, string reason) + { + Allowed = allowed; + Reason = reason; + } + + public static BrokkrCommandAdmission Deny(string reason) => new BrokkrCommandAdmission(false, reason); + + // A refusal is as inspectable as an acceptance: it gets a receipt of its own. + public BrokkrUnityCommandReceipt DeniedReceipt(BrokkrUnityCommand command) => new BrokkrUnityCommandReceipt + { + commandId = command.commandId, + status = "denied", + message = Reason, + observedAt = DateTime.UtcNow.ToString("O") + }; + } +} diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs.meta b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs.meta new file mode 100644 index 0000000..01c1272 --- /dev/null +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrCommandPolicy.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9621754a04b94e29a6f7fb3b32aff3fc diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs index 4affd17..2da7a2b 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs @@ -23,7 +23,10 @@ namespace GameCult.Brokkr [Key(11)] public string[] capabilities = Array.Empty(); [Key(12)] public BrokkrGameObjectSnapshot[] sceneObjects = Array.Empty(); [Key(13)] public BrokkrAssetSnapshot[] assets = Array.Empty(); - // Keys 14-17 are reserved for the editor play-state fields (A4). + [Key(14)] public bool isPlaying; + [Key(15)] public bool isPaused; + [Key(16)] public bool isCompiling; + [Key(17)] public bool isUpdating; // False means the editor executes no agent commands: the operator has not enabled the sink. [Key(18)] public bool agentCommandsEnabled; } @@ -112,11 +115,13 @@ namespace GameCult.Brokkr [Key(10)] public string localPosition = ""; [Key(11)] public string localEulerAngles = ""; [Key(12)] public string localScale = ""; - // Editor view capture (A4): viewKind is scene or game; outputPath is relative to the project root. + // Editor view capture: viewKind is scene or game; outputPath is relative to .brokkr/captures (BrokkrCommandPolicy). [Key(13)] public string viewKind = ""; [Key(14)] public string outputPath = ""; [Key(15)] public int width; [Key(16)] public int height; + // Who asked: a caller's name for itself, echoed on the receipt. Informational; admission never reads it. + [Key(17)] public string requestedBy = ""; } [MessagePackObject] @@ -137,5 +142,6 @@ namespace GameCult.Brokkr [Key(3)] public string message = ""; [Key(4)] public string objectId = ""; [Key(5)] public string observedAt = ""; + [Key(6)] public string requestedBy = ""; } }