diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 6e242a3..e8f5cba 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -42,6 +42,9 @@ a named invariant that the native runtime cannot protect yet. `LocalcastMoveEvidenceBufferDescriptor` so Muninn Move witnesses can be admitted as compute-upload buffers before Mimir's fusion pass and Fensalir's GPU consumers touch them. +- `MimirNativeReservoirRuntime` is the managed owner for that native runtime + boundary. It pins Move evidence sample/descriptor batches so native reservoir + handles remain valid while Mimir prepares fusion input. - `mimir.move_controller_pose.v1` is Mimir's resolved wand pose contract. Mimir owns calibration, association, triangulation, IMU fusion, prediction, confidence, and latency accounting for those poses before Fensalir consumes diff --git a/docs/perfect-machine-module-library.md b/docs/perfect-machine-module-library.md index a057446..aa14bbb 100644 --- a/docs/perfect-machine-module-library.md +++ b/docs/perfect-machine-module-library.md @@ -14,7 +14,7 @@ job-interview answer for why it belongs in the body of the machine. | Alignment actuator | `Mimir.Runtime` + Faust | Converts sync state into bounded fractional-delay, gain, and sample-rate-offset controls; Faust moves samples. | `src/Mimir.Runtime/Synchronization/MimirAudioAlignmentActuator.cs` | | Audio actuator strategies | `Mimir.Runtime` + Faust | Integer baseline, Farrow fractional delay, variable ASRC, and hybrid delay/ASRC strategy profiles. | `src/Mimir.Runtime/Synchronization/MimirAudioActuatorConfiguration.cs` | | CultMesh contracts | `Mimir.Runtime` | Typed codebook, decoder, acoustic path, actuator, program, Move evidence, and Mimir-fused Move controller pose documents for distributed Mimir nodes. | `src/Mimir.Runtime/Synchronization/MimirCultMeshContracts.cs`, `src/Mimir.Runtime/Synchronization/MimirTrackingObservation.cs` | -| Move controller fusion | `Mimir.Runtime` + native reservoir + Fensalir | Mimir admits Muninn marker candidates plus controller/IMU/button feeds into native `move_evidence` buffers, fuses them into `mimir.move_controller_pose.v1`, and Fensalir consumes the resolved pose stream for interactive environments. | `src/Mimir.Runtime/Synchronization/MimirTrackingObservation.cs`, `native/reservoir/src/lib.rs` | +| Move controller fusion | `Mimir.Runtime` + native reservoir + Fensalir | Mimir admits Muninn marker candidates plus controller/IMU/button feeds into native `move_evidence` buffers, fuses them into `mimir.move_controller_pose.v1`, and Fensalir consumes the resolved pose stream for interactive environments. | `src/Mimir.Runtime/Synchronization/MimirTrackingObservation.cs`, `src/Mimir.Runtime/Synchronization/MimirNativeReservoirRuntime.cs`, `native/reservoir/src/lib.rs` | | Acoustic path learning | `Mimir.Runtime` | Calibration stages for usable bands, confusion, global delay, group delay, and codebook adaptation. | `src/Mimir.Runtime/Synchronization/MimirAcousticPathLearningConfiguration.cs` | | Acoustic localization | `Mimir.Runtime` + Fensalir | Pairwise TDOA, SRP-PHAT grid, sparse source, and visual-constrained localization profiles plus a small SRP/TDOA scorer. | `src/Mimir.Runtime/Synchronization/MimirAcousticLocalizationConfiguration.cs`, `src/Mimir.Runtime/Synchronization/MimirAcousticLocalizationSolver.cs` | | Benchmark panels | `Mimir.Runtime` | Decoder golf and meatspace acceptance degradation panels with receipt roots and thresholds. | `src/Mimir.Runtime/Synchronization/MimirBenchmarkPanelConfiguration.cs` | @@ -62,6 +62,7 @@ dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --perfect-machine-lowering-benchmark dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --perfect-machine-contract-smoke dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --move-tracking-contract-smoke +dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --move-native-reservoir-smoke --native-reservoir .\native\reservoir\target\debug\localcast_reservoir.dll dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --perfect-machine-manifest dotnet run --no-build --project .\src\Mimir.BufferSmoke\Mimir.BufferSmoke.csproj -- --bioacoustic-actuator-self-test ``` diff --git a/src/Mimir.BufferSmoke/Program.cs b/src/Mimir.BufferSmoke/Program.cs index 637aea9..c571a6d 100644 --- a/src/Mimir.BufferSmoke/Program.cs +++ b/src/Mimir.BufferSmoke/Program.cs @@ -96,6 +96,12 @@ if (args.Any(arg => string.Equals(arg, "--move-tracking-contract-smoke", StringC return RunMoveTrackingContractSmoke(); } +if (args.Any(arg => string.Equals(arg, "--move-native-reservoir-smoke", StringComparison.OrdinalIgnoreCase))) +{ + return RunMoveNativeReservoirSmoke( + ParseStringOption(args, "--native-reservoir", DefaultNativeReservoirPath())); +} + if (args.Any(arg => string.Equals(arg, "--import-obs-program-scene", StringComparison.OrdinalIgnoreCase))) { return await ImportObsProgramSceneAsync( @@ -1439,6 +1445,87 @@ static int RunMoveTrackingContractSmoke() : 1; } +static int RunMoveNativeReservoirSmoke(string nativeReservoirPath) +{ + if (!File.Exists(nativeReservoirPath)) + { + Console.Error.WriteLine($"move-native-reservoir-smoke missing-native path={nativeReservoirPath}"); + return 1; + } + + using var runtime = new MimirNativeReservoirRuntime(nativeReservoirPath); + var samples = new[] + { + new MimirNativeMoveEvidenceSample( + WitnessIdHash: 0x57A2_F12E_0001, + ControllerIdHash: 0xC011_7A01, + SourceTimestampNs: 1_000_000_000, + ArrivalNs: 1_000_000_700, + Sequence: 41, + EvidenceKind: (uint)MimirNativeMoveEvidenceKind.OpticalMarker, + Flags: 0, + ImageX: 318.25f, + ImageY: 119.5f, + RadiusPx: 13.75f, + Confidence: 0.91f, + AccelX: 0.0f, + AccelY: 0.0f, + AccelZ: 0.0f, + GyroX: 0.0f, + GyroY: 0.0f, + GyroZ: 0.0f, + Trigger: 0.0f, + ButtonsMask: 0, + Reserved: 0, + Battery01: float.NaN, + Reserved1: 0, + Reserved2: 0), + new MimirNativeMoveEvidenceSample( + WitnessIdHash: 0x516E_7716_0001, + ControllerIdHash: 0xC011_7A01, + SourceTimestampNs: 1_000_000_500, + ArrivalNs: 1_000_001_000, + Sequence: 42, + EvidenceKind: (uint)MimirNativeMoveEvidenceKind.ControllerState, + Flags: 0, + ImageX: float.NaN, + ImageY: float.NaN, + RadiusPx: float.NaN, + Confidence: 0.84f, + AccelX: -0.02f, + AccelY: 0.11f, + AccelZ: 0.98f, + GyroX: 0.01f, + GyroY: -0.02f, + GyroZ: 0.03f, + Trigger: 0.42f, + ButtonsMask: 0b101, + Reserved: 0, + Battery01: 0.77f, + Reserved1: 0, + Reserved2: 0) + }; + + var handle = runtime.AdmitMoveEvidence( + "mimir:move-native-reservoir-smoke", + samples, + "synthetic-move-calibration", + "mimir-stage-space"); + var status = runtime.Status; + + Console.WriteLine( + $"move-native-reservoir-smoke native={nativeReservoirPath} stride={MimirNativeReservoirRuntime.MoveEvidenceSampleStrideBytes} samples={samples.Length} payload=0x{handle.PayloadHandle:X} total={status.TotalSampleCount} moveEvidence={status.MoveEvidenceCount} edgeNs={status.EdgeNs}"); + + return MimirNativeReservoirRuntime.MoveEvidenceSampleStrideBytes == 112 && + samples.Length == 2 && + handle.PayloadHandle != 0 && + status.TotalSampleCount.ToUInt64() == 1 && + status.MoveEvidenceCount.ToUInt64() == 1 && + status.EdgeNs == 1_000_000_500 + ? 0 + : 1; +} + static MoveTrackingSmokeContext BuildMoveTrackingSmokeHub() { var starfireDescriptor = new MimirStreamDescriptor( @@ -1831,6 +1918,27 @@ static string DefaultObsScenePath() => "scenes", "Untitled.json"); +static string DefaultNativeReservoirPath() +{ + var fromBase = Path.Combine(AppContext.BaseDirectory, "localcast_reservoir.dll"); + if (File.Exists(fromBase)) + { + return fromBase; + } + + return Path.GetFullPath(Path.Combine( + AppContext.BaseDirectory, + "..", + "..", + "..", + "..", + "native", + "reservoir", + "target", + "debug", + "localcast_reservoir.dll")); +} + static async Task WritePerfectMachineManifestAsync(string outputPath) { var manifest = MimirPerfectMachineManifestFactory.Create(); diff --git a/src/Mimir.Runtime/Synchronization/MimirNativeReservoirRuntime.cs b/src/Mimir.Runtime/Synchronization/MimirNativeReservoirRuntime.cs new file mode 100644 index 0000000..1684976 --- /dev/null +++ b/src/Mimir.Runtime/Synchronization/MimirNativeReservoirRuntime.cs @@ -0,0 +1,329 @@ +using System.Runtime.InteropServices; +using System.Text; + +namespace Mimir.Runtime.Synchronization; + +public enum MimirNativeReservoirSampleKind : uint +{ + CameraFrame = 0, + CameraFeature = 1, + SceneRay = 2, + SurfaceClaim = 3, + MaterialClaim = 4, + AudioBlock = 5, + PhaseClaim = 6, + EventClaim = 7, + RenderPacket = 8, + MoveEvidence = 9 +} + +public enum MimirNativeMoveEvidenceKind : uint +{ + OpticalMarker = 1, + ControllerState = 2 +} + +[StructLayout(LayoutKind.Sequential)] +public readonly record struct MimirNativeSampleHandle( + ulong SensorIdHash, + ulong TimestampNs, + ulong ArrivalNs, + ulong Sequence, + ulong PayloadHandle, + uint Flags, + uint Reserved); + +[StructLayout(LayoutKind.Sequential)] +public readonly record struct MimirNativeMoveEvidenceSample( + ulong WitnessIdHash, + ulong ControllerIdHash, + ulong SourceTimestampNs, + ulong ArrivalNs, + ulong Sequence, + uint EvidenceKind, + uint Flags, + float ImageX, + float ImageY, + float RadiusPx, + float Confidence, + float AccelX, + float AccelY, + float AccelZ, + float GyroX, + float GyroY, + float GyroZ, + float Trigger, + uint ButtonsMask, + uint Reserved, + float Battery01, + uint Reserved1, + uint Reserved2); + +[StructLayout(LayoutKind.Sequential)] +public readonly record struct MimirNativeMoveEvidenceBufferDescriptor( + ulong SampleBufferHandle, + uint SampleCount, + uint SampleStrideBytes, + ulong SourceTimeMinNs, + ulong SourceTimeMaxNs, + ulong CalibrationHash, + ulong TrackingSpaceHash); + +[StructLayout(LayoutKind.Sequential)] +public readonly record struct MimirNativeRuntimeStatus( + ulong EdgeNs, + ulong WindowStartNs, + UIntPtr TotalSampleCount, + UIntPtr CameraFrameCount, + UIntPtr CameraFeatureCount, + UIntPtr SceneRayCount, + UIntPtr SurfaceClaimCount, + UIntPtr MaterialClaimCount, + UIntPtr AudioBlockCount, + UIntPtr PhaseClaimCount, + UIntPtr EventClaimCount, + UIntPtr RenderPacketCount, + UIntPtr MoveEvidenceCount); + +public sealed unsafe class MimirNativeReservoirRuntime : IDisposable +{ + public const int MoveEvidenceSampleStrideBytes = 112; + + private readonly nint runtime; + private readonly List batches = []; + private bool disposed; + + public MimirNativeReservoirRuntime(string nativeLibraryPath, TimeSpan? window = null) + { + Native.Load(nativeLibraryPath); + runtime = Native.RuntimeCreate((ulong)(window ?? TimeSpan.FromSeconds(5)).TotalNanoseconds()); + if (runtime == 0) + { + throw new InvalidOperationException("Native reservoir runtime creation failed."); + } + } + + public MimirNativeRuntimeStatus Status + { + get + { + ThrowIfDisposed(); + if (!Native.RuntimeStatus(runtime, out var status)) + { + throw new InvalidOperationException("Native reservoir runtime status read failed."); + } + + return status; + } + } + + public MimirNativeSampleHandle AdmitMoveEvidence( + string producerSourceId, + IReadOnlyList samples, + string calibrationId, + string trackingSpaceId) + { + ThrowIfDisposed(); + ArgumentException.ThrowIfNullOrWhiteSpace(producerSourceId); + ArgumentException.ThrowIfNullOrWhiteSpace(calibrationId); + ArgumentException.ThrowIfNullOrWhiteSpace(trackingSpaceId); + if (samples.Count == 0) + { + throw new ArgumentException("Move evidence batch must contain at least one sample.", nameof(samples)); + } + + var producer = Native.ProducerCreateForSource( + MimirNativeReservoirSampleKind.MoveEvidence, + producerSourceId); + if (producer == 0) + { + throw new InvalidOperationException($"Native Move evidence producer creation failed for '{producerSourceId}'."); + } + + try + { + var batch = new PinnedMoveEvidenceBatch(samples, calibrationId, trackingSpaceId); + if (!Native.ProducerPushMoveEvidenceBuffer( + producer, + runtime, + batch.SourceTimeMaxNs, + batch.ArrivalMaxNs, + batch.DescriptorPointer, + out var handle)) + { + batch.Dispose(); + throw new InvalidOperationException("Native Move evidence admission failed."); + } + + batches.Add(batch); + return handle; + } + finally + { + Native.ProducerDestroy(producer); + } + } + + public void Dispose() + { + if (disposed) + { + return; + } + + disposed = true; + foreach (var batch in batches) + { + batch.Dispose(); + } + + batches.Clear(); + Native.RuntimeDestroy(runtime); + } + + private void ThrowIfDisposed() + { + ObjectDisposedException.ThrowIf(disposed, this); + } + + private sealed class PinnedMoveEvidenceBatch : IDisposable + { + private readonly GCHandle samplesHandle; + private readonly GCHandle descriptorHandle; + + public PinnedMoveEvidenceBatch( + IReadOnlyList samples, + string calibrationId, + string trackingSpaceId) + { + var sampleArray = samples.ToArray(); + SourceTimeMaxNs = sampleArray.Max(sample => sample.SourceTimestampNs); + ArrivalMaxNs = sampleArray.Max(sample => sample.ArrivalNs); + samplesHandle = GCHandle.Alloc(sampleArray, GCHandleType.Pinned); + var descriptor = new[] + { + new MimirNativeMoveEvidenceBufferDescriptor( + (ulong)samplesHandle.AddrOfPinnedObject(), + (uint)sampleArray.Length, + MoveEvidenceSampleStrideBytes, + sampleArray.Min(sample => sample.SourceTimestampNs), + SourceTimeMaxNs, + Fnva64(calibrationId), + Fnva64(trackingSpaceId)) + }; + descriptorHandle = GCHandle.Alloc(descriptor, GCHandleType.Pinned); + } + + public ulong SourceTimeMaxNs { get; } + + public ulong ArrivalMaxNs { get; } + + public nint DescriptorPointer => descriptorHandle.AddrOfPinnedObject(); + + public void Dispose() + { + if (descriptorHandle.IsAllocated) + { + descriptorHandle.Free(); + } + + if (samplesHandle.IsAllocated) + { + samplesHandle.Free(); + } + } + } + + private static ulong Fnva64(string value) + { + var bytes = Encoding.UTF8.GetBytes(value); + const ulong offset = 14_695_981_039_346_656_037; + const ulong prime = 1_099_511_628_211; + var hash = offset; + foreach (var b in bytes) + { + hash ^= b; + hash *= prime; + } + + return hash == 0 ? 1 : hash; + } + + private static class Native + { + private static nint library; + private static delegate* unmanaged[Cdecl] runtimeCreate; + private static delegate* unmanaged[Cdecl] runtimeDestroy; + private static delegate* unmanaged[Cdecl] runtimeStatus; + private static delegate* unmanaged[Cdecl] producerCreateForSource; + private static delegate* unmanaged[Cdecl] producerDestroy; + private static delegate* unmanaged[Cdecl] producerPushMoveEvidenceBuffer; + + public static void Load(string path) + { + if (library != 0) + { + return; + } + + if (string.IsNullOrWhiteSpace(path)) + { + path = Path.Combine(AppContext.BaseDirectory, "localcast_reservoir.dll"); + } + + library = NativeLibrary.Load(path); + runtimeCreate = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(library, "localcast_runtime_create"); + runtimeDestroy = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(library, "localcast_runtime_destroy"); + runtimeStatus = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(library, "localcast_runtime_status"); + producerCreateForSource = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(library, "localcast_producer_create_for_source"); + producerDestroy = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(library, "localcast_producer_destroy"); + producerPushMoveEvidenceBuffer = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(library, "localcast_producer_push_move_evidence_buffer"); + } + + public static nint RuntimeCreate(ulong durationNs) => runtimeCreate(durationNs); + + public static void RuntimeDestroy(nint handle) + { + if (handle != 0) + { + runtimeDestroy(handle); + } + } + + public static bool RuntimeStatus(nint handle, out MimirNativeRuntimeStatus status) => + runtimeStatus(handle, out status) != 0; + + public static nint ProducerCreateForSource(MimirNativeReservoirSampleKind kind, string sourceId) + { + var bytes = Encoding.UTF8.GetBytes(sourceId); + fixed (byte* ptr = bytes) + { + return producerCreateForSource((uint)kind, ptr, (nuint)bytes.Length, 0); + } + } + + public static void ProducerDestroy(nint handle) + { + if (handle != 0) + { + producerDestroy(handle); + } + } + + public static bool ProducerPushMoveEvidenceBuffer( + nint producer, + nint runtime, + ulong timestampNs, + ulong arrivalNs, + nint descriptor, + out MimirNativeSampleHandle handle) => + producerPushMoveEvidenceBuffer(producer, runtime, timestampNs, arrivalNs, descriptor, out handle) != 0; + + } +} + +internal static class MimirTimeSpanExtensions +{ + public static long TotalNanoseconds(this TimeSpan value) => + checked((long)(value.TotalSeconds * 1_000_000_000.0)); +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index a7bf42a..0ec30e9 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -131,3 +131,4 @@ {"ts": "2026-06-11T07:57:05+01:00", "type": "decision", "status": "ok", "note": "PS Move structured light ownership moved to Odin/Muninn: Mimir requests muninn.move_light_command.v1 over CultNet/CultMesh; Muninn serve consumes host-addressed pending commands, writes local HID report 0x06, and updates command state. Nightwing direct HID launcher path is opt-in smoke/bootstrap only."} {"ts": "2026-06-11T16:59:31+01:00", "type": "decision", "status": "ok", "note": "Move sensor fusion authority moved to Mimir: Muninn publishes source-local marker candidates and controller/IMU/button state, Odin discovers/projects schemas, Mimir owns calibration, association, triangulation, IMU fusion, prediction, confidence, latency, and mimir.move_controller_pose.v1 for Fensalir interaction."} {"ts": "2026-06-11T18:47:43+01:00", "type": "implementation", "status": "ok", "note": "Added native reservoir Move evidence admission: LocalcastMoveEvidenceSample and LocalcastMoveEvidenceBufferDescriptor define a fixed compute-upload ABI, SampleKind move_evidence enters the shared rolling window, malformed buffers are rejected before live admission, and Mimir docs/maps now route Muninn marker/controller witnesses through native buffers before Mimir pose fusion and Fensalir consumption."} +{"ts": "2026-06-11T19:27:48+01:00", "type": "implementation", "status": "ok", "note": "Connected Mimir.Runtime to the native Move evidence reservoir: MimirNativeReservoirRuntime loads localcast_reservoir, pins Move evidence sample/descriptor batches, admits them through localcast_producer_push_move_evidence_buffer, and BufferSmoke --move-native-reservoir-smoke proves a marker plus controller-state batch enters the native move_evidence view."} diff --git a/state/map.yaml b/state/map.yaml index ef45a67..6f4fc56 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -92,6 +92,8 @@ accepted_design: - `native/reservoir` now exposes a `move_evidence` typed view and `LocalcastMoveEvidenceBufferDescriptor` for compute-upload buffers carrying Muninn optical marker and controller-state witnesses before Mimir fusion. + - `MimirNativeReservoirRuntime` loads the native reservoir DLL and pins Move + evidence sample/descriptor batches so admitted native handles remain valid. - `mimir.move_controller_pose.v1` is Mimir's resolved wand pose contract for Fensalir-facing interaction. Mimir owns calibration, association, triangulation, IMU fusion, prediction, confidence, and latency accounting.