feat(01-04): observe accepted input with bounded passive output

This commit is contained in:
UnixNight committed 2026-11-12 23:09:01 -05:00
1 parent 773c228a30
commit 72523eebb7
2 files changed
+184 -3

No files matched your search

@@ -0,0 +1,174 @@
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using GamePort.Game;
namespace GamePort.Application;
/// <summary>Optional application diagnostics. Owns only copied observations and output;
/// it never owns a simulation, callback, input source or continuation payload.</summary>
internal sealed class FidelityObservation : IDisposable
{
private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
private readonly Stopwatch clock = Stopwatch.StartNew();
private readonly string directory, session, caseId, kind;
private readonly DateTimeOffset wallStart = DateTimeOffset.UtcNow;
private readonly int maxRecords;
private const long MaxBytes = 512L * 1024 * 1024;
private TextWriter? writer;
private long sequence, bytes;
private string? failure;
private bool completed, disposed, ownsDirectory;
private double overhead;
private FidelityObservation(string directory, string session, string caseId, string kind, int maxRecords)
{ this.directory = directory; this.session = session; this.caseId = caseId; this.kind = kind; this.maxRecords = maxRecords; }
public static FidelityObservation? FromArguments(string[] args, string project, string originals)
{
string? Option(string name)
{
var index = Array.IndexOf(args, name);
if (index < 0) return null;
if (index + 1 == args.Length || args[index + 1].StartsWith("--", StringComparison.Ordinal))
throw new ArgumentException(name + " requires a value");
if (Array.LastIndexOf(args, name) != index) throw new ArgumentException("Repeated " + name);
return args[index + 1];
}
var output = Option("--fidelity-output");
if (output == null) return null;
var session = Option("--fidelity-session") ?? throw new ArgumentException("--fidelity-session required");
var caseId = Option("--fidelity-case") ?? throw new ArgumentException("--fidelity-case required");
var fixture = args.Any(a => a.StartsWith("--smoke-", StringComparison.Ordinal)
|| a is "--headless" or "--story-time" or "--time" or "--inspect" or "--skip-intro"
or "--noclip" or "--debug-menu" or "--debug-page" or "--gadget-menu");
return Create(output, session, caseId, fixture ? "port_fixture" : "native_port", project, originals);
}
public static FidelityObservation Create(string output, string session, string caseId, string kind,
string project, string originals, int maxRecords = 250000, TextWriter? sink = null)
{
foreach (var id in new[] { session, caseId })
if (!Regex.IsMatch(id, "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$", RegexOptions.CultureInvariant))
throw new ArgumentException("Observation IDs require 1..128 safe characters");
if (kind is not ("port_fixture" or "native_port") || maxRecords < 1 || maxRecords > 250000)
throw new ArgumentException("Invalid observation category or record limit");
var path = Path.TrimEndingDirectorySeparator(Path.GetFullPath(output));
static bool Within(string child, string parent) => child.Equals(parent, StringComparison.OrdinalIgnoreCase)
|| child.StartsWith(Path.TrimEndingDirectorySeparator(parent) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
var original = Path.TrimEndingDirectorySeparator(Path.GetFullPath(originals));
var git = Path.Combine(Path.GetFullPath(project), ".git");
if (Within(path, original) || Within(original, path) || Within(path, git) || Within(git, path))
throw new ArgumentException("Observation output must be separate from original assets and Git metadata");
for (var parent = new DirectoryInfo(path); parent != null; parent = parent.Parent)
if (parent.LinkTarget != null) throw new ArgumentException("Observation output cannot traverse symbolic links");
if (Directory.Exists(path) || File.Exists(path)) throw new IOException("Observation requires a new output directory");
var observer = new FidelityObservation(path, session, caseId, kind, maxRecords);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
// A cooperative local reservation prevents two observers reusing the same directory.
var reservation = path + ".fidelity-reservation";
using (new FileStream(reservation, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
if (Directory.Exists(path) || File.Exists(path)) throw new IOException("Observation directory was reserved by another writer");
Directory.CreateDirectory(path);
observer.ownsDirectory = true;
}
File.Delete(reservation);
observer.WriteSummary(false);
observer.writer = sink ?? new StreamWriter(new FileStream(Path.Combine(path, "events.jsonl"),
FileMode.CreateNew, FileAccess.Write, FileShare.Read), new UTF8Encoding(false), 65536);
}
catch (Exception error) when (OutputError(error)) { observer.Fail(error.Message); }
return observer;
}
public void RecordInput(string scene, int simulationTick, PlayerInput requested, bool acceptsInput, string controlOwner)
=> Record("input_step", scene, simulationTick, "post_owner_step", new {
requested_input = requested, accepts_input = acceptsInput,
accepted_input = acceptsInput ? (PlayerInput?)requested : null,
control_owner = controlOwner,
acceptance_scope = "player_binding_input_gate; independent body/fire work is not classified by this boolean" });
private void Record(string name, string scene, int simulationTick, string method, object data)
{
if (disposed || completed || failure != null) return;
var started = Stopwatch.GetTimestamp();
try
{
if (sequence >= maxRecords) throw new IOException("Observation record limit reached");
var line = JsonSerializer.Serialize(new { schema_version = 1, session_id = session, case_id = caseId,
evidence_kind = kind, clock_id = session + ":stopwatch", sequence = sequence + 1,
elapsed_seconds = clock.Elapsed.TotalSeconds, simulation_tick = simulationTick,
name, scene, method, data }, Json);
var length = Encoding.UTF8.GetByteCount(line) + 1;
if (bytes + length > MaxBytes) throw new IOException("Observation byte limit reached");
writer!.WriteLine(line);
sequence++; bytes += length;
}
catch (Exception error) when (OutputError(error)) { Fail(error.Message); }
finally { overhead += Stopwatch.GetElapsedTime(started).TotalSeconds; }
}
public void Complete(int exitCode)
{
if (disposed || completed) return;
if (exitCode != 0) Fail("Port exited with code " + exitCode);
try { writer?.Dispose(); writer = null; }
catch (Exception error) when (OutputError(error)) { Fail(error.Message); }
completed = true;
TrySummary(exitCode == 0 && failure == null);
}
private static bool OutputError(Exception error) => error is IOException or UnauthorizedAccessException
or System.Security.SecurityException or JsonException or ArgumentException or NotSupportedException;
private void Fail(string reason)
{
if (failure != null) return;
failure = reason;
Console.Error.WriteLine("Fidelity observation INCOMPLETE: " + reason);
try { writer?.Dispose(); } catch (Exception error) when (OutputError(error)) { }
writer = null;
TrySummary(false);
}
private void TrySummary(bool success)
{
if (!ownsDirectory) return;
try { WriteSummary(success); }
catch (Exception error) when (OutputError(error))
{ Console.Error.WriteLine("Fidelity observation INCOMPLETE; summary unavailable: " + error.Message); }
}
private void WriteSummary(bool success)
{
var target = Path.Combine(directory, "observation-summary.json");
var temporary = target + "." + Guid.NewGuid().ToString("N") + ".tmp";
var summary = new { schema_version = 1, session_id = session, case_id = caseId, evidence_kind = kind,
clock_id = session + ":stopwatch", wall_start = wallStart, wall_end = DateTimeOffset.UtcNow,
elapsed_seconds = clock.Elapsed.TotalSeconds, records = sequence, bytes, incomplete = !success,
status = success ? "recorded" : "incomplete", failure,
diagnostic = true, observer_seconds = overhead, max_records = maxRecords, max_bytes = MaxBytes,
limitations = new[] { "Diagnostic observer adds serialization, buffered disk writes and state-copy overhead; not a clean audiovisual capture.",
"Observation is not a receipt or an acceptance decision; fixture and native full-route evidence remain distinct.",
"No media clock mapping is inferred. Simulation ticks are scene-local and may reset across continuations.",
"Only named application seams are observed; fixture helper-internal steps are not a complete simulation trace." } };
try
{
using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
JsonSerializer.Serialize(stream, summary, Json);
File.Move(temporary, target, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
public void Dispose()
{
if (disposed) return;
if (!completed) { Fail("Session ended without successful completion"); TrySummary(false); }
disposed = true;
}
}
+10 -3
View File
@@ -15,6 +15,8 @@ internal static class Program
{
try
{
using var observation = args.Contains("--help") || !args.Contains("--fidelity-output") ? null : FidelityObservation.FromArguments(args,
Directory.GetCurrentDirectory(), AssetPath.FindOriginal(Option(args, "--assets")));
using var presentation = new RenderSession();
OriginalSave? carriedSave = null;
PlayerLevelState? carriedPlayer = null;
@@ -24,8 +26,8 @@ internal static class Program
var grapplerMemory = new GrapplerMemory();
while (true)
{
var result = Run(args, carriedSave, carriedPlayer, returning, diagnostics, presentation, energy, grapplerMemory, out var continuation);
if (result != 0 || continuation == null) return result;
var result = Run(args, carriedSave, carriedPlayer, returning, diagnostics, presentation, energy, grapplerMemory, observation, out var continuation);
if (result != 0 || continuation == null) { observation?.Complete(result); return result; }
args = continuation.Args; carriedSave = continuation.Save; returning = continuation.Returning;
carriedPlayer = continuation.Player;
}
@@ -45,7 +47,7 @@ internal static class Program
private sealed record SceneContinuation(string[] Args, OriginalSave Save, bool Returning, PlayerLevelState? Player);
private static int Run(string[] args, OriginalSave? carriedSave, PlayerLevelState? carriedPlayer, bool returning, DebugDiagnostics diagnostics,
RenderSession presentation, PlayerEnergy energy, GrapplerMemory grapplerMemory, out SceneContinuation? continuation)
RenderSession presentation, PlayerEnergy energy, GrapplerMemory grapplerMemory, FidelityObservation? observation, out SceneContinuation? continuation)
{
continuation = null;
if (args.Contains("--help"))
@@ -69,6 +71,9 @@ internal static class Program
--start TAG Use a named original STRT checkpoint
--load-save PATH Resume original TSK task/items/checkpoint state
--write-save PATH Write checkpoint state as TSK outside asset directory
--fidelity-output PATH New local diagnostic session directory
--fidelity-session ID Stable session identity across scene continuations
--fidelity-case ID Declared comparison case; does not establish acceptance
--mute Disable scene audio
--time SECONDS Fixed animation time for comparisons
--headless Render offscreen through Vulkan
@@ -1294,6 +1299,8 @@ internal static class Program
bool acceptsInput;
if (playerBinding != null) acceptsInput = playerBinding.Step(input);
else { simulation.Step(input); acceptsInput = true; }
observation?.RecordInput(level?.Code ?? "preview", simulation.Steps, input, acceptsInput,
director?.ControlledTag ?? (playerBinding == null ? "direct-simulation" : "script"));
scooterFixture?.Received(input);
grapplerFixture?.Received(input);
rocketFixture?.Received(input);