Decide "before the enable" by the store, batch the expiry, bound receipts

Soul pass 2 findings S1, S2, S3, S4.

- Enabling the sink is the drain's EnableAsync: every intent already in the
  store gets an "expired" receipt and the enable marker is written, all in one
  flush. No decision compares StoredAt with a clock any more, so a fast
  writer clock and the Rust daemon's secs.nanosZ stamps stop mattering.
- The operator's EditorPrefs hold a token, and the sink runs only while the
  store carries the marker with that token. A re-clone or a copied .brokkr has
  no such marker, so a stale "enabled" authorizes nothing and the editor drops
  it. The epoch and agentCommandsEnabledAt (host snapshot key 19) are gone.
- Selection is one pass over the store per tick (Pending), not a copy and sort
  per intent.
- Receipts are capped at the newest 1000, pruned 128 pairs per tick with the
  intent deleted before its receipt.
- A marker that could not be written is withdrawn, so the intent reads as
  never started and is retried, not "interrupted".
- The drain writes through IBrokkrCommandStore; puts stage and one flush makes
  them durable.
- The CLI timeout text no longer says the intent "stays written" without the
  expiry caveat; the check-then-write window on --command-id is documented.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-29 16:56:33 +02:00
commit 9f5e8fbf3c
12 changed files with 476 additions and 173 deletions

View file

@ -107,7 +107,7 @@ internal static class Cli
{
// A command id is single-use, so every invocation is a new act with a new id. --command-id exists for callers
// that need to name their own; one that already has a receipt is refused, because that receipt answered an
// earlier act and would be reported as the answer to this one.
// earlier act and would be reported as the answer to this one. The check and the write are two steps, so two\n // callers naming the same new id in the same instant can still collide; ids are minted, and that is a caller defect.
var named = options.TryGetValue("--command-id", out var commandId) && !string.IsNullOrWhiteSpace(commandId);
if (named)
{
@ -167,7 +167,7 @@ internal static class Cli
if (started)
why = " The editor started this intent and has not recorded a result; it will not run it again.";
throw new TimeoutException(
$"Timed out waiting for Brokkr receipt '{receiptKey.Value}'; the intent stays written.{why}");
$"Timed out waiting for Brokkr receipt '{receiptKey.Value}'; the intent is still in the store: a running editor with the sink on will run it, but if the operator enables the sink after now it expires unrun.{why}");
}
private static BrokkrHostSnapshot? ReadHostSnapshot(CultCache cache) =>

View file

@ -135,7 +135,7 @@ public sealed class BrokkrCommandCliTests
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.AgentCommandsEnabled = false;
editor.DisableSink();
await editor.TickAsync();
var result = await RunAsync("--unity-cache", project.StorePath, "--action", "readHost");
@ -149,7 +149,7 @@ public sealed class BrokkrCommandCliTests
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.AgentCommandsEnabled = false;
editor.DisableSink();
await editor.TickAsync();
editor.Dispose();

View file

@ -1,11 +1,22 @@
using System.Diagnostics;
using GameCult.Brokkr;
using GameCult.Caching;
using Xunit.Abstractions;
namespace Brokkr.Contracts.Tests;
// The rules BrokkrCommandDrain owns, through the same drain the editor service runs, over a real directory store.
public sealed class BrokkrCommandDrainTests
{
// The budgets the flood scenario holds the editor to. Yggdrasil's containers run several jobs at once, so they
// are generous; the point is that they do not scale with the number of stale intents.
private static readonly TimeSpan EnableBudget = TimeSpan.FromSeconds(10);
private static readonly TimeSpan TickBudget = TimeSpan.FromSeconds(3);
private readonly ITestOutputHelper output;
public BrokkrCommandDrainTests(ITestOutputHelper output) => this.output = output;
private static BrokkrUnityCommandReceipt[] Receipts(ScratchProject project)
{
using var audit = project.OpenCache();
@ -16,19 +27,16 @@ public sealed class BrokkrCommandDrainTests
Receipts(project).Single(receipt => receipt.commandId == commandId).status;
[Fact]
public async Task IntentStoredBeforeTheSinkWasEnabledExpiresAndNeverRuns()
public async Task IntentAlreadyInTheStoreWhenTheSinkIsEnabledExpiresAndNeverRuns()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.AgentCommandsEnabled = false;
editor.DisableSink();
await project.WriteCommandAsync("written-while-off");
await editor.TickAsync();
Assert.Empty(editor.Executed);
await Task.Delay(30);
editor.EnabledAt = DateTimeOffset.UtcNow;
editor.AgentCommandsEnabled = true;
await Task.Delay(30);
Assert.Equal(1, await editor.EnableSinkAsync());
await project.WriteCommandAsync("written-after-enable");
await editor.TickAsync();
await editor.TickAsync();
@ -43,23 +51,65 @@ public sealed class BrokkrCommandDrainTests
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.EnabledAt = DateTimeOffset.UtcNow;
await Task.Delay(30);
await project.WriteCommandAsync("ran-while-on");
await editor.TickAsync();
editor.AgentCommandsEnabled = false;
await Task.Delay(30);
editor.DisableSink();
await project.WriteCommandAsync("waited-while-off");
await Task.Delay(30);
editor.EnabledAt = DateTimeOffset.UtcNow;
editor.AgentCommandsEnabled = true;
await editor.EnableSinkAsync();
await editor.TickAsync();
Assert.Equal(new[] { "ran-while-on" }, editor.Executed.Select(command => command.commandId));
Assert.Equal("expired", StatusOf(project, "waited-while-off"));
}
[Fact]
public async Task IntentsWrittenWhileTheEditorWasDownRunOnRestart()
{
// The token survives a restart and so does the marker: what arrives after the enable is fresh.
using var project = new ScratchProject();
using (var first = await EditorProbe.StartAsync(project.StorePath))
await first.TickAsync();
await project.WriteCommandAsync("written-while-down");
using var restarted = await EditorProbe.StartAsync(project.StorePath);
await restarted.TickAsync();
Assert.Equal(new[] { "written-while-down" }, restarted.Executed.Select(command => command.commandId));
}
[Theory]
[InlineData("never-enabled-here")]
[InlineData("enabled-by-someone-else")]
public async Task StoreThisEditorDidNotEnableRunsNothing(string kind)
{
// A re-clone at the same path keeps the old EditorPrefs token; the new clone's store has no marker for it,
// or carries a marker minted elsewhere. Neither is authority.
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath, enabledInStore: kind != "never-enabled-here");
if (kind == "enabled-by-someone-else")
{
using var other = project.OpenCache();
await other.AddAsync(
new BrokkrSinkEnabled { token = "another-editors-token" },
new CultRecordHandle<BrokkrSinkEnabled>(BrokkrCommandLedger.SinkKey));
await other.FlushAsync();
}
await project.WriteCommandAsync("from-the-new-clone");
await editor.TickAsync();
await editor.TickAsync();
Assert.Empty(editor.Executed);
Assert.False(editor.AgentCommandsEnabled, "the editor drops the stale token");
Assert.Empty(Receipts(project));
// The operator's enable is what makes it this editor's store, and it expires what is already there.
Assert.Equal(1, await editor.EnableSinkAsync());
await editor.TickAsync();
Assert.Empty(editor.Executed);
Assert.Equal("expired", StatusOf(project, "from-the-new-clone"));
}
[Fact]
public async Task AttemptReceiptIsDurableBeforeTheExecutorRuns()
{
@ -80,8 +130,8 @@ public sealed class BrokkrCommandDrainTests
public async Task CrashDuringExecutionNeverRerunsTheIntentAndReportsItInterrupted()
{
using var project = new ScratchProject();
await project.WriteCommandAsync("crashy");
var firstRun = await EditorProbe.StartAsync(project.StorePath);
await project.WriteCommandAsync("crashy");
firstRun.OnExecute = _ => throw new InvalidOperationException("the editor died");
await Assert.ThrowsAsync<InvalidOperationException>(firstRun.TickAsync);
firstRun.Dispose();
@ -96,12 +146,12 @@ public sealed class BrokkrCommandDrainTests
}
[Fact]
public async Task FailingFinalReceiptWriteNeverRerunsTheIntent()
public async Task FailingFinalReceiptPutNeverRerunsTheIntent()
{
// A receipt write that throws every second must not turn createGameObject into one object per second.
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.FailReceiptWrite = receipt => receipt.status == "accepted";
editor.FailReceiptPut = receipt => receipt.status == "accepted";
await project.WriteCommandAsync("unlucky");
await Assert.ThrowsAsync<IOException>(editor.TickAsync);
@ -111,33 +161,64 @@ public sealed class BrokkrCommandDrainTests
}
Assert.Single(editor.Executed);
editor.FailReceiptWrite = null;
editor.FailReceiptPut = null;
await editor.TickAsync();
Assert.Single(editor.Executed);
Assert.Equal("interrupted", StatusOf(project, "unlucky"));
}
[Fact]
public async Task FailingAttemptWriteExecutesNothing()
public async Task FailingFinalFlushNeverRerunsTheIntentEvenAfterARestart()
{
using var project = new ScratchProject();
var editor = await EditorProbe.StartAsync(project.StorePath);
await project.WriteCommandAsync("unlucky");
var flushes = 0;
editor.FailFlush = () => ++flushes == 2; // the marker's flush lands, the verdict's does not
await Assert.ThrowsAsync<IOException>(editor.TickAsync);
Assert.Single(editor.Executed);
editor.Dispose(); // the editor dies here, before anything else could flush the verdict
using var restarted = await EditorProbe.StartAsync(project.StorePath);
for (var tick = 0; tick < 3; tick++)
await restarted.TickAsync();
Assert.Empty(restarted.Executed);
Assert.Equal("interrupted", StatusOf(project, "unlucky"));
}
[Theory]
[InlineData("put")]
[InlineData("flush")]
public async Task IntentWhoseMarkerCouldNotBeWrittenNeverStartedAndIsRetried(string failing)
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
editor.FailReceiptWrite = receipt => receipt.status == "attempted";
await project.WriteCommandAsync("unmarked");
if (failing == "put")
editor.FailReceiptPut = receipt => receipt.status == "attempted";
else
editor.FailFlush = () => true;
await Assert.ThrowsAsync<IOException>(editor.TickAsync);
Assert.Empty(editor.Executed);
editor.FailReceiptPut = null;
editor.FailFlush = null;
await editor.TickAsync();
await editor.TickAsync();
Assert.Single(editor.Executed);
Assert.Equal("accepted", StatusOf(project, "unmarked"));
Assert.DoesNotContain(Receipts(project), receipt => receipt.status == "interrupted");
}
[Fact]
public async Task OneTickHandlesAtMostTheBoundAndTheRestWaits()
public async Task OneTickExecutesAtMostTheBoundAndTheRestWaits()
{
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
var total = BrokkrCommandDrain.MaxPerTick * 2 + 3;
for (var index = 0; index < total; index++)
await project.WriteCommandAsync($"flood-{index}");
await project.WriteCommandsAsync(Enumerable.Range(0, total).Select(index => $"flood-{index}"));
var first = await editor.TickAsync();
@ -149,18 +230,46 @@ public sealed class BrokkrCommandDrainTests
}
[Fact]
public async Task ExpiredIntentsCountTowardTheBoundToo()
public async Task AStaleFloodExpiresInOneFlushAndTheFreshIntentRunsInTheFirstTick()
{
const int stale = 2000;
using var project = new ScratchProject();
using var editor = await EditorProbe.StartAsync(project.StorePath);
for (var index = 0; index < BrokkrCommandDrain.MaxPerTick + 4; index++)
await project.WriteCommandAsync($"stale-{index}");
await Task.Delay(30);
editor.EnabledAt = DateTimeOffset.UtcNow;
editor.DisableSink();
await project.WriteCommandsAsync(Enumerable.Range(0, stale).Select(index => $"stale-{index}"));
Assert.Equal(BrokkrCommandDrain.MaxPerTick, await editor.TickAsync());
Assert.Equal(4, await editor.TickAsync());
Assert.Empty(editor.Executed);
var flushesBefore = editor.Flushes;
var clock = Stopwatch.StartNew();
var expired = await editor.EnableSinkAsync();
var enableTime = clock.Elapsed;
output.WriteLine($"enable: {expired} expired in {enableTime.TotalMilliseconds:F0} ms, {editor.Flushes - flushesBefore} flush(es)");
Assert.Equal(stale, expired);
Assert.Equal(1, editor.Flushes - flushesBefore);
Assert.True(enableTime < EnableBudget, $"enable took {enableTime}");
await project.WriteCommandAsync("fresh");
var slowest = TimeSpan.Zero;
var ticks = 0;
do
{
clock.Restart();
await editor.TickAsync();
slowest = clock.Elapsed > slowest ? clock.Elapsed : slowest;
output.WriteLine($"tick {++ticks}: {clock.Elapsed.TotalMilliseconds:F0} ms, receipts kept {Receipts(project).Length}");
if (ticks == 1)
Assert.Equal(new[] { "fresh" }, editor.Executed.Select(command => command.commandId));
}
while (Receipts(project).Length > BrokkrCommandDrain.RetainedReceipts && ticks < 40);
Assert.True(slowest < TickBudget, $"slowest tick took {slowest}");
Assert.Equal(new[] { "fresh" }, editor.Executed.Select(command => command.commandId));
Assert.Equal("accepted", StatusOf(project, "fresh"));
// Receipts are bounded, and an intent goes with its receipt: nothing is left to run again.
using var audit = project.OpenCache();
var documents = audit.AllStoredDocuments.Select(entry => entry.Document).ToArray();
Assert.Equal(BrokkrCommandDrain.RetainedReceipts, documents.OfType<BrokkrUnityCommandReceipt>().Count());
Assert.Equal(BrokkrCommandDrain.RetainedReceipts, documents.OfType<BrokkrUnityCommand>().Count());
Assert.False(new BrokkrCommandLedger(audit).TryNextPending(out _));
}
[Fact]

View file

@ -10,8 +10,8 @@ namespace Brokkr.Contracts.Tests;
// node with StartServer=false over a directory store and durable shard logs) and runs one service tick in the
// service order: pull, drain pending intents through BrokkrCommandDrain (the same class the service uses), host
// snapshot, soft flush. "Executing" an intent only records it, so the scenarios measure delivery and once-only
// execution, not Unity.
internal sealed class EditorProbe : IDisposable
// execution, not Unity. It is also the drain's IBrokkrCommandStore, with knobs to make the store fail.
internal sealed class EditorProbe : IDisposable, IBrokkrCommandStore
{
private readonly CultMeshNode node;
private readonly BrokkrCommandLedger ledger;
@ -25,17 +25,21 @@ internal sealed class EditorProbe : IDisposable
// What the "editor" answers with. Real Unity answers accepted or failed per the executor.
internal Func<BrokkrUnityCommand, string> StatusFor { get; set; } = _ => "accepted";
// What the host snapshot says about the sink; the real editor reports the operator's toggle.
internal bool AgentCommandsEnabled { get; set; } = true;
// The token the operator's enable left in EditorPrefs; null while the sink is off. A probe starts with the sink
// enabled, as an editor whose operator enabled it earlier and whose store already carries the marker.
internal string? SinkToken { get; private set; } = "probe-token";
// When the operator last enabled the sink; intents stored earlier expire.
internal DateTimeOffset EnabledAt { get; set; } = DateTimeOffset.MinValue;
internal bool AgentCommandsEnabled => SinkToken != null;
// Runs inside the "executor", after the intent is recorded.
internal Action<BrokkrUnityCommand>? OnExecute { get; set; }
// Makes a receipt write throw, as a full disk or a lease timeout would.
internal Func<BrokkrUnityCommandReceipt, bool>? FailReceiptWrite { get; set; }
// Makes a receipt put or a flush throw, as a full disk or a lease timeout would.
internal Func<BrokkrUnityCommandReceipt, bool>? FailReceiptPut { get; set; }
internal Func<bool>? FailFlush { get; set; }
// Flushes the drain asked for; each is an fsync in the real store.
internal int Flushes { get; private set; }
private EditorProbe(CultMeshNode node)
{
@ -43,7 +47,7 @@ internal sealed class EditorProbe : IDisposable
ledger = new BrokkrCommandLedger(node.Cache);
}
internal static async Task<EditorProbe> StartAsync(string cachePath)
// enabledInStore false is an editor whose EditorPrefs still hold a token, opening a store that never saw that\n // enable: a re-clone, or a copied .brokkr.\n internal static async Task<EditorProbe> StartAsync(string cachePath, bool enabledInStore = true)
{
Directory.CreateDirectory(Path.GetDirectoryName(cachePath)!);
var node = await CultMesh.CreateNodeAsync(cachePath, new CultMeshNodeOptions
@ -53,39 +57,57 @@ internal sealed class EditorProbe : IDisposable
EnableDurableShardLogs = true,
DatabaseOptions = new CultNetDatabaseOptions { RuntimeId = "brokkr-unity-editor" }
});
return new EditorProbe(node);
var probe = new EditorProbe(node);
// A restart with the token persisted finds its marker; a first start is the operator's enable.
if (enabledInStore && !probe.ledger.SinkAuthorized(probe.SinkToken))
await NewDrain(probe).EnableAsync(probe.SinkToken!);
return probe;
}
// Returns how many intents the drain answered.
private static BrokkrCommandDrain NewDrain(EditorProbe probe) =>
new(
probe.ledger,
probe.policy,
command =>
{
probe.Executed.Add(command);
probe.OnExecute?.Invoke(command);
return new BrokkrUnityCommandReceipt
{
commandId = command.commandId,
status = probe.StatusFor(command),
message = "probe",
observedAt = DateTime.UtcNow.ToString("O")
};
},
probe);
// The operator ticks the toggle off.
internal void DisableSink() => SinkToken = null;
// The operator ticks it on: a new token, every waiting intent expired, one flush. Returns how many expired.
internal async Task<int> EnableSinkAsync()
{
await ledger.PullAsync();
var token = Guid.NewGuid().ToString("N");
var expired = await NewDrain(this).EnableAsync(token);
SinkToken = token;
return expired;
}
// Returns how many intents the drain answered (0 with the sink off).
internal async Task<int> TickAsync()
{
await ledger.PullAsync();
var handled = 0;
if (AgentCommandsEnabled)
if (SinkToken != null)
{
await ledger.PullAsync();
var drain = new BrokkrCommandDrain(
ledger,
policy,
command =>
{
Executed.Add(command);
OnExecute?.Invoke(command);
return new BrokkrUnityCommandReceipt
{
commandId = command.commandId,
status = StatusFor(command),
message = "probe",
observedAt = DateTime.UtcNow.ToString("O")
};
},
async receipt =>
{
if (FailReceiptWrite?.Invoke(receipt) == true)
throw new IOException("receipt write failed");
await node.Database.PutAsync(BrokkrCommandLedger.ReceiptKey(receipt.commandId), receipt);
await node.FlushAsync(soft: true);
});
handled = await drain.DrainAsync(EnabledAt);
handled = await NewDrain(this).DrainAsync(SinkToken);
if (handled == BrokkrCommandDrain.NotAuthorized)
{
SinkToken = null;
handled = 0;
}
}
await node.Database.PutAsync(
@ -94,12 +116,35 @@ internal sealed class EditorProbe : IDisposable
{
observedAt = DateTime.UtcNow.ToString("O"),
projectPath = "probe",
agentCommandsEnabled = AgentCommandsEnabled,
agentCommandsEnabledAt = AgentCommandsEnabled ? EnabledAt.ToString("O") : ""
agentCommandsEnabled = AgentCommandsEnabled
});
await node.FlushAsync(soft: true);
return handled;
}
public Task PutReceiptAsync(BrokkrUnityCommandReceipt receipt)
{
if (FailReceiptPut?.Invoke(receipt) == true)
throw new IOException("receipt write failed");
return node.Database.PutAsync(BrokkrCommandLedger.ReceiptKey(receipt.commandId), receipt);
}
public Task PutSinkEnabledAsync(BrokkrSinkEnabled marker) => node.Database.PutAsync(BrokkrCommandLedger.SinkKey, marker);
public Task DeleteIntentAsync(string commandId) =>
node.Database.DeleteAsync<BrokkrUnityCommand>(BrokkrCommandLedger.CommandKey(commandId));
public Task DeleteReceiptAsync(string commandId) =>
node.Database.DeleteAsync<BrokkrUnityCommandReceipt>(BrokkrCommandLedger.ReceiptKey(commandId));
public Task FlushAsync()
{
if (FailFlush?.Invoke() == true)
throw new IOException("flush failed");
Flushes++;
return node.FlushAsync(soft: true);
}
public void Dispose() => node.Dispose();
}
@ -120,6 +165,17 @@ internal sealed class ScratchProject : IDisposable
await writer.FlushAsync();
}
// Many intents in one open and one flush, for the flood scenarios.
internal async Task WriteCommandsAsync(IEnumerable<string> commandIds, string action = "refreshAssets")
{
using var writer = OpenCache();
foreach (var commandId in commandIds)
await writer.AddAsync(
new BrokkrUnityCommand { commandId = commandId, action = action },
new CultRecordHandle<BrokkrUnityCommand>(BrokkrCommandLedger.CommandKey(commandId)));
await writer.FlushAsync();
}
internal CultCache OpenCache()
{
Directory.CreateDirectory(Path.GetDirectoryName(StorePath)!);

View file

@ -12,8 +12,9 @@ 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
// publishes through it and never opens the store itself. It is also the drain's IBrokkrCommandStore: puts and
// deletes stage, and FlushAsync is the only fsync.
internal sealed class BrokkrCultMeshMirror : IDisposable, IBrokkrCommandStore
{
private readonly Queue<BrokkrSyncReceipt> syncReceiptQueue = new();
private CultMeshNode node;
@ -75,7 +76,7 @@ namespace GameCult.Brokkr.Editor
}
// The receipt is the only proof an intent ran, and it is keyed by the intent it answers.
internal async Task PublishReceiptAsync(BrokkrUnityCommandReceipt receipt)
public Task PutReceiptAsync(BrokkrUnityCommandReceipt receipt)
{
RequireRunning();
if (string.IsNullOrWhiteSpace(receipt.commandId))
@ -83,10 +84,32 @@ namespace GameCult.Brokkr.Editor
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);
return node.Database.PutAsync(BrokkrCommandLedger.ReceiptKey(receipt.commandId), receipt);
}
public Task PutSinkEnabledAsync(BrokkrSinkEnabled marker)
{
RequireRunning();
return node.Database.PutAsync(BrokkrCommandLedger.SinkKey, marker);
}
public Task DeleteIntentAsync(string commandId)
{
RequireRunning();
return node.Database.DeleteAsync<BrokkrUnityCommand>(BrokkrCommandLedger.CommandKey(commandId));
}
public Task DeleteReceiptAsync(string commandId)
{
RequireRunning();
return node.Database.DeleteAsync<BrokkrUnityCommandReceipt>(BrokkrCommandLedger.ReceiptKey(commandId));
}
public Task FlushAsync()
{
RequireRunning();
return 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)
{

View file

@ -61,12 +61,28 @@ namespace GameCult.Brokkr.Editor
}
}
// The operator's toggle. Enabling expires every intent already in the store and writes the enable marker in
// one flush (BrokkrCommandDrain.EnableAsync); only then does the editor remember the token, so a failure
// leaves the sink off.
internal static async Task SetAgentCommandsEnabledAsync(bool enabled)
{
BrokkrSettings.AgentCommandsEnabled = enabled;
if (enabled)
{
await StartAsync();
if (!MirrorInstance.IsRunning)
{
throw new InvalidOperationException("The Brokkr mirror did not start; the sink stays off.");
}
await MirrorInstance.PullExternalUpdatesAsync();
var token = Guid.NewGuid().ToString("N");
var expired = await NewDrain().EnableAsync(token);
BrokkrSettings.EnableAgentCommands(token);
Debug.Log($"Brokkr command sink enabled; {expired} waiting intent(s) expired unrun.");
}
else
{
BrokkrSettings.DisableAgentCommands();
}
// The snapshot carries the flag, so a caller can see why nothing executes.
@ -100,8 +116,8 @@ namespace GameCult.Brokkr.Editor
LastSyncReceipt = syncReceipt;
}
var enabledSince = BrokkrSettings.AgentCommandsEnabledSince;
if (enabledSince == null || EditorApplication.timeSinceStartup < nextPullAt)
var token = BrokkrSettings.AgentCommandsToken;
if (token.Length == 0 || EditorApplication.timeSinceStartup < nextPullAt)
{
return;
}
@ -110,7 +126,20 @@ namespace GameCult.Brokkr.Editor
try
{
MirrorInstance.PullExternalUpdatesAsync().GetAwaiter().GetResult();
DrainCommands(enabledSince.Value);
var handled = NewDrain().DrainAsync(token).GetAwaiter().GetResult();
if (handled == BrokkrCommandDrain.NotAuthorized)
{
// The store in front of us was not enabled by this editor (re-clone, copied .brokkr, replaced
// store). The stale token authorizes nothing: drop it and make the operator enable again.
BrokkrSettings.DisableAgentCommands();
Debug.LogWarning("Brokkr command sink turned off: this project's store carries no enable marker "
+ "from this editor. Enable Agent Commands again to run intents from it.");
PublishSnapshotAsync().GetAwaiter().GetResult();
}
else if (handled > 0)
{
PublishSnapshotAsync().GetAwaiter().GetResult();
}
}
catch (Exception error)
{
@ -119,19 +148,15 @@ namespace GameCult.Brokkr.Editor
}
// Every rule about whether and when an intent runs lives in BrokkrCommandDrain; this only supplies the
// executor and the receipt writer.
private static void DrainCommands(DateTimeOffset enabledSince)
// executor and the store.
private static BrokkrCommandDrain NewDrain()
{
var projectRoot = Directory.GetParent(Application.dataPath)?.FullName ?? Application.dataPath;
var drain = new BrokkrCommandDrain(
return new BrokkrCommandDrain(
MirrorInstance.Ledger,
new BrokkrCommandPolicy(projectRoot, BrokkrSettings.AllowedAgentActions),
BrokkrUnityCommandExecutor.Execute,
MirrorInstance.PublishReceiptAsync);
if (drain.DrainAsync(enabledSince).GetAwaiter().GetResult() > 0)
{
PublishSnapshotAsync().GetAwaiter().GetResult();
}
MirrorInstance);
}
}
}

View file

@ -1,5 +1,3 @@
using System;
using System.Globalization;
using System.Linq;
using UnityEditor;
using UnityEngine;
@ -25,45 +23,19 @@ namespace GameCult.Brokkr.Editor
}
// 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.
// Turning it on stamps the enable epoch; intents stored before that instant never run (BrokkrCommandDrain).
internal static bool AgentCommandsEnabled
{
get => EditorPrefs.GetBool(ProjectKey("AgentCommandsEnabled"), false);
set
{
if (value && !AgentCommandsEnabled)
{
EditorPrefs.SetString(ProjectKey("AgentCommandsEnabledAt"), DateTimeOffset.UtcNow.ToString("O"));
}
// EditorPrefs is shared by every project on the machine, so the flag keys on the project.
//
// What is stored is a token minted at enable time. The same token is written into the project's store as the
// enable marker (BrokkrSinkEnabled); the sink runs only while the store still carries it. A re-clone or a
// copied .brokkr has no such marker, so an old "enabled" left in EditorPrefs authorizes nothing.
internal static string AgentCommandsToken => EditorPrefs.GetString(ProjectKey("AgentCommandsToken"), "");
EditorPrefs.SetBool(ProjectKey("AgentCommandsEnabled"), value);
}
}
internal static bool AgentCommandsEnabled => AgentCommandsToken.Length > 0;
// The enable epoch: null while the sink is off. A sink enabled before the epoch was recorded is stamped now,
// so intents already waiting expire rather than run.
internal static DateTimeOffset? AgentCommandsEnabledSince
{
get
{
if (!AgentCommandsEnabled)
{
return null;
}
internal static void EnableAgentCommands(string token) =>
EditorPrefs.SetString(ProjectKey("AgentCommandsToken"), token);
var key = ProjectKey("AgentCommandsEnabledAt");
if (DateTimeOffset.TryParse(EditorPrefs.GetString(key, ""), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var since))
{
return since;
}
since = DateTimeOffset.UtcNow;
EditorPrefs.SetString(key, since.ToString("O"));
return since;
}
}
internal static void DisableAgentCommands() => EditorPrefs.DeleteKey(ProjectKey("AgentCommandsToken"));
private static string ProjectKey(string name) => $"GameCult.Brokkr.{name}.{Application.dataPath}";

View file

@ -45,7 +45,6 @@ namespace GameCult.Brokkr.Editor
.ToArray(),
assetCount = AssetDatabase.GetAllAssetPaths().Length,
agentCommandsEnabled = BrokkrSettings.AgentCommandsEnabled,
agentCommandsEnabledAt = BrokkrSettings.AgentCommandsEnabledSince?.ToString("O") ?? "",
isPlaying = EditorApplication.isPlaying,
isPaused = EditorApplication.isPaused,
isCompiling = EditorApplication.isCompiling,

View file

@ -128,7 +128,7 @@ namespace GameCult.Brokkr.Editor
"Command Sink",
BrokkrSettings.AgentCommandsEnabled
? (Mirror.IsRunning ? $"executing intents from {Mirror.CachePath}" : "enabled, mirror not running")
: "off: no intent written into .brokkr will run");
: "off: enabling it expires every intent already waiting in .brokkr");
allowedAgentActions = EditorGUILayout.TextField("Allowed Actions", allowedAgentActions);
if (GUILayout.Button("Save Settings"))

View file

@ -1,27 +1,52 @@
#nullable disable
using System;
using System.Globalization;
using System.Threading.Tasks;
namespace GameCult.Brokkr
{
// What the drain writes through. BrokkrCultMeshMirror is the editor's implementation and the scenario harness
// has its own; puts and deletes only stage, and FlushAsync makes them durable (an fsync, so batches share one).
public interface IBrokkrCommandStore
{
Task PutReceiptAsync(BrokkrUnityCommandReceipt receipt);
Task PutSinkEnabledAsync(BrokkrSinkEnabled marker);
Task DeleteIntentAsync(string commandId);
Task DeleteReceiptAsync(string commandId);
Task FlushAsync();
}
// The one decision path from a pending intent to a receipt. BrokkrEditorService supplies the executor and the
// receipt writer; the scenario harness supplies fakes. Nothing else may run an intent.
// store; the scenario harness supplies fakes. Nothing else may run an intent.
//
// Whether an intent may run is decided by what the store holds, never by comparing clocks:
// * EnableAsync is the operator's act. It answers every intent already in the store with "expired" and writes
// a BrokkrSinkEnabled marker carrying a fresh token, all in one flush. The token also lives in the
// editor's own EditorPrefs, so a store this editor did not enable (a re-clone, a copied .brokkr) carries no
// matching marker and DrainAsync refuses to run anything from it.
// * Anything that arrives after the marker is fresh, whatever its writer's clock says.
//
// Every intent leaves exactly one of these receipts, and any receipt retires its id (BrokkrCommandLedger):
// expired stored before the sink was last enabled; the operator never saw it, so it never runs
// expired in the store when the operator enabled the sink; never runs
// denied admission refused it
// attempted written and flushed BEFORE execution; it stays only if the editor died or the final receipt
// could not be written, and the next drain rewrites it as interrupted
// interrupted an attempt that did not finish; it is never run again automatically, the operator decides
// accepted / failed / ... the executor's verdict
// A receipt write that fails therefore cannot make an intent run twice: at worst the marker is the answer.
// A marker that could not be flushed is withdrawn, so an intent that never started is retried, not reported
// as interrupted.
public sealed class BrokkrCommandDrain
{
// The most intents one drain handles, receipts of every kind included. A flood cannot hold the editor's
// update loop; the remainder waits for the next tick.
// The most intents one drain executes or denies. A flood cannot hold the editor's update loop.
public const int MaxPerTick = 16;
// Answered intents keep their receipt (the CLI reads its own) until this many newer receipts exist; then the
// oldest command and receipt are deleted together, at most MaxPrunedPerTick pairs per drain. A caller
// waiting for a receipt would need this many newer answers inside its wait to lose it.
public const int RetainedReceipts = 1000;
public const int MaxPrunedPerTick = 128;
public const int NotAuthorized = -1;
public const string AttemptedStatus = "attempted";
public const string InterruptedStatus = "interrupted";
public const string ExpiredStatus = "expired";
@ -29,65 +54,122 @@ namespace GameCult.Brokkr
private readonly BrokkrCommandLedger ledger;
private readonly BrokkrCommandPolicy policy;
private readonly Func<BrokkrUnityCommand, BrokkrUnityCommandReceipt> execute;
private readonly Func<BrokkrUnityCommandReceipt, Task> publishReceipt;
private readonly IBrokkrCommandStore store;
public BrokkrCommandDrain(
BrokkrCommandLedger ledger,
BrokkrCommandPolicy policy,
Func<BrokkrUnityCommand, BrokkrUnityCommandReceipt> execute,
Func<BrokkrUnityCommandReceipt, Task> publishReceipt)
IBrokkrCommandStore store)
{
this.ledger = ledger ?? throw new ArgumentNullException(nameof(ledger));
this.policy = policy ?? throw new ArgumentNullException(nameof(policy));
this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
this.publishReceipt = publishReceipt ?? throw new ArgumentNullException(nameof(publishReceipt));
this.store = store ?? throw new ArgumentNullException(nameof(store));
}
// sinkEnabledAt is when the operator last turned the sink on. Returns how many intents it answered.
public async Task<int> DrainAsync(DateTimeOffset sinkEnabledAt)
// The operator turned the sink on. Returns how many waiting intents it expired. The caller keeps the token
// and passes it to every DrainAsync; nothing runs before this returns.
public async Task<int> EnableAsync(string token)
{
if (string.IsNullOrWhiteSpace(token))
{
throw new ArgumentException("A sink token is required.", nameof(token));
}
var waiting = ledger.Pending(int.MaxValue);
foreach (var command in waiting)
{
await store.PutReceiptAsync(Receipt(command, ExpiredStatus,
"This intent was already in the store when the operator enabled the command sink, so the "
+ "operator never saw it. It was not run."));
}
await store.PutSinkEnabledAsync(new BrokkrSinkEnabled { token = token, enabledAt = DateTime.UtcNow.ToString("O") });
await store.FlushAsync();
return waiting.Length;
}
// Returns how many intents it answered, or NotAuthorized when this store holds no enable marker for the
// token: the caller must treat the sink as off until the operator enables it again.
public async Task<int> DrainAsync(string token)
{
if (!ledger.SinkAuthorized(token))
{
return NotAuthorized;
}
// Nothing is in flight at the start of a drain (execution is synchronous inside it), so an attempted
// receipt found here belongs to a run that never finished.
foreach (var attempt in ledger.AttemptedReceipts())
var interrupted = ledger.AttemptedReceipts();
foreach (var attempt in interrupted)
{
await publishReceipt(Receipt(attempt.commandId, attempt.requestedBy, InterruptedStatus,
await store.PutReceiptAsync(Receipt(attempt.commandId, attempt.requestedBy, InterruptedStatus,
"The editor stopped, or could not record the result, after starting this intent. It was not run "
+ "again. Check the project, then send a new intent if it should run."));
}
if (interrupted.Length > 0)
{
await store.FlushAsync();
}
var handled = 0;
while (handled < MaxPerTick && ledger.TryNextPending(out var command, out var storedAt))
foreach (var command in ledger.Pending(MaxPerTick))
{
handled++;
if (!DateTimeOffset.TryParse(storedAt, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var stored)
|| stored < sinkEnabledAt)
{
await publishReceipt(Receipt(command, ExpiredStatus,
"This intent was stored before the command sink was last enabled, so the operator never saw "
+ "it. It was not run."));
continue;
}
var admission = policy.Decide(command);
if (!admission.Allowed)
{
var denied = admission.DeniedReceipt(command);
denied.requestedBy = command.requestedBy;
await publishReceipt(denied);
await store.PutReceiptAsync(denied);
await store.FlushAsync();
continue;
}
// Durable before any effect: a crash after this line leaves the marker, never a second run.
await publishReceipt(Receipt(command, AttemptedStatus, "Started; no result recorded yet."));
await MarkAttemptedAsync(command);
var receipt = execute(command);
receipt.commandId = command.commandId;
receipt.requestedBy = command.requestedBy;
await publishReceipt(receipt);
await store.PutReceiptAsync(receipt);
await store.FlushAsync();
}
var pruned = ledger.Prunable(RetainedReceipts, MaxPrunedPerTick);
foreach (var commandId in pruned)
{
// The intent goes first: a receipt without its intent is harmless, an intent without its receipt
// would run again.
await store.DeleteIntentAsync(commandId);
await store.DeleteReceiptAsync(commandId);
}
if (pruned.Length > 0)
{
await store.FlushAsync();
}
return handled;
}
private async Task MarkAttemptedAsync(BrokkrUnityCommand command)
{
try
{
await store.PutReceiptAsync(Receipt(command, AttemptedStatus, "Started; no result recorded yet."));
await store.FlushAsync();
}
catch
{
// Nothing has run. Withdraw the marker so this reads as never started and is retried; if the store
// will not even do that, the leftover marker is reported as interrupted, which errs safe.
try { await store.DeleteReceiptAsync(command.commandId); } catch { }
throw;
}
}
private static BrokkrUnityCommandReceipt Receipt(BrokkrUnityCommand command, string status, string message) =>
Receipt(command.commandId, command.requestedBy, status, message);

View file

@ -26,14 +26,22 @@ namespace GameCult.Brokkr
public static CultRecordKey ReceiptKey(string commandId) => new CultRecordKey(ReceiptKeyPrefix + commandId);
public static readonly CultRecordKey SinkKey = new CultRecordKey("unity/sink/enabled");
// Loads writes that other processes have landed in the backing store.
public Task PullAsync() => cache.PullAllBackingStoresAsync();
// The oldest unanswered intent by stored-at. Exact ties keep the cache's own order (schema, then key): the sort is stable.
public bool TryNextPending(out BrokkrUnityCommand command) => TryNextPending(out command, out _);
public bool TryNextPending(out BrokkrUnityCommand command)
{
var next = Pending(1);
command = next.Length > 0 ? next[0] : null;
return command != null;
}
// storedAt is the cache's own stamp for the intent (round-trip ISO 8601), minted when the writer stored it.
public bool TryNextPending(out BrokkrUnityCommand command, out string storedAt)
// Up to max unanswered intents, oldest first, from one pass over the store. Stored-at only orders them; no
// decision anywhere compares it with a clock.
public BrokkrUnityCommand[] Pending(int max)
{
var stored = cache.AllStoredDocuments.ToArray();
var answered = new HashSet<string>(
@ -42,19 +50,22 @@ namespace GameCult.Brokkr
.Where(id => !string.IsNullOrWhiteSpace(id)),
StringComparer.Ordinal);
var next = stored
return stored
.Where(entry => entry.Document is BrokkrUnityCommand)
.OrderBy(entry => entry.StoredAt, StringComparer.Ordinal)
.FirstOrDefault(entry =>
{
var candidate = (BrokkrUnityCommand)entry.Document;
return !string.IsNullOrWhiteSpace(candidate.commandId) && !answered.Contains(candidate.commandId);
});
command = next?.Document as BrokkrUnityCommand;
storedAt = next?.StoredAt;
return command != null;
.Select(entry => (BrokkrUnityCommand)entry.Document)
.Where(candidate => !string.IsNullOrWhiteSpace(candidate.commandId) && !answered.Contains(candidate.commandId))
.Take(max)
.ToArray();
}
// True when the store holds the enable marker for this token (see BrokkrCommandDrain).
public bool SinkAuthorized(string token) =>
!string.IsNullOrWhiteSpace(token)
&& cache.TryGet(SinkKey, out BrokkrSinkEnabled marker)
&& marker != null
&& string.Equals(marker.token, token, StringComparison.Ordinal);
// Receipts that say an intent was started and never finished (see BrokkrCommandDrain).
public BrokkrUnityCommandReceipt[] AttemptedReceipts() =>
cache.AllStoredDocuments
@ -63,5 +74,20 @@ namespace GameCult.Brokkr
.Where(receipt => string.Equals(receipt.status, BrokkrCommandDrain.AttemptedStatus, StringComparison.Ordinal)
&& !string.IsNullOrWhiteSpace(receipt.commandId))
.ToArray();
// The ids of the oldest answered intents beyond the newest keep receipts, at most max. Receipts are ordered by
// their own stored-at, all minted by the editor, so one clock orders them. An attempt in flight is never listed.
public string[] Prunable(int keep, int max)
{
var receipts = cache.AllStoredDocuments
.Where(entry => entry.Document is BrokkrUnityCommandReceipt receipt
&& !string.IsNullOrWhiteSpace(receipt.commandId)
&& !string.Equals(receipt.status, BrokkrCommandDrain.AttemptedStatus, StringComparison.Ordinal))
.OrderBy(entry => entry.StoredAt, StringComparer.Ordinal)
.Select(entry => ((BrokkrUnityCommandReceipt)entry.Document).commandId)
.ToArray();
var excess = receipts.Length - keep;
return excess <= 0 ? Array.Empty<string>() : receipts.Take(Math.Min(excess, max)).ToArray();
}
}
}

View file

@ -29,9 +29,20 @@ namespace GameCult.Brokkr
[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;
// When the operator last enabled the sink (round-trip ISO 8601), empty while it is off. Intents stored before
// this instant expire instead of running (BrokkrCommandDrain).
[Key(19)] public string agentCommandsEnabledAt = "";
}
// Written by the editor, into the store, when the operator enables the command sink. The token is also kept in
// the editor's own EditorPrefs; a store whose marker does not carry that token was not enabled by this editor,
// so nothing in it runs (BrokkrCommandDrain). A caller that can only write intents cannot forge it.
[CultDocument("brokkr.unity.sink_enabled", "brokkr.unity.sink_enabled.v0")]
[MessagePackObject]
[Serializable]
public sealed class BrokkrSinkEnabled
{
[Key(0)] public string schema = "gamecult.brokkr.sink_enabled.v0";
[Key(1)] public string token = "";
// Informational only; no decision reads it.
[Key(2)] public string enabledAt = "";
}
[CultDocument("brokkr.unity.snapshot_receipt", "brokkr.unity.snapshot_receipt.v0")]