A1: BrokkrEditorService is the one command owner; the sink is off by default

Deleted: the window's command drain (OnEditorUpdate poll, Poll Mirror Command,
PublishCommandAndPoll executing), the window's own second mirror, and the
machine-global AutoPollCommands setting. The mirror lost its Watch-fed queue
and its in-memory dedup sets; BrokkrCommandLedger derives "pending" from the
cache on every call.

BrokkrEditorService ([InitializeOnLoad], one EditorApplication.update
registration, no asset-import or reload-script hooks) owns the mirror, the
one-second pull and the drain. AgentCommandsEnabled is per project and false
until the operator ticks the window toggle; loading the package opens no
store. The flag is published in the host snapshot. The mirror uses the
directory store with StartServer=false, so there is no listener.

The store path preference is now keyed by project too: it was one value for
every project on the machine, so enabling the sink in one project could have
opened another project's .brokkr.

Not compiled: Unity code is checked by the operator (see the A1 smoke steps).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-29 14:20:36 +02:00
commit 68319ddaf8
6 changed files with 227 additions and 131 deletions

View file

@ -3,24 +3,25 @@ using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using GameCult.Mesh;
using GameCult.Networking;
using R3;
using UnityEditor;
using UnityEngine;
namespace GameCult.Brokkr.Editor
{
// The one open handle on the project's directory store. BrokkrEditorService owns the only instance; the window
// publishes through it and never opens the store itself.
internal sealed class BrokkrCultMeshMirror : IDisposable
{
private readonly Queue<BrokkrUnityCommand> commandQueue = new();
private readonly Queue<BrokkrSyncReceipt> syncReceiptQueue = new();
private CultMeshNode node;
private IDisposable commandSubscription;
private IDisposable syncReceiptSubscription;
internal bool IsRunning => node != null;
internal string CachePath { get; private set; } = "";
internal BrokkrCommandLedger Ledger { get; private set; }
internal async Task StartAsync(string cachePath)
{
@ -32,24 +33,23 @@ namespace GameCult.Brokkr.Editor
CachePath = cachePath;
Directory.CreateDirectory(Path.GetDirectoryName(cachePath) ?? ".");
node = await CultMesh.StartNodeAsync(cachePath, new CultMeshNodeOptions
// File transport: no listener, no endpoint. Other processes reach the editor through the store and are
// seen on the next pull.
node = await CultMesh.CreateNodeAsync(cachePath, new CultMeshNodeOptions
{
StartServer = false,
CacheOptions = new CultCacheOpenOptions
{
UseDirectoryStore = true
},
EnableDurableShardLogs = true,
DatabaseOptions = new CultNetDatabaseOptions
{
RuntimeId = "brokkr-unity-editor"
}
});
Ledger = new BrokkrCommandLedger(node.Cache);
commandSubscription = node.Database
.Watch<BrokkrUnityCommand>()
.Subscribe(change =>
{
if (change.Document != null)
{
commandQueue.Enqueue(change.Document);
}
});
syncReceiptSubscription = node.Database
.Watch<BrokkrSyncReceipt>()
.Subscribe(change =>
@ -61,6 +61,12 @@ namespace GameCult.Brokkr.Editor
});
}
internal async Task PullExternalUpdatesAsync()
{
RequireRunning();
await Ledger.PullAsync();
}
internal async Task PublishSnapshotAsync(BrokkrHostSnapshot snapshot)
{
RequireRunning();
@ -68,24 +74,29 @@ namespace GameCult.Brokkr.Editor
await node.FlushAsync(soft: true);
}
// The receipt is the only proof an intent ran, and it is keyed by the intent it answers.
internal async Task PublishReceiptAsync(BrokkrUnityCommandReceipt receipt)
{
RequireRunning();
var key = string.IsNullOrWhiteSpace(receipt.commandId)
? $"unity/receipts/{Guid.NewGuid():N}"
: $"unity/receipts/{receipt.commandId}";
await node.Database.PutAsync(new CultRecordKey(key), receipt);
if (string.IsNullOrWhiteSpace(receipt.commandId))
{
throw new ArgumentException("A receipt must name the command it answers.", nameof(receipt));
}
await node.Database.PutAsync(BrokkrCommandLedger.ReceiptKey(receipt.commandId), receipt);
await node.FlushAsync(soft: true);
}
// Command ids are single-use: a caller with no id gets a fresh one, and reusing an answered id is a defect.
internal async Task PublishCommandAsync(BrokkrUnityCommand command)
{
RequireRunning();
var commandId = string.IsNullOrWhiteSpace(command.commandId)
? Guid.NewGuid().ToString("N")
: command.commandId;
command.commandId = commandId;
await node.Database.PutAsync(new CultRecordKey($"unity/commands/{commandId}"), command);
if (string.IsNullOrWhiteSpace(command.commandId))
{
command.commandId = Guid.NewGuid().ToString("N");
}
await node.Database.PutAsync(BrokkrCommandLedger.CommandKey(command.commandId), command);
await node.FlushAsync(soft: true);
}
@ -124,18 +135,6 @@ namespace GameCult.Brokkr.Editor
await node.FlushAsync(soft: true);
}
internal bool TryDequeueCommand(out BrokkrUnityCommand command)
{
if (commandQueue.Count > 0)
{
command = commandQueue.Dequeue();
return true;
}
command = null;
return false;
}
internal bool TryDequeueSyncReceipt(out BrokkrSyncReceipt receipt)
{
if (syncReceiptQueue.Count > 0)
@ -164,12 +163,11 @@ namespace GameCult.Brokkr.Editor
public void Dispose()
{
commandSubscription?.Dispose();
commandSubscription = null;
syncReceiptSubscription?.Dispose();
syncReceiptSubscription = null;
node?.Dispose();
node = null;
Ledger = null;
}
}
}

View file

@ -0,0 +1,130 @@
using System;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
namespace GameCult.Brokkr.Editor
{
// The only owner of command execution in the editor. It owns the mirror, the pull cadence and the drain; the
// window is a caller (it writes intents) and a display (it reads state from here). Nothing else calls
// BrokkrCommandLedger.TryNextPending or BrokkrUnityCommandExecutor.Execute.
//
// The command sink is off until the operator enables it for this project (BrokkrSettings.AgentCommandsEnabled).
// Loading the package opens no store and executes nothing.
[InitializeOnLoad]
internal static class BrokkrEditorService
{
private const double PullIntervalSeconds = 1.0;
private static readonly BrokkrCultMeshMirror MirrorInstance = new BrokkrCultMeshMirror();
private static double nextPullAt;
private static bool starting;
static BrokkrEditorService()
{
// [InitializeOnLoad] runs again after every domain reload, so this is the only registration.
EditorApplication.update += Tick;
AssemblyReloadEvents.beforeAssemblyReload += MirrorInstance.Dispose;
EditorApplication.quitting += MirrorInstance.Dispose;
if (BrokkrSettings.AgentCommandsEnabled)
{
EditorApplication.delayCall += () => _ = StartAsync();
}
}
internal static BrokkrCultMeshMirror Mirror => MirrorInstance;
// The newest sync receipt seen; display only.
internal static BrokkrSyncReceipt LastSyncReceipt { get; private set; }
internal static async Task StartAsync()
{
if (starting || MirrorInstance.IsRunning)
{
return;
}
starting = true;
try
{
await MirrorInstance.StartAsync(BrokkrSettings.CultMeshCachePath);
await PublishSnapshotAsync();
}
catch (Exception error)
{
Debug.LogWarning($"Brokkr editor service failed to start: {error.Message}");
}
finally
{
starting = false;
}
}
internal static async Task SetAgentCommandsEnabledAsync(bool enabled)
{
BrokkrSettings.AgentCommandsEnabled = enabled;
if (enabled)
{
await StartAsync();
}
// The snapshot carries the flag, so a caller can see why nothing executes.
await PublishSnapshotAsync();
}
internal static async Task PublishSnapshotAsync()
{
if (MirrorInstance.IsRunning)
{
await MirrorInstance.PublishSnapshotAsync(BrokkrUnitySnapshotBuilder.Capture());
}
}
private static void Tick()
{
if (!MirrorInstance.IsRunning)
{
return;
}
while (MirrorInstance.TryDequeueSyncReceipt(out var syncReceipt))
{
LastSyncReceipt = syncReceipt;
}
if (!BrokkrSettings.AgentCommandsEnabled || EditorApplication.timeSinceStartup < nextPullAt)
{
return;
}
nextPullAt = EditorApplication.timeSinceStartup + PullIntervalSeconds;
try
{
MirrorInstance.PullExternalUpdatesAsync().GetAwaiter().GetResult();
DrainCommands();
}
catch (Exception error)
{
Debug.LogWarning($"Brokkr editor service tick failed: {error.Message}");
}
}
private static void DrainCommands()
{
var drained = false;
while (MirrorInstance.Ledger.TryNextPending(out var command))
{
var receipt = BrokkrUnityCommandExecutor.Execute(command);
// The receipt answers exactly the id it ran, or the ledger would offer the intent again.
receipt.commandId = command.commandId;
MirrorInstance.PublishReceiptAsync(receipt).GetAwaiter().GetResult();
drained = true;
}
if (drained)
{
PublishSnapshotAsync().GetAwaiter().GetResult();
}
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d8a002bde1a940c5b1a9d8b40c8137ee

View file

@ -1,4 +1,5 @@
using UnityEditor;
using UnityEngine;
namespace GameCult.Brokkr.Editor
{
@ -20,16 +21,20 @@ namespace GameCult.Brokkr.Editor
set => EditorPrefs.SetBool("GameCult.Brokkr.AutoPublish", value);
}
internal static bool AutoPollCommands
// Whether this editor executes intents that agents write into .brokkr. Off until the operator turns it on.
// EditorPrefs is shared by every project on the machine, so the store path and the flag both key on the project.
internal static bool AgentCommandsEnabled
{
get => EditorPrefs.GetBool("GameCult.Brokkr.AutoPollCommands", false);
set => EditorPrefs.SetBool("GameCult.Brokkr.AutoPollCommands", value);
get => EditorPrefs.GetBool(ProjectKey("AgentCommandsEnabled"), false);
set => EditorPrefs.SetBool(ProjectKey("AgentCommandsEnabled"), value);
}
private static string ProjectKey(string name) => $"GameCult.Brokkr.{name}.{Application.dataPath}";
internal static string CultMeshCachePath
{
get => EditorPrefs.GetString("GameCult.Brokkr.CultMeshCachePath", BrokkrCultMeshMirror.DefaultCachePath());
set => EditorPrefs.SetString("GameCult.Brokkr.CultMeshCachePath", value);
get => EditorPrefs.GetString(ProjectKey("CultMeshCachePath"), BrokkrCultMeshMirror.DefaultCachePath());
set => EditorPrefs.SetString(ProjectKey("CultMeshCachePath"), value);
}
internal static string SyncSessionId

View file

@ -41,6 +41,7 @@ namespace GameCult.Brokkr.Editor
.Select(item => item.name)
.ToArray(),
assetCount = AssetDatabase.GetAllAssetPaths().Length,
agentCommandsEnabled = BrokkrSettings.AgentCommandsEnabled,
capabilities = Capabilities,
sceneObjects = CaptureSceneObjects(),
assets = CaptureAssets()

View file

@ -10,13 +10,11 @@ namespace GameCult.Brokkr.Editor
private string brokerUri = BrokkrSettings.DefaultBrokerUri;
private string cultMeshCachePath = "";
private bool autoPublish;
private bool autoPollCommands;
private BrokkrHostSnapshot lastSnapshot;
private BrokkrSyncReceipt lastSyncReceipt;
private string lastReceipt = "No snapshot published yet.";
private MessageType lastMessageType = MessageType.Info;
private double nextPollAt;
private BrokkrCultMeshMirror mirror;
private static BrokkrCultMeshMirror Mirror => BrokkrEditorService.Mirror;
private string syncSessionId = "default";
private string syncDisplayName = "Brokkr Editor Sync";
private string blenderObjectName = "";
@ -67,7 +65,6 @@ namespace GameCult.Brokkr.Editor
brokerUri = BrokkrSettings.BrokerUri;
cultMeshCachePath = BrokkrSettings.CultMeshCachePath;
autoPublish = BrokkrSettings.AutoPublish;
autoPollCommands = BrokkrSettings.AutoPollCommands;
syncSessionId = BrokkrSettings.SyncSessionId;
syncDisplayName = BrokkrSettings.SyncDisplayName;
blenderObjectName = BrokkrSettings.BlenderObjectName;
@ -108,8 +105,6 @@ namespace GameCult.Brokkr.Editor
EditorSceneManagerBridge.SceneDirtied -= OnEditorSignal;
EditorApplication.playModeStateChanged -= OnPlayModeChanged;
EditorApplication.update -= OnEditorUpdate;
mirror?.Dispose();
mirror = null;
}
private void OnGUI()
@ -119,14 +114,24 @@ namespace GameCult.Brokkr.Editor
brokerUri = EditorGUILayout.TextField("Broker URI", brokerUri);
cultMeshCachePath = EditorGUILayout.TextField("CultMesh Cache", cultMeshCachePath);
autoPublish = EditorGUILayout.Toggle("Auto Publish", autoPublish);
autoPollCommands = EditorGUILayout.Toggle("Auto Poll Commands", autoPollCommands);
var agentCommands = EditorGUILayout.Toggle("Agent Commands", BrokkrSettings.AgentCommandsEnabled);
if (agentCommands != BrokkrSettings.AgentCommandsEnabled)
{
SetAgentCommands(agentCommands);
}
EditorGUILayout.LabelField(
"Command Sink",
BrokkrSettings.AgentCommandsEnabled
? (Mirror.IsRunning ? $"executing intents from {Mirror.CachePath}" : "enabled, mirror not running")
: "off: no intent written into .brokkr will run");
if (GUILayout.Button("Save Settings"))
{
BrokkrSettings.BrokerUri = brokerUri;
BrokkrSettings.CultMeshCachePath = cultMeshCachePath;
BrokkrSettings.AutoPublish = autoPublish;
BrokkrSettings.AutoPollCommands = autoPollCommands;
BrokkrSettings.SyncSessionId = syncSessionId;
BrokkrSettings.SyncDisplayName = syncDisplayName;
BrokkrSettings.BlenderObjectName = blenderObjectName;
@ -178,16 +183,6 @@ namespace GameCult.Brokkr.Editor
{
CaptureSnapshot();
}
if (GUILayout.Button("Poll Mirror Command"))
{
PollAndExecuteCommand(false);
}
if (GUILayout.Button("Poll Sync Receipt"))
{
PollSyncReceipts(false);
}
}
EditorGUILayout.Space();
@ -351,7 +346,7 @@ namespace GameCult.Brokkr.Editor
}
RequireMirror();
mirror.PublishSnapshotAsync(lastSnapshot).GetAwaiter().GetResult();
Mirror.PublishSnapshotAsync(lastSnapshot).GetAwaiter().GetResult();
SetStatus($"Mirrored Unity snapshot: {lastSnapshot.observedAt}", MessageType.Info);
}
catch (Exception error)
@ -360,13 +355,37 @@ namespace GameCult.Brokkr.Editor
}
}
private async void SetAgentCommands(bool enabled)
{
try
{
await BrokkrEditorService.SetAgentCommandsEnabledAsync(enabled);
SetStatus(enabled ? "Agent commands enabled for this project." : "Agent commands disabled.", MessageType.Info);
}
catch (Exception error)
{
SetStatus(error.Message, MessageType.Error);
}
}
private async void StartMirror()
{
try
{
mirror ??= new BrokkrCultMeshMirror();
await mirror.StartAsync(cultMeshCachePath);
SetStatus($"CultMesh mirror running: {mirror.CachePath}", MessageType.Info);
if (Mirror.IsRunning && Mirror.CachePath != cultMeshCachePath)
{
throw new InvalidOperationException(
$"The mirror is already running at {Mirror.CachePath}; a new path applies after an editor restart.");
}
BrokkrSettings.CultMeshCachePath = cultMeshCachePath;
await BrokkrEditorService.StartAsync();
if (!Mirror.IsRunning)
{
throw new InvalidOperationException("The mirror did not start; see the Console.");
}
SetStatus($"CultMesh mirror running: {Mirror.CachePath}", MessageType.Info);
}
catch (Exception error)
{
@ -374,65 +393,6 @@ namespace GameCult.Brokkr.Editor
}
}
private void PollAndExecuteCommand(bool quiet)
{
try
{
RequireMirror();
if (!mirror.TryDequeueCommand(out var command) || string.IsNullOrEmpty(command.commandId))
{
if (!quiet)
{
SetStatus("No queued CultMesh Unity command.", MessageType.Info);
}
return;
}
var receipt = BrokkrUnityCommandExecutor.Execute(command);
mirror.PublishReceiptAsync(receipt).GetAwaiter().GetResult();
lastSnapshot = BrokkrUnitySnapshotBuilder.Capture();
mirror.PublishSnapshotAsync(lastSnapshot).GetAwaiter().GetResult();
SetStatus($"Command {receipt.status}: {receipt.commandId} {receipt.message}", MessageType.Info);
}
catch (Exception error)
{
SetStatus(error.Message, MessageType.Error);
}
}
private void PollSyncReceipts(bool quiet)
{
try
{
RequireMirror();
var sawReceipt = false;
while (mirror.TryDequeueSyncReceipt(out var receipt) && receipt != null)
{
lastSyncReceipt = receipt;
sawReceipt = true;
}
if (sawReceipt)
{
Repaint();
return;
}
if (!quiet)
{
SetStatus("No queued Brokkr sync receipt.", MessageType.Info);
}
}
catch (Exception error)
{
if (!quiet)
{
SetStatus(error.Message, MessageType.Error);
}
}
}
private void PublishCreateScriptableObjectCommand()
{
try
@ -453,7 +413,7 @@ namespace GameCult.Brokkr.Editor
? "Assets/BrokkrAsset.asset"
: scriptableObjectAssetPath.Trim()
};
PublishCommandAndPoll(command);
PublishCommand(command);
}
catch (Exception error)
{
@ -480,7 +440,7 @@ namespace GameCult.Brokkr.Editor
name = prefabInstanceName.Trim(),
parentObjectId = selected != null ? BrokkrUnitySnapshotBuilder.GetObjectId(selected) : ""
};
PublishCommandAndPoll(command);
PublishCommand(command);
}
catch (Exception error)
{
@ -508,7 +468,7 @@ namespace GameCult.Brokkr.Editor
? "Assets/BrokkrPrefabVariant.prefab"
: prefabVariantPath.Trim()
};
PublishCommandAndPoll(command);
PublishCommand(command);
}
catch (Exception error)
{
@ -516,10 +476,16 @@ namespace GameCult.Brokkr.Editor
}
}
private void PublishCommandAndPoll(BrokkrUnityCommand command)
// The window writes the intent and stops. The editor service executes it, and only while the operator has
// enabled agent commands for this project.
private void PublishCommand(BrokkrUnityCommand command)
{
mirror.PublishCommandAsync(command).GetAwaiter().GetResult();
PollAndExecuteCommand(true);
Mirror.PublishCommandAsync(command).GetAwaiter().GetResult();
SetStatus(
BrokkrSettings.AgentCommandsEnabled
? $"Published intent {command.commandId}; the editor service will run it."
: $"Published intent {command.commandId}. Agent Commands is off, so nothing will run it.",
MessageType.Info);
}
private void PublishSelectedObjectSync()
@ -551,8 +517,8 @@ namespace GameCult.Brokkr.Editor
updatedAt = now
};
mirror.PublishSyncSessionAsync(session).GetAwaiter().GetResult();
mirror.PublishSyncObjectBindingAsync(binding).GetAwaiter().GetResult();
Mirror.PublishSyncSessionAsync(session).GetAwaiter().GetResult();
Mirror.PublishSyncObjectBindingAsync(binding).GetAwaiter().GetResult();
PublishSyncVar(bindingId, "transform", "Transform", "m_LocalPosition,m_LocalRotation,m_LocalScale", "location,rotationEuler,scale", syncTransform, "linear", now);
PublishSyncVar(bindingId, "parent", "Parent", "parentId", "parentName", syncParent, "step", now);
PublishSyncVar(bindingId, "active-state", "Active State", "m_IsActive", "visible", syncActiveState, "step", now);
@ -611,8 +577,8 @@ namespace GameCult.Brokkr.Editor
updatedAt = now
};
mirror.PublishSyncSessionAsync(session).GetAwaiter().GetResult();
mirror.PublishTimelineBindingAsync(binding).GetAwaiter().GetResult();
Mirror.PublishSyncSessionAsync(session).GetAwaiter().GetResult();
Mirror.PublishTimelineBindingAsync(binding).GetAwaiter().GetResult();
PublishSyncVar(bindingId, "timeline-frame", "Timeline Frame", "Timeline.time", "scene.frame_current", syncTimelineFrame, "linear", now);
PublishSyncVar(bindingId, "cinemachine-virtual-camera", "Cinemachine Camera", "CinemachineVirtualCamera", "camera", syncCinemachineCamera, "linear", now);
SetStatus($"Published Brokkr timeline sync binding: {binding.displayName}", MessageType.Info);
@ -634,7 +600,7 @@ namespace GameCult.Brokkr.Editor
: adHocSyncVarBindingId.Trim();
var session = BuildSyncSession(now);
mirror.PublishSyncSessionAsync(session).GetAwaiter().GetResult();
Mirror.PublishSyncSessionAsync(session).GetAwaiter().GetResult();
PublishSyncVar(
bindingId,
string.IsNullOrWhiteSpace(adHocSyncVarKind) ? "custom-property" : adHocSyncVarKind.Trim(),
@ -694,7 +660,7 @@ namespace GameCult.Brokkr.Editor
interpolation = interpolation,
updatedAt = updatedAt
};
mirror.PublishSyncVarAsync(syncVar).GetAwaiter().GetResult();
Mirror.PublishSyncVarAsync(syncVar).GetAwaiter().GetResult();
}
private static string DefaultAuthorityForKind(string kind)
@ -772,25 +738,19 @@ namespace GameCult.Brokkr.Editor
OnEditorSignal();
}
// Display refresh only. The window executes nothing; BrokkrEditorService owns the drain.
private void OnEditorUpdate()
{
if (mirror != null && mirror.IsRunning)
if (!ReferenceEquals(lastSyncReceipt, BrokkrEditorService.LastSyncReceipt))
{
PollSyncReceipts(true);
lastSyncReceipt = BrokkrEditorService.LastSyncReceipt;
Repaint();
}
if (!autoPollCommands || EditorApplication.timeSinceStartup < nextPollAt)
{
return;
}
nextPollAt = EditorApplication.timeSinceStartup + 1.0;
PollAndExecuteCommand(true);
}
private void RequireMirror()
{
if (mirror == null || !mirror.IsRunning)
if (!Mirror.IsRunning)
{
throw new InvalidOperationException("Start the Brokkr CultMesh mirror first.");
}