Files
frameledger/tests/FrameLedger.Application.Tests/Capture/CaptureSessionTests.cs
T
poli0981andClaude Opus 5.5 2ce8251d31 feat: the game's own memory, measured from outside the game in every session - a C++ reader of the GPU Process Memory counters and GetProcessMemoryInfo, median and mean, schema 0018 (D43, beta.12 PR-2) (#254)
- FrameLedger.ProcessStats.dll (C++20, loaded by the Agent, never into a game): the game process's dedicated and shared
  GPU memory from the documented `GPU Process Memory` performance counters (no handle to the game, every instance of the
  pid summed) and its private working set / working set / commit from GetProcessMemoryInfo (EX2, falling back to EX)
  through PROCESS_QUERY_LIMITED_INFORMATION only (a sentinel refuses an EX2 answer whose private working set was not
  filled). Not D3DKMTQueryStatistics ("Reserved for system use").
  ctest fl_process_stats (GPU_INSTANCE on a hardware adapter, NO_GPU_INSTANCE on CI) and fl-probe-processstats.
- Measured first, decision table in spike-notes §16 written before the runs: +512.0 MiB for a 512 MiB buffer,
  private working set equal to Windows' own counter, 0.1 ms per read, nothing leaked over 600 reads; dedicated reads a
  constant 4.5 MiB above DXGI's local usage, so it is never compared with a budget.
- NativeProcessStats (third facade), GameMemoryReader: a pinned session reads through its held handle; an unpinned
  Tier-2 hold opens each process of the executable for the read, refuses a reused pid, sums. CaptureSession tells the
  observer which process (ICaptureObserver.Measuring), the recorder forwards it to the poller (ITelemetryPoller.Follow).
- TelemetrySample.Game; five sensor series; schema 0018 (game_vram_dedicated_*, game_ram_private_*, ..., sensor_stats_json);
  SeriesAggregates gains Median and Min; a wide .partial sensors chunk (type 8) with type 4 still read; SessionProgress
  and SessionHeld carry the game's memory live.
- notice-check accepts a contributor's own copyright line in the same form.
- Tests: the two classes that open a LibreHardwareMonitor Computer run one at a time - GenericCpu.Update threw a
  NullReferenceException in the local gate when they ran in parallel (the Agent's own read is already contained).
- Docs corrected in place: 03_METRICS, 18_GPU_VENDOR_APIS, 17_HOOK_ENGINE, 20_OPEN_QUESTIONS (§M7, §H10, new §M11),
  04_CAPTURE, 19_SAFETY, 06_DATA_MODEL, 07_IPC, 02_SPEC, 01_ARCHITECTURE, 12_BUILD, CLAUDE.md; the accuracy block and
  LIMITATIONS.md.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 23:21:45 +07:00

1474 lines
71 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Capture;
using FrameLedger.Application.Consent;
using FrameLedger.Application.Recording;
using FrameLedger.Application.Telemetry;
using FrameLedger.Application.Tests.AntiCheat;
using FrameLedger.Domain.AntiCheat;
using FrameLedger.Domain.Consent;
using FrameLedger.Domain.Display;
using FrameLedger.Domain.Sessions;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Shared;
namespace FrameLedger.Application.Tests.Capture;
/// <summary>
/// The loop's ordering rules, each of which is load-bearing.
/// </summary>
/// <remarks>
/// Merge-gated: no injection, no native fixture, no Integration trait. What these
/// cannot cover — that a real Overlay reads the tick we publish — is the end-to-end
/// class, and the split is stated rather than left implied.
/// </remarks>
public sealed class CaptureSessionTests : IAsyncDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-loop-" + Guid.NewGuid().ToString("N"));
private LedgerDatabase? _db;
private const string _exe = @"C:\Games\Title\game.exe";
private const string _disclosure = "operator-disclosure/test";
private const int _pid = 4242;
private static ExecutableFingerprint Fingerprint =>
new() { ExePath = _exe, SizeBytes = 90_000, MtimeUnixMs = 1_700_000_000_000 };
public async ValueTask DisposeAsync()
{
if (_db is not null)
{
await _db.DisposeAsync().ConfigureAwait(false);
}
try
{
Directory.Delete(_dir, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// MEASURED ON CI 2026-09-10, and it failed a test that had already passed: this class opens a
// real SQLite ledger, Microsoft.Data.Sqlite pools connections, and the pooled handle on
// ledger.db can outlive DisposeAsync by enough for the recursive delete to throw IOException —
// which xUnit reports against the TEST, not the fixture, so `AnIncompleteAttachIsRetried…`
// failed for something that has nothing to do with attaching.
//
// The narrow `catch (DirectoryNotFoundException)` this replaces was the ONLY one of its kind:
// every sibling fixture in this repository already catches IOException (CaptureSessionLaunchTests,
// SessionRecorderTests, LedgerFixture, PartialSessionFileTests…), and this is the one that holds
// a database. A scratch directory left behind under %TEMP% is not worth a red build.
}
}
private sealed class CountingGuard : IAntiCheatGuard
{
public int InjectCalls { get; private set; }
public int EvaluateCalls { get; private set; }
public AntiCheatVerdict Verdict { get; set; } = AntiCheatVerdict.Allowed();
public AntiCheatVerdict EvaluateVerdict { get; set; } = AntiCheatVerdict.Allowed();
public Exception? EvaluateThrows { get; set; }
/// <summary>Throw only from the Nth evaluation onward, so the first scan can succeed.</summary>
public int EvaluateThrowsAfter { get; set; } = int.MaxValue;
/// <summary>D33: the family each injection and each re-scan named, in order.</summary>
public List<string?> InjectTolerated { get; } = [];
public List<string?> EvaluateTolerated { get; } = [];
/// <summary>D33: where "inject" is written, beside the tolerance channel's "publish-tolerance", so their order is observable.</summary>
public List<string>? Events { get; init; }
public ValueTask<AntiCheatVerdict> EvaluateAsync(int targetPid, string? toleratedFamily, CancellationToken ct = default)
{
EvaluateCalls++;
EvaluateTolerated.Add(toleratedFamily);
if (EvaluateThrows is not null || EvaluateCalls > EvaluateThrowsAfter)
{
return ValueTask.FromException<AntiCheatVerdict>(
EvaluateThrows ?? new InvalidOperationException("service query blocked"));
}
return ValueTask.FromResult(EvaluateVerdict);
}
public ValueTask<AntiCheatVerdict> GuardedInjectAsync(int targetPid, string payloadPath, string? toleratedFamily,
CancellationToken ct = default)
{
InjectCalls++;
InjectTolerated.Add(toleratedFamily);
Events?.Add("inject");
return ValueTask.FromResult(Verdict);
}
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath,
int timeoutMs, string? toleratedFamily, CancellationToken ct = default)
{
InjectCalls++;
return ValueTask.FromResult(Verdict);
}
public ValueTask<AntiCheatVerdict> PreScanGameAsync(string executablePath, string? toleratedFamily,
CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
}
private sealed class FakeSink : ICaptureSink
{
private int _remaining;
public FakeSink(int recordsToServe = 0) => _remaining = recordsToServe;
public List<(uint Ticks, bool Unhook)> Published { get; } = [];
public List<int> DrainCallSizes { get; } = [];
/// <summary>
/// Drains and publishes in ONE ordered list, so ordering between them is observable.
/// </summary>
/// <remarks>
/// Two independent lists could not express it: <c>TheFirstTickIsPublishedBeforeAnyDrain</c>
/// asserted only that the first tick was numbered 1, which is true whether the first scan runs
/// before the drain loop or is deferred to the first 30 s boundary. The test was named for a
/// property no assertion in it could see.
/// </remarks>
public List<string> Events { get; } = [];
public int DrainsWithoutGapList { get; private set; }
public FlWriterState State = new() { Status = (uint)FlStatus.Ready };
public FlWriterState WriterState => State;
public FlShmHandshake Handshake => default;
/// <summary>Region 4 as the Overlay would publish it (beta.10); null reads as a writer that described nothing.</summary>
public FlDisplayState? Display { get; set; }
public FlDisplayState? DisplayState => Display;
public long TotalDropped { get; set; }
public long TotalGaps { get; set; }
public DrainResult Drain(Span<FlFrameRecord> into, IList<ulong> gapIndices)
{
if (gapIndices is null)
{
DrainsWithoutGapList++;
}
int n = Math.Min(into.Length, _remaining);
for (int i = 0; i < n; i++)
{
into[i] = new FlFrameRecord { FrameIndex = (uint)i, Qpc = (ulong)(1000 + i), SwapchainId = 1 };
}
_remaining -= n;
DrainCallSizes.Add(n);
Events.Add("drain");
return new DrainResult(n, 0, 0);
}
public void PublishGuardResult(uint completedEvaluations, bool unhookRequested)
{
Published.Add((completedEvaluations, unhookRequested));
Events.Add("publish");
}
public void SetPaused(bool paused)
{
}
public int LogFlushRequests { get; private set; }
public void RequestLogFlush() => LogFlushRequests++;
public void Dispose()
{
}
}
/// <summary>D33: the Overlay's channel, recording what was published, in the order <see cref="CountingGuard.Events"/> keeps.</summary>
private sealed class FakeToleranceChannel(List<string> events, bool works = true) : IOverlayToleranceChannel
{
public List<(int Pid, string Family)> Published { get; } = [];
public int Disposed { get; private set; }
public IDisposable? TryPublish(int pid, string family)
{
events.Add("publish-tolerance");
Published.Add((pid, family));
return works ? new Held(this) : null;
}
private sealed class Held(FakeToleranceChannel owner) : IDisposable
{
public void Dispose() => owner.Disposed++;
}
}
private sealed class FakeLiveness : ITargetLiveness
{
private int _foregroundSamples = int.MaxValue;
private bool _exited;
private int _exitChecks;
/// <summary>Exit after this many liveness checks — the Tier-2 hold's clock when the loop holds a pin (2026-09-22).</summary>
public int ExitAfterChecks { get; set; } = int.MaxValue;
public bool HasExited
{
get => _exited || ++_exitChecks > ExitAfterChecks;
set => _exited = value;
}
public int? ExitCode { get; set; }
/// <summary>How many samples answer true before focus is lost. Default: every one.</summary>
public int ForegroundFor
{
get => _foregroundSamples;
set => _foregroundSamples = value;
}
/// <summary>
/// Consumed per read, so a test can put the switch at a known tick rather than at a
/// known time — the loop's cadence is a wall clock and must not be an input to an
/// assertion.
/// </summary>
public bool IsForeground => _foregroundSamples-- > 0;
public void Dispose()
{
}
}
private sealed class FixedResolver(int? pid, SessionEndReason reason, int runningTicks = 0, IReadOnlyList<int>? pids = null) : ITargetResolver
{
private int _running = runningTicks;
public int ResolveCalls { get; private set; }
public int? Resolve(string normalisedExePath, out SessionEndReason r)
{
ResolveCalls++;
r = reason;
return pid;
}
/// <summary>The name clock of a hold that never opened the process: "running" for so many checks, then gone.</summary>
public bool IsRunning(string normalisedExePath) => _running-- > 0;
public IReadOnlyList<int> PidsOf(string normalisedExePath) => pids ?? [];
}
/// <summary>The window reader (beta.10): what each tick asked it, and one fixed answer.</summary>
private sealed class RecordingProbe(WindowView? answer) : IDisplayProbe
{
public List<(int[] Pids, ulong Hwnd)> Calls { get; } = [];
public WindowView? Observe(IReadOnlyCollection<int> pids, ulong hwnd)
{
Calls.Add(([.. pids], hwnd));
return answer;
}
}
private sealed class TickCounter : ICaptureObserver
{
public int Ticks { get; private set; }
/// <summary>What each tick said the session is held under (2026-09-23: the pipe announces a hold from its first tick).</summary>
public List<CaptureOutcome?> Holds { get; } = [];
public void Attached(int pid, FlShmHandshake handshake)
{
}
public void Tick(CaptureProgress progress)
{
Ticks++;
Holds.Add(progress.Hold);
progress.Records.Should().BeEmpty("a held session has no ring to drain");
}
}
private async Task<IGameConsentStore> StoreWithAsync(bool enabled = true, bool preScanUnverified = false)
{
// The same SQLite adapter the host and the Agent use, on a scratch ledger under this test's directory.
_db ??= await LedgerDatabase.OpenAsync(Path.Combine(_dir, LedgerPaths.DatabaseFileName), ct: TestContext.Current.CancellationToken)
.ConfigureAwait(false);
var store = new SqliteGameConsentStore(_db);
if (enabled)
{
await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
{
Fingerprint = Fingerprint,
DisclosureVersion = _disclosure,
AcknowledgedAt = DateTimeOffset.UnixEpoch,
}, TestContext.Current.CancellationToken).ConfigureAwait(false);
}
if (preScanUnverified)
{
await store.RecordGuardBlockAsync(Fingerprint, default, TestContext.Current.CancellationToken)
.ConfigureAwait(false);
}
return store;
}
private static CaptureSession Loop(IGameConsentStore store, CountingGuard guard, FakeSink? sink,
FakeLiveness? alive = null, int? pid = _pid, SessionEndReason resolveReason = SessionEndReason.Running,
CaptureOptions? options = null, IKillSwitch? killSwitch = null, ICapturePauseSource? pause = null,
IUserModeExceptionSwitch? exceptions = null, IOverlayToleranceChannel? tolerance = null, IDisplayProbe? display = null) =>
new(store,
new HookedCaptureGate(guard),
guard,
new FixedResolver(pid, resolveReason),
new DelegateLivenessSource(_ => alive ?? new FakeLiveness()),
new DelegateRingAttacher(_ => (sink, sink is null ? ShmAttachRefusal.BuildIdMismatch : ShmAttachRefusal.Ok)),
options ?? new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromMilliseconds(50),
MaxDuration = TimeSpan.FromMilliseconds(120),
HoldInterval = TimeSpan.FromMilliseconds(1),
LogFlushGrace = TimeSpan.FromMilliseconds(1),
},
killSwitch: killSwitch,
pause: pause,
exceptions: exceptions,
tolerance: tolerance,
display: display);
private static readonly bool[] _pauseThenResume = [true, false];
private sealed class SwitchablePause : ICapturePauseSource
{
public bool IsPaused { get; set; }
}
private sealed class PauseObservingSink : ICaptureSink
{
public List<bool> PauseCalls { get; } = [];
public FlWriterState WriterState => new() { Status = (uint)FlStatus.Ready };
public FlShmHandshake Handshake => default;
public FlDisplayState? DisplayState => null;
public long TotalDropped => 0;
public long TotalGaps => 0;
public DrainResult Drain(Span<FlFrameRecord> into, IList<ulong> gapIndices) => new(0, 0, 0);
public void PublishGuardResult(uint completedEvaluations, bool unhookRequested)
{
}
public void SetPaused(bool paused) => PauseCalls.Add(paused);
public void RequestLogFlush()
{
}
public void Dispose()
{
}
}
[Fact]
public async Task AStopTokenEndsTheSessionAsStoppedByUserWithTheTargetStillRunning()
{
// FR-3.6's "user stop" (P3 PR-1b): the loop reads its own stop token at a tick and ends with a reason the
// recorder finalizes — not the host's cancellation, which would leave a .partial. The target is untouched.
IGameConsentStore store = await StoreWithAsync().ConfigureAwait(true);
var guard = new CountingGuard();
using var sink = new FakeSink(recordsToServe: 3);
using var alive = new FakeLiveness();
using var stop = new CancellationTokenSource();
CaptureSession loop = Loop(store, guard, sink, alive, options: new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromSeconds(30),
AttachBudget = TimeSpan.FromSeconds(5),
MaxDuration = TimeSpan.FromSeconds(30),
LogFlushGrace = TimeSpan.FromMilliseconds(1),
});
Task<CaptureOutcome> running = loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken, stop.Token);
await Task.Delay(30, TestContext.Current.CancellationToken).ConfigureAwait(true);
running.IsCompleted.Should().BeFalse("nothing has ended the session");
await stop.CancelAsync().ConfigureAwait(true);
CaptureOutcome r = await running.ConfigureAwait(true);
r.Reason.Should().Be(SessionEndReason.StoppedByUser);
r.Records.Should().HaveCount(3, "the drains before and at the stop are kept");
alive.HasExited.Should().BeFalse("the stop is the session's, never the target's");
sink.Events.Last().Should().Be("drain", "the last drain runs after the stop is seen");
}
[Fact]
public async Task ThePauseIsToldToTheRingOncePerTransitionAndNeverStopsSupervision()
{
IGameConsentStore store = await StoreWithAsync().ConfigureAwait(true);
var guard = new CountingGuard();
var pause = new SwitchablePause();
using var sink = new PauseObservingSink();
using var alive = new FakeLiveness();
using var stop = new CancellationTokenSource();
// This case needs its own observing sink, so the attacher is built directly rather than through Loop().
var loop = new CaptureSession(store, new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
new DelegateLivenessSource(_ => alive), new DelegateRingAttacher(_ => (sink, ShmAttachRefusal.Ok)),
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromSeconds(5),
MaxDuration = TimeSpan.FromSeconds(30),
LogFlushGrace = TimeSpan.FromMilliseconds(1),
}, pause: pause);
Task<CaptureOutcome> running = loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken, stop.Token);
await Task.Delay(20, TestContext.Current.CancellationToken).ConfigureAwait(true);
int scansBeforePause = guard.EvaluateCalls;
pause.IsPaused = true;
await Task.Delay(30, TestContext.Current.CancellationToken).ConfigureAwait(true);
pause.IsPaused = false;
await Task.Delay(20, TestContext.Current.CancellationToken).ConfigureAwait(true);
await stop.CancelAsync().ConfigureAwait(true);
CaptureOutcome r = await running.ConfigureAwait(true);
r.Reason.Should().Be(SessionEndReason.StoppedByUser);
sink.PauseCalls.Should().Equal(_pauseThenResume, "told once per transition, never per tick");
guard.EvaluateCalls.Should().BeGreaterThan(scansBeforePause, "supervision keeps scanning while the recording is paused");
}
/// <summary>
/// beta.8: the Overlay records nothing while paused, so the first record after a resume is QPC-apart from the last one
/// before the pause by the whole pause — a fabricated long frame in every statistic, and time the averages counted.
/// It follows a gap now, like a torn slot's survivor.
/// </summary>
[Fact]
public async Task TheFirstRecordPresentedAfterAResumeFollowsAGap()
{
IGameConsentStore store = await StoreWithAsync().ConfigureAwait(true);
var guard = new CountingGuard();
var pause = new SwitchablePause();
using var sink = new PresentingSink();
using var alive = new FakeLiveness();
using var stop = new CancellationTokenSource();
var loop = new CaptureSession(store, new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
new DelegateLivenessSource(_ => alive), new DelegateRingAttacher(_ => (sink, ShmAttachRefusal.Ok)),
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromSeconds(30),
AttachBudget = TimeSpan.FromSeconds(5),
MaxDuration = TimeSpan.FromSeconds(30),
LogFlushGrace = TimeSpan.FromMilliseconds(1),
}, pause: pause);
Task<CaptureOutcome> running = loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken, stop.Token);
await Task.Delay(30, TestContext.Current.CancellationToken).ConfigureAwait(true);
pause.IsPaused = true;
await Task.Delay(120, TestContext.Current.CancellationToken).ConfigureAwait(true);
pause.IsPaused = false;
await Task.Delay(30, TestContext.Current.CancellationToken).ConfigureAwait(true);
await stop.CancelAsync().ConfigureAwait(true);
CaptureOutcome r = await running.ConfigureAwait(true);
// The pause is the one long interval in the stream; the record that ends it is the one after the resume.
int afterResume = Enumerable.Range(1, r.Records.Count - 1).MaxBy(i => r.Records[i].Qpc - r.Records[i - 1].Qpc);
(r.Records[afterResume].Qpc - r.Records[afterResume - 1].Qpc).Should().BeGreaterThan((ulong)(Stopwatch.Frequency / 20), "the pause lasted 120 ms");
r.GapBefore.Should().ContainSingle().Which.Should().Be(afterResume, "the interval that spans the pause is not a frame time");
}
/// <summary>A ring the Overlay writes one record into per drain while it is not paused, stamped with the QPC as the Overlay's present is.</summary>
private sealed class PresentingSink : ICaptureSink
{
private bool _paused;
private uint _frame;
public FlWriterState WriterState => new() { Status = (uint)FlStatus.Ready };
public FlShmHandshake Handshake => default;
public FlDisplayState? DisplayState => null;
public long TotalDropped => 0;
public long TotalGaps => 0;
public DrainResult Drain(Span<FlFrameRecord> into, IList<ulong> gapIndices)
{
if (Volatile.Read(ref _paused))
{
return new DrainResult(0, 0, 0);
}
into[0] = new FlFrameRecord { FrameIndex = _frame++, Qpc = (ulong)Stopwatch.GetTimestamp(), SwapchainId = 1 };
return new DrainResult(1, 0, 0);
}
public void PublishGuardResult(uint completedEvaluations, bool unhookRequested)
{
}
public void SetPaused(bool paused) => Volatile.Write(ref _paused, paused);
public void RequestLogFlush()
{
}
public void Dispose()
{
}
}
[Fact]
public async Task TheModuleSnapshotIsTakenBesideEveryGuardScanAndOnceMoreBeforeTheLastDrain()
{
// The snapshot rides on the scan's cadence, never its own: one directly after each publish,
// and one more after the loop exits so a module that loaded after the final scan is still
// named. The sink's ordered event list is what makes the "directly after" observable.
var guard = new CountingGuard();
using var sink = new FakeSink();
int snapshots = 0;
var loop = new CaptureSession(
await StoreWithAsync(), new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
new DelegateLivenessSource(_ => new FakeLiveness()),
new DelegateRingAttacher(_ => (sink, ShmAttachRefusal.Ok)),
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromMilliseconds(50),
MaxDuration = TimeSpan.FromMilliseconds(120),
HoldInterval = TimeSpan.FromMilliseconds(1),
LogFlushGrace = TimeSpan.FromMilliseconds(1),
},
new DelegateModuleSnapshot(pid =>
{
pid.Should().Be(_pid);
snapshots++;
sink.Events.Add("modules");
return new RuntimeModuleSet(
[new RuntimeModuleInfo("sl.interposer.dll", @"C:\Games\Title\sl.interposer.dll", "2,8,0,0", new Version(2, 8, 0, 0))],
Snapshots: 1, Unreadable: 0);
}));
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
snapshots.Should().Be(sink.Published.Count + 1, "one per scan, plus the one before the last drain");
r.RuntimeModules.Snapshots.Should().Be(snapshots);
r.RuntimeModules.Unreadable.Should().Be(0);
r.RuntimeModules.VersionOf("sl.interposer.dll").Should().Be(new Version(2, 8, 0, 0));
r.RuntimeModules.Modules.Should().ContainSingle("the same module across snapshots is one entry");
for (int i = 0; i < sink.Events.Count; i++)
{
if (string.Equals(sink.Events[i], "publish", StringComparison.Ordinal))
{
sink.Events[i + 1].Should().Be("modules", "the snapshot follows the publish directly");
}
}
sink.Events[^2].Should().Be("modules", "the final snapshot precedes the final drain");
sink.Events[^1].Should().Be("drain");
}
[Fact]
public async Task ALoopBuiltWithoutASnapshotSourceReportsAnEmptySet()
{
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.RuntimeModules.Should().BeSameAs(RuntimeModuleSet.Empty);
r.NgxDriver.Should().BeSameAs(NgxDriverState.NotRun, "no probe was given to the loop");
}
[Fact]
public async Task TheDriverProbeRidesOnTheSameTouchAsTheModuleSnapshotAndIsMergedOntoTheResult()
{
// The probe is out of process and answers per pid; it rides the scan's cadence exactly as the
// module snapshot does, and a later answer that differs is reported as a CHANGE, not averaged.
var guard = new CountingGuard();
using var sink = new FakeSink();
int probes = 0;
var loop = new CaptureSession(
await StoreWithAsync(), new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
new DelegateLivenessSource(_ => new FakeLiveness()),
new DelegateRingAttacher(_ => (sink, ShmAttachRefusal.Ok)),
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromMilliseconds(50),
MaxDuration = TimeSpan.FromMilliseconds(120),
HoldInterval = TimeSpan.FromMilliseconds(1),
LogFlushGrace = TimeSpan.FromMilliseconds(1),
},
modules: null,
ngx: new DelegateNgxProbe(pid =>
{
pid.Should().Be(_pid);
probes++;
sink.Events.Add("ngx");
// The first reading has DLSS not yet created; every later one has it created and evaluated.
ulong sr = probes == 1 ? NgxOverrideFlags.Initialized | NgxOverrideFlags.DllExists
: NgxOverrideFlags.Initialized | NgxOverrideFlags.DllExists | NgxOverrideFlags.CreatedAndEvaluated;
return NgxDriverState.Parse($"NGXSTATE status=ANSWERED sr=0x{sr:X16} rr=0x1 fg=0x5 ratio=0.0000 mode=0 preset=0 fgcount=0 fgpreset=0 fgmode=0 driver=61664");
}));
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
probes.Should().Be(sink.Published.Count + 1, "one per scan, plus the one before the last drain");
r.NgxDriver.Outcome.Should().Be(NgxProbeOutcome.Answered);
r.NgxDriver.Readings.Should().Be(probes);
r.NgxDriver.Answered.Should().Be(probes);
r.NgxDriver.SrCreatedAndEvaluated.Should().BeTrue("the last answered reading is the state");
r.NgxDriver.Changed.Should().BeTrue("the first reading differed from the later ones");
r.NgxDriver.Driver.Should().Be(61664u);
for (int i = 0; i < sink.Events.Count; i++)
{
if (string.Equals(sink.Events[i], "publish", StringComparison.Ordinal))
{
sink.Events[i + 1].Should().Be("ngx", "the probe follows the publish directly, on the snapshot's touch");
}
}
}
[Fact]
public async Task NoRecordRefusesConsentAndNothingIsEverInjected()
{
// HANDOFF's acceptance for item 1: "Assert ConsentMissing with FlGuardedInject NEVER reached."
// HookNotEnabled is what an ABSENT record produces, because the gate checks enablement first.
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(enabled: false), guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedHookNotEnabled);
guard.InjectCalls.Should().Be(0);
sink.Published.Should().BeEmpty("nothing was attached to, so nothing could be published");
}
[Fact]
public async Task PreScanUnverifiedRefusesWithoutBecomingPreviouslyBlocked()
{
// 05_DETECTION: "could not verify" is neither a hit nor a pass. Routing it through the gate
// would force one of the two collapses it forbids, so it is refused before a request is built.
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(preScanUnverified: true), guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.PreScanCouldNotVerify);
r.Reason.Should().NotBe(SessionEndReason.RefusedPreviouslyBlocked);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task AnUnresolvedTargetNeverReachesConsentOrTheGuard()
{
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink,
pid: null, resolveReason: SessionEndReason.TargetNotRunning);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.TargetNotRunning);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task TwoProcessesOfTheSameGameRefuseRatherThanPickOne()
{
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink,
pid: null, resolveReason: SessionEndReason.TargetAmbiguous);
(await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken))
.Reason.Should().Be(SessionEndReason.TargetAmbiguous);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task TheFirstTickIsPublishedBeforeAnyDrain()
{
// The Overlay's 65 s FL_GUARD_TICK_DEADLINE_MS clock starts at mapping publish, not at attach,
// so a first scan deferred to the 30 s boundary is already half way to a supervision stop.
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
// THE ORDERING, OBSERVED. Asserting `Published[0].Ticks == 1` alone was decoration: it holds
// whether the first scan runs before the drain loop or is deferred to the first 30 s boundary,
// because either way the first tick published is the first tick counted.
sink.Events.Should().NotBeEmpty();
sink.Events[0].Should().Be("publish",
"the Overlay's 65 s supervision clock starts when the mapping is published, not when we "
+ "adopt it, so a first scan deferred by 30 s is already half way to a supervision stop");
sink.Published[0].Ticks.Should().Be(1u);
r.GuardTicksPublished.Should().BeGreaterThanOrEqualTo(1u);
}
[Fact]
public async Task ThePublishedTickIsTheSupervisorsCompletedEvaluations()
{
// NEVER a counter this loop keeps. A loop-owned tick attests that this process is alive while
// the guard loop can be dead — the exact signal fl_shm.h spends sixteen lines forbidding.
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
sink.Published.Select(p => p.Ticks).Should().BeEquivalentTo(
Enumerable.Range(1, sink.Published.Count).Select(i => (uint)i),
options => options.WithStrictOrdering());
sink.Published[^1].Ticks.Should().Be((uint)guard.EvaluateCalls);
}
/// <summary>
/// What a finding does to the game (owner decision 2026-09-22, <c>19_SAFETY</c>): the guard's start-time scan named
/// an anti-cheat IN the game, so the loop writes the block the pre-scan would have — hooking off, the reason on the
/// row — and says so in the outcome. The next launch is a game whose hooking is off, not a new refusal.
/// </summary>
[Fact]
public async Task AStartTimeFindingAboutTheGameTurnsItsHookingOffAndTheOutcomeSaysSo()
{
var guard = new CountingGuard { Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedModule, "BattlEye", "BEClient_x64.dll") };
using var sink = new FakeSink();
IGameConsentStore store = await StoreWithAsync();
CaptureSession loop = Loop(store, guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedByGuard);
r.HookingTurnedOff.Should().BeTrue();
GameConsentRecord after = await store.FindAsync(_exe, TestContext.Current.CancellationToken);
after.HookEnabled.Should().BeFalse("the finding turned hooking off");
after.BlockedReason.Should().Contain("BattlEye").And.Contain("BEClient_x64.dll");
after.ConsentedAt.Should().NotBeNull("a block is not a withdrawal of consent (19_SAFETY)");
}
/// <summary>A machine-wide driver says nothing about THIS game: the session is refused, the row is untouched.</summary>
[Fact]
public async Task AMachineWideDriverRefusesThisSessionAndLeavesTheGamesHookingOn()
{
var guard = new CountingGuard { Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedDriver, "Riot Vanguard", "vgk.sys") };
using var sink = new FakeSink();
IGameConsentStore store = await StoreWithAsync();
CaptureOutcome r = await Loop(store, guard, sink).RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedByGuard);
r.HookingTurnedOff.Should().BeFalse();
GameConsentRecord after = await store.FindAsync(_exe, TestContext.Current.CancellationToken);
after.HookEnabled.Should().BeTrue();
after.BlockedReason.Should().BeNull();
}
[Fact]
public async Task AGuardRefusalStopsTheSessionAndPublishesTheLatch()
{
var guard = new CountingGuard
{
EvaluateVerdict = AntiCheatVerdict.Refused(
AntiCheatRefusalReason.BlockedModule, "BattlEye", "BEClient_x64.dll")
};
using var sink = new FakeSink();
IGameConsentStore store = await StoreWithAsync();
CaptureSession loop = Loop(store, guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.SafetyUnhook);
sink.Published.Should().ContainSingle().Which.Unhook.Should().BeTrue();
// A finding at the re-scan turns the game's hooking off exactly as one at the start does (2026-09-22).
r.HookingTurnedOff.Should().BeTrue();
(await store.FindAsync(_exe, TestContext.Current.CancellationToken)).HookEnabled.Should().BeFalse();
}
[Fact]
public async Task AGuardThatThrowsStopsTheTickRatherThanBeingSwallowed()
{
// GuardSupervisor deliberately does not catch. If the guard throws, the tick does not advance
// and the capture side sees supervision stop, which is the correct outcome.
var guard = new CountingGuard { EvaluateThrows = new InvalidOperationException("service query blocked") };
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
Func<Task> act = () => loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
await act.Should().ThrowAsync<InvalidOperationException>();
}
[Fact]
public async Task AQuietButLiveTargetIsNeverASessionEnd()
{
// §S29(e). The sink serves nothing at all and status stays READY — byte-for-byte a loading
// screen. The session must run to its own limit, not decide the game is gone.
var guard = new CountingGuard();
using var sink = new FakeSink(recordsToServe: 0);
using var alive = new FakeLiveness { HasExited = false };
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink, alive);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.Running, "a frozen writeIndex means nothing about liveness");
r.Records.Should().BeEmpty();
}
[Fact]
public async Task AnExitedTargetEndsTheSessionEvenWhileStatusStillSaysReady()
{
var guard = new CountingGuard();
using var sink = new FakeSink();
using var alive = new FakeLiveness { HasExited = true };
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink, alive);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.TargetExited);
sink.State.Status.Should().Be((uint)FlStatus.Ready, "the mapping never said the target had gone");
}
[Fact]
public async Task TheLoopCountsWhetherTheOperatorWasWATCHINGTheGame()
{
// Frame generation stops while a title is unfocused, so a window spanning an alt-tab
// averages two configurations: measured 2026-08-16, that turned a ×2 capture into an
// achieved presents/batch of 1.84. FgWindow.BatchRefusal is what REFUSES such a window
// from the records; these two counts are what let the report name the cause.
//
// BOTH NUMBERS OR NEITHER. "Unfocused for 40 ticks" is a finding only if the target ever
// held the foreground — a windowless target, which hook-harness is, answers false on
// every tick of every run and means nothing by it.
var guard = new CountingGuard();
using var sink = new FakeSink(recordsToServe: 10);
using var alive = new FakeLiveness { ForegroundFor = 1 };
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink, alive);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.DrainTicks.Should().BeGreaterThan(1, "the loop ran more than one tick inside its own duration");
r.ForegroundTicks.Should().Be(1,
"the fake yields focus after one sample, so the count is about the SAMPLE and not about "
+ "how fast this machine happened to run the loop");
}
[Fact]
public async Task ADrainThatFillsTheBufferIsCalledAgainInTheSameTick()
{
// Drain copies at most into.Length and returns, so one call per tick caps throughput and the
// excess becomes drops that look like a stall.
var guard = new CountingGuard();
using var sink = new FakeSink(recordsToServe: 1200);
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Records.Should().HaveCount(1200);
sink.DrainCallSizes.Take(2).Should().AllSatisfy(n => n.Should().Be(512));
}
[Fact]
public async Task DrainIsNeverCalledWithoutAGapList()
{
// The parameter defaults to null and the default is the wrong behaviour: 07_IPC needs a torn
// record recorded at its INDEX, or the two surrounding intervals merge into one fabricated
// stutter.
var guard = new CountingGuard();
using var sink = new FakeSink(recordsToServe: 10);
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
sink.DrainsWithoutGapList.Should().Be(0);
}
[Fact]
public async Task ATerminalAttachRefusalIsNotRetriedIntoATimeout()
{
// COUNTING THE ATTEMPTS IS THE POINT. Asserting only the final Reason and AttachRefusal was
// decoration: both are identical whether the terminal refusal returns on the first attempt or
// is retried until the budget expires, so the test could not fail for the property it names.
var guard = new CountingGuard();
int attempts = 0;
var loop = new CaptureSession(
await StoreWithAsync(), new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
new DelegateLivenessSource(_ => new FakeLiveness()),
new DelegateRingAttacher(_ =>
{
attempts++;
return ((ICaptureSink?)null, ShmAttachRefusal.BuildIdMismatch);
}),
// The refused attach is held as Tier 2 until the target exits (2026-09-22); the fake never exits, so bound it.
new CaptureOptions { AttachBudget = TimeSpan.FromMilliseconds(500), MaxDuration = TimeSpan.FromMilliseconds(50), HoldInterval = TimeSpan.FromMilliseconds(1) });
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.AttachRefused);
r.HeldUnhooked.Should().BeTrue("a refused attach is a Tier-2 session, not a return code");
r.AttachRefusal.Should().Be(ShmAttachRefusal.BuildIdMismatch,
"the cause must survive to the caller; a build-id mismatch tells the user to restart the game");
attempts.Should().Be(1, "a terminal refusal is an answer, and retrying one turns it into a timeout");
}
[Fact]
public async Task AnIncompleteAttachIsRetriedUntilTheHandshakeIsPublished()
{
// THE GREEN HALF, without which the case above is satisfied by a loop that never retries at
// all. Incomplete is the one retryable refusal: the Overlay publishes layoutVersion last,
// behind a release fence, so "not ready yet" is a real transient state.
var guard = new CountingGuard();
using var sink = new FakeSink();
int attempts = 0;
var loop = new CaptureSession(
await StoreWithAsync(), new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
new DelegateLivenessSource(_ => new FakeLiveness()),
new DelegateRingAttacher(_ => ++attempts < 3 ? (null, ShmAttachRefusal.Incomplete) : (sink, ShmAttachRefusal.Ok)),
new CaptureOptions
{
DrainInterval = TimeSpan.FromMilliseconds(1),
ScanInterval = TimeSpan.FromMilliseconds(5),
AttachBudget = TimeSpan.FromSeconds(2),
MaxDuration = TimeSpan.FromMilliseconds(60),
});
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
attempts.Should().Be(3);
r.Reason.Should().NotBe(SessionEndReason.AttachRefused);
r.AttachRefusal.Should().Be(ShmAttachRefusal.Ok);
}
[Fact]
public async Task APidThatCannotBePinnedRefusesInsteadOfInjecting()
{
// A handle we could not open means the pid is not reserved, so it can be recycled between here
// and FlGuardedInject — and there is an awaited file read in that window. 19_SAFETY §Elevated /
// protected targets: report "cannot attach", never escalate creatively.
var guard = new CountingGuard();
using var sink = new FakeSink();
var loop = new CaptureSession(
await StoreWithAsync(), new HookedCaptureGate(guard), guard, new FixedResolver(_pid, SessionEndReason.Running),
new DelegateLivenessSource(_ => null),
new DelegateRingAttacher(_ => (sink, ShmAttachRefusal.Ok)),
new CaptureOptions());
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.TargetCannotBePinned);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task AnUnreadableExecutableRefusesRatherThanComparingTheRecordWithItself()
{
// `observed ?? record.Fingerprint` made FromConsent's mismatch check compare the record against
// ITSELF and always pass, so "we could not look at the binary" decided as "the binary is the
// consented one" — the one polarity every other default here refuses.
var guard = new CountingGuard();
using var sink = new FakeSink();
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
CaptureOutcome r = await loop.RunAsync(_exe, observed: null, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.ExecutableUnreadable);
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task AGuardThatThrowsMidSessionKeepsTheRecordsItAlreadyDrained()
{
// The two consequences are separable and were conflated. Not advancing the tick is what stops
// the capture side and is correct; losing the whole session's records with the stack is not.
var guard = new CountingGuard();
using var sink = new FakeSink(recordsToServe: 40);
CaptureSession loop = Loop(await StoreWithAsync(), guard, sink);
guard.EvaluateThrowsAfter = 1;
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.SupervisionFaulted);
r.Records.Should().NotBeEmpty("the drain ran before the guard threw, and those frames are real");
sink.Published.Should().ContainSingle("the tick must NOT advance past the evaluation that threw");
}
[Fact]
public async Task AnEngagedKillSwitchRefusesBeforeTheGuardAndStopsARunningSessionAtTheNextScan()
{
// FR-2.4 (P2 PR-F, decision D7). Engaged from the start: the gate refuses with its own reason and the
// guard is never asked. Engaged mid-session: at the next scan boundary the loop publishes
// unhookRequested — the signal the Overlay already stops on — and ends as KillSwitchEngaged, which is
// the user's stop and not the SafetyUnhook a refused scan would read as.
var guard = new CountingGuard();
var engaged = new DelegateKillSwitch(() => true);
using var refusedSink = new FakeSink();
CaptureOutcome refused = await Loop(await StoreWithAsync(), guard, refusedSink, killSwitch: engaged)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
refused.Reason.Should().Be(SessionEndReason.RefusedKillSwitch);
refused.Verdict.Reason.Should().Be(AntiCheatRefusalReason.KillSwitchEngaged);
guard.InjectCalls.Should().Be(0, "the switch is checked before consent is read, so the guard is never reached");
int asks = 0;
var flipsAfterTwo = new DelegateKillSwitch(() => ++asks > 2);
using var sink = new FakeSink(recordsToServe: 3);
var stopped = new CountingGuard();
CaptureOutcome result = await Loop(await StoreWithAsync(), stopped, sink, killSwitch: flipsAfterTwo)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
result.Reason.Should().Be(SessionEndReason.KillSwitchEngaged);
sink.Published.Should().Contain(p => p.Unhook, "the stop is published on the ring the way a safety stop is");
sink.Published[^1].Ticks.Should().Be(stopped.EvaluateCalls > 0 ? (uint)stopped.EvaluateCalls : 0u,
"the tick stays the supervisor's own count; nothing here attests to a scan that did not run");
result.Records.Should().HaveCount(3, "the last drain still runs on this path");
}
/// <summary>The loop with an explicit resolver and liveness: the Tier-2 hold's two clocks (2026-09-22).</summary>
private static CaptureSession With(IGameConsentStore store, CountingGuard guard, FixedResolver resolver, FakeLiveness? alive = null,
ICaptureObserver? observer = null, bool hold = true, IUserModeExceptionSwitch? exceptions = null, IOverlayToleranceChannel? tolerance = null,
IDisplayProbe? display = null) =>
new(store, new HookedCaptureGate(guard), guard, resolver,
new DelegateLivenessSource(_ => alive ?? new FakeLiveness()),
new DelegateRingAttacher(_ => (null, ShmAttachRefusal.BuildIdMismatch)),
new CaptureOptions
{
HoldInterval = TimeSpan.FromMilliseconds(1),
HoldUnhooked = hold,
MaxDuration = TimeSpan.FromSeconds(5),
AttachBudget = TimeSpan.FromMilliseconds(20),
},
observer: observer,
exceptions: exceptions,
tolerance: tolerance,
display: display);
/// <summary>
/// Tier 2 as a session (2026-09-22; <c>04_CAPTURE</c> §Tier selection): a row whose hooking is off is decided BEFORE the
/// process is opened — no resolver, no pin, no gate — and the session is held, ticking, until the executable's name
/// leaves the process list. Until then a hooking-off utility that ran elevated was reported as an anti-cheat-protected
/// process (Borderless Gaming on the owner's machine), because the resolver ran first.
/// </summary>
[Fact]
public async Task AHookingOffRowIsHeldAsTierTwoAndItsProcessIsNeverOpened()
{
var guard = new CountingGuard();
var resolver = new FixedResolver(_pid, SessionEndReason.Running, runningTicks: 3);
var ticks = new TickCounter();
CaptureSession loop = With(await StoreWithAsync(enabled: false), guard, resolver, observer: ticks);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedHookNotEnabled);
r.Verdict.Reason.Should().Be(AntiCheatRefusalReason.HookNotEnabled);
r.HeldUnhooked.Should().BeTrue();
r.TargetPid.Should().Be(0, "nothing was opened, so there is no pid to report");
resolver.ResolveCalls.Should().Be(0, "a hooking-off row is never resolved, so its process is never opened");
guard.InjectCalls.Should().Be(0);
ticks.Ticks.Should().BeGreaterThanOrEqualTo(3, "duration and telemetry accrue on the hold's ticks");
ticks.Holds.Should().AllSatisfy(static h =>
{
h.Should().NotBeNull("every held tick says why, so the pipe can say it while the game runs");
h!.Reason.Should().Be(SessionEndReason.RefusedHookNotEnabled);
h.Verdict.Reason.Should().Be(AntiCheatRefusalReason.HookNotEnabled);
h.TargetPid.Should().Be(0);
});
}
[Fact]
public async Task ABlockedRowsTierTwoSessionCarriesTheBlockAsItsVerdict()
{
IGameConsentStore store = await StoreWithAsync();
await store.RecordGuardBlockAsync(Fingerprint, AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedModule, "BattlEye", "BEClient_x64.dll"),
TestContext.Current.CancellationToken);
var resolver = new FixedResolver(_pid, SessionEndReason.Running, runningTicks: 1);
CaptureOutcome r = await With(store, new CountingGuard(), resolver).RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedHookNotEnabled, "a block forces hooking off, and hooking off is decided first");
r.Verdict.Reason.Should().Be(AntiCheatRefusalReason.PreviouslyBlocked);
r.Verdict.Signal.Should().Contain("BattlEye");
resolver.ResolveCalls.Should().Be(0);
}
[Fact]
public async Task ATargetThatCannotBeReadIsHeldByItsNameAndOneThatIsNotRunningIsNot()
{
var guard = new CountingGuard();
IGameConsentStore store = await StoreWithAsync();
CaptureOutcome held = await With(store, guard, new FixedResolver(null, SessionEndReason.TargetUnreadable, runningTicks: 2))
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
CaptureOutcome gone = await With(store, guard, new FixedResolver(null, SessionEndReason.TargetNotRunning, runningTicks: 5))
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
held.Reason.Should().Be(SessionEndReason.TargetUnreadable);
held.HeldUnhooked.Should().BeTrue("the process exists and cannot be opened; its name is the clock");
gone.Reason.Should().Be(SessionEndReason.TargetNotRunning);
gone.HeldUnhooked.Should().BeFalse("there is nothing to hold");
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task ARefusedSessionHoldsUntilTheTargetExitsAndCarriesItsExitCode()
{
var guard = new CountingGuard { Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedDriver, "Riot Vanguard", "vgk.sys") };
using var alive = new FakeLiveness { ExitAfterChecks = 3, ExitCode = 7 };
var ticks = new TickCounter();
CaptureOutcome r = await With(await StoreWithAsync(), guard, new FixedResolver(_pid, SessionEndReason.Running), alive, ticks)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedByGuard);
r.HeldUnhooked.Should().BeTrue();
r.TargetPid.Should().Be(_pid);
r.ExitCode.Should().Be(7, "the game's own end is the session's end, crash and all");
ticks.Ticks.Should().BeGreaterThanOrEqualTo(3);
guard.InjectCalls.Should().Be(1, "the guard was asked once and refused; the hold asks nothing more");
ticks.Holds.Should().AllSatisfy(h =>
{
h!.Reason.Should().Be(SessionEndReason.RefusedByGuard);
h.Verdict.Family.Should().Be("Riot Vanguard");
h.TargetPid.Should().Be(_pid, "the pipe's start names the process the loop holds");
});
}
/// <summary>What the loop told the observer to read the game's memory of (beta.12, D43), in order.</summary>
private sealed class MeasuringRecorder : ICaptureObserver
{
public List<GameProcess> Targets { get; } = [];
public void Attached(int pid, FlShmHandshake handshake)
{
}
public void Tick(CaptureProgress progress)
{
}
public void Measuring(GameProcess target) => Targets.Add(target);
}
/// <summary>A resolver whose watcher snapshot names a different set of processes after a few hold ticks.</summary>
private sealed class ChangingProcesses(int runningTicks, IReadOnlyList<GameProcessId> first, IReadOnlyList<GameProcessId> then, int switchAfter) : ITargetResolver
{
private int _running = runningTicks;
private int _asked;
public int? Resolve(string normalisedExePath, out SessionEndReason reason)
{
reason = SessionEndReason.Running;
return _pid;
}
public bool IsRunning(string normalisedExePath) => _running-- > 0;
public IReadOnlyList<int> PidsOf(string normalisedExePath) => [];
public IReadOnlyList<GameProcessId> ProcessesOf(string normalisedExePath) => _asked++ < switchAfter ? first : then;
}
/// <summary>
/// beta.12 (D43): a session refused after the pin is held through that pin, and the game's memory is read through it —
/// the observer hears the pinned process first and "none" before the pin is released, nothing in between.
/// </summary>
[Fact]
public async Task ARefusalAfterThePinReadsTheGamesMemoryThroughThePinAndLetsGoBeforeItCloses()
{
var guard = new CountingGuard { Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedDriver, "Riot Vanguard", "vgk.sys") };
using var alive = new FakeLiveness { ExitAfterChecks = 3 };
var measuring = new MeasuringRecorder();
await With(await StoreWithAsync(), guard, new FixedResolver(_pid, SessionEndReason.Running), alive, measuring)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
measuring.Targets.Should().HaveCount(2);
measuring.Targets[0].Pid.Should().Be(_pid);
measuring.Targets[0].PinnedBy.Should().BeSameAs(alive, "the session's own pin, whose handle the read borrows");
measuring.Targets[1].IsNone.Should().BeTrue("let go of before the pin's handle closes");
}
/// <summary>
/// beta.12 (D43): a hooking-off hold never opens the game for itself; it names the processes the watcher's snapshot
/// lists for the executable, re-announces only when that set changes, and lets go at the end.
/// </summary>
[Fact]
public async Task AnUnpinnedHoldAnnouncesItsProcessesWhenTheSetChangesAndLetsGoAtTheEnd()
{
var t = DateTimeOffset.UnixEpoch;
GameProcessId[] one = [new(100, t)];
GameProcessId[] two = [new(100, t), new(200, t.AddSeconds(3))];
var resolver = new ChangingProcesses(runningTicks: 8, first: one, then: two, switchAfter: 3);
var measuring = new MeasuringRecorder();
var guard = new CountingGuard();
CaptureOutcome r = await With(await StoreWithAsync(enabled: false), guard, new FixedResolver(_pid, SessionEndReason.Running, runningTicks: 0), observer: measuring)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.HeldUnhooked.Should().BeTrue();
measuring.Targets.Should().BeEmpty("a hold whose snapshot names no process announces nothing");
var held = new MeasuringRecorder();
await new CaptureSession(await StoreWithAsync(enabled: false), new HookedCaptureGate(guard), guard, resolver,
new DelegateLivenessSource(_ => new FakeLiveness()), new DelegateRingAttacher(_ => (null, ShmAttachRefusal.BuildIdMismatch)),
new CaptureOptions { HoldInterval = TimeSpan.FromMilliseconds(1), HoldUnhooked = true, MaxDuration = TimeSpan.FromSeconds(5) },
observer: held)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
held.Targets.Should().HaveCount(3, "the first set, the changed set, and none at the end — never a repeat of an unchanged set");
held.Targets[0].Processes.Should().Equal(one);
held.Targets[0].PinnedBy.Should().BeNull("nothing was pinned: each process is opened only for its read, by the reader");
held.Targets[1].Processes.Should().Equal(two);
held.Targets[2].IsNone.Should().BeTrue();
guard.InjectCalls.Should().Be(0);
}
[Fact]
public async Task TheOperatorHostTakesARefusalAsTheAnswer()
{
var guard = new CountingGuard { Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedDriver, "Riot Vanguard", "vgk.sys") };
using var alive = new FakeLiveness();
CaptureOutcome r = await With(await StoreWithAsync(), guard, new FixedResolver(_pid, SessionEndReason.Running), alive, hold: false)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedByGuard);
r.HeldUnhooked.Should().BeFalse("HoldUnhooked = false returns the refusal at once");
}
private const string _yidunBlock = "AntiCheatFile|NetEase Yidun|NEP2.dll";
/// <summary>
/// D33: the row as the owner's GIRLS' FRONTLINE 2 would be under its exception — consented, blocked for NetEase Yidun,
/// the exception granted on these bytes, and hooking turned on again through FR-2.1 — written through the real store.
/// </summary>
private async Task<IGameConsentStore> ExceptedStoreAsync()
{
CancellationToken ct = TestContext.Current.CancellationToken;
IGameConsentStore store = await StoreWithAsync().ConfigureAwait(false);
await store.RecordGuardBlockAsync(Fingerprint, AntiCheatVerdict.Refused(AntiCheatRefusalReason.AntiCheatFile, "NetEase Yidun", "NEP2.dll"), ct)
.ConfigureAwait(false);
(await store.GrantAntiCheatExceptionAsync(new AntiCheatExceptionGrantRequest
{
Fingerprint = Fingerprint,
Block = _yidunBlock,
Verdict = AntiCheatVerdict.AllowedUnderException("NetEase Yidun", "NEP2.dll"),
DisclosureVersion = "ac-exception-dialog/2",
GrantedAt = DateTimeOffset.UnixEpoch,
}, ct).ConfigureAwait(false)).Should().Be(ConsentWriteOutcome.Written);
(await store.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
{
Fingerprint = Fingerprint,
DisclosureVersion = _disclosure,
AcknowledgedAt = DateTimeOffset.UnixEpoch,
}, ct).ConfigureAwait(false)).Should().Be(ConsentWriteOutcome.Written);
GameConsentRecord record = await store.FindAsync(_exe, ct).ConfigureAwait(false);
record.HookEnabled.Should().BeTrue();
record.BlockedReason.Should().Be(_yidunBlock, "the exception is a layer over the block, never its clearing");
return store;
}
/// <summary>
/// D33 (owner decision 2026-09-26): under its exception the Overlay's channel is published BEFORE the injection — the
/// Overlay reads it before its loader detour exists — the injection and every re-scan name the family, and the channel
/// is let go with the session.
/// </summary>
[Fact]
public async Task UnderItsExceptionTheOverlayIsToldFirstAndEveryScanNamesTheFamily()
{
var events = new List<string>();
var guard = new CountingGuard
{
Verdict = AntiCheatVerdict.AllowedUnderException("NetEase Yidun", "NEP2.dll"),
EvaluateVerdict = AntiCheatVerdict.AllowedUnderException("NetEase Yidun", "NEP2.dll"),
Events = events,
};
using var sink = new FakeSink();
var channel = new FakeToleranceChannel(events);
CaptureSession loop = Loop(await ExceptedStoreAsync(), guard, sink, exceptions: new FakeExceptionSwitch(on: true), tolerance: channel);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.ExceptionFamily.Should().Be("NetEase Yidun");
r.AttachRefusal.Should().Be(ShmAttachRefusal.Ok);
channel.Published.Should().Equal((_pid, "NetEase Yidun"));
events.IndexOf("publish-tolerance").Should().BeLessThan(events.IndexOf("inject"), "a channel published after the injection is read by nobody");
guard.InjectTolerated.Should().Equal("NetEase Yidun");
guard.EvaluateTolerated.Should().NotBeEmpty().And.OnlyContain(static f => f == "NetEase Yidun");
channel.Disposed.Should().BeGreaterThan(0, "the channel is held for the session and let go with it");
}
[Fact]
public async Task WithTheOptionOffTheBlockedGameIsHookingOffAndItsProcessIsNeverOpened()
{
var guard = new CountingGuard();
var resolver = new FixedResolver(_pid, SessionEndReason.Running, runningTicks: 1);
var channel = new FakeToleranceChannel([]);
CaptureSession loop = With(await ExceptedStoreAsync(), guard, resolver, exceptions: new FakeExceptionSwitch(on: false), tolerance: channel);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Verdict.Reason.Should().Be(AntiCheatRefusalReason.PreviouslyBlocked, "off suspends the exception, and the block is what is left");
resolver.ResolveCalls.Should().Be(0, "hook_enabled is 1 only because the exception once applied; without it this is a hooking-off row");
guard.InjectCalls.Should().Be(0);
channel.Published.Should().BeEmpty();
r.ExceptionFamily.Should().BeNull();
}
[Fact]
public async Task ABlockedGameOnOtherBytesIsHookingOff()
{
var guard = new CountingGuard();
var resolver = new FixedResolver(_pid, SessionEndReason.Running, runningTicks: 1);
CaptureSession loop = With(await ExceptedStoreAsync(), guard, resolver, exceptions: new FakeExceptionSwitch(on: true), tolerance: new FakeToleranceChannel([]));
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint with { SizeBytes = 1 }, "payload.dll", TestContext.Current.CancellationToken);
r.Verdict.Reason.Should().Be(AntiCheatRefusalReason.PreviouslyBlocked, "a game update is not the file the user accepted the risk for");
guard.InjectCalls.Should().Be(0);
resolver.ResolveCalls.Should().Be(0);
}
/// <summary>A channel that could not be published is no exception: the guard is asked nothing, and the game is refused as blocked.</summary>
[Fact]
public async Task AChannelThatCannotBePublishedIsNoException()
{
var guard = new CountingGuard();
using var sink = new FakeSink();
var channel = new FakeToleranceChannel([], works: false);
CaptureSession loop = Loop(await ExceptedStoreAsync(), guard, sink, exceptions: new FakeExceptionSwitch(on: true), tolerance: channel);
CaptureOutcome r = await loop.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
channel.Published.Should().ContainSingle("it was tried");
r.Reason.Should().Be(SessionEndReason.RefusedPreviouslyBlocked);
guard.InjectCalls.Should().Be(0, "injecting while the Overlay would stop on the family's module would read as the exception failing");
r.ExceptionFamily.Should().BeNull();
}
/// <summary>
/// A finding about the game at the start of a session under the exception is written as the block, as every finding is,
/// and the outcome names the exception it ran under — the recorder's policy ends the exception on it.
/// </summary>
[Fact]
public async Task AStartTimeFindingUnderTheExceptionIsTheBlockAndEndsTheException()
{
var guard = new CountingGuard { Verdict = AntiCheatVerdict.Refused(AntiCheatRefusalReason.AntiCheatFile, "Kernel driver in the game folder", "NEPKernel.sys") };
using var sink = new FakeSink();
var channel = new FakeToleranceChannel([]);
IGameConsentStore store = await ExceptedStoreAsync();
CaptureOutcome r = await Loop(store, guard, sink, exceptions: new FakeExceptionSwitch(on: true), tolerance: channel)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Reason.Should().Be(SessionEndReason.RefusedByGuard);
r.HookingTurnedOff.Should().BeTrue();
r.ExceptionFamily.Should().Be("NetEase Yidun");
UserModeExceptionLapsePolicy.LapseOf(r, ExitStatus.Normal).Should().Be(UserModeExceptionLapse.NewFinding);
channel.Disposed.Should().BeGreaterThan(0);
(await store.FindAsync(_exe, TestContext.Current.CancellationToken)).BlockedReason.Should().Contain("NEPKernel.sys");
}
private static readonly ScreenRect _monitor = new(0, 0, 2560, 1440);
/// <summary>
/// beta.10 (<c>03_METRICS</c> §Display mode): a hooked session samples the display on every drain tick — region 4 for the
/// swap chain's own answer, the window by the handle region 4 names and the pid the loop holds — and the outcome carries
/// the tally the recorder writes.
/// </summary>
[Fact]
public async Task AHookedSessionTalliesTheDisplayFromRegionFourAndTheWindow()
{
IGameConsentStore store = await StoreWithAsync();
using var sink = new FakeSink
{
Display = new FlDisplayState
{
Flags = FlDisplayFlags.Sampled | FlDisplayFlags.ExclusiveKnown,
Hwnd = 0x1234,
BufferWidth = 2560,
BufferHeight = 1440,
SwapEffect = 4, // FLIP_SEQUENTIAL (3), stored plus one
SampleQpc = (ulong)Stopwatch.GetTimestamp(),
},
};
var probe = new RecordingProbe(new WindowView(false, _monitor, _monitor, 165));
CaptureOutcome r = await Loop(store, new CountingGuard(), sink, display: probe)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
probe.Calls.Should().NotBeEmpty().And.OnlyContain(static c => c.Hwnd == 0x1234 && c.Pids.Length == 1 && c.Pids[0] == _pid,
"the window is the one the swap chain presents to, checked against the process the loop holds");
r.Display.Should().NotBeNull();
r.Display!.BorderlessMs.Should().BeGreaterThan(0, "covering the monitor while the chain said not exclusive is borderless");
r.Display.ExclusiveMs.Should().Be(0);
r.Display.CoversMs.Should().Be(0, "the chain was asked, so the mode is not left undecided");
r.Display.Source.Should().Be(DisplaySource.SwapChain);
r.Display.SwapEffect.Should().Be("flip_sequential");
(r.Display.WindowWidth, r.Display.BufferWidth, r.Display.MonitorHz).Should().Be((2560, 2560u, 165));
}
/// <summary>
/// beta.10: a Tier-2 session has its display mode too — the window only, found by the executable's image path in the
/// watcher's snapshot for a hold that never opened the process, and never said to be exclusive or borderless.
/// </summary>
[Fact]
public async Task ATierTwoHoldTalliesTheWindowOfEveryProcessRunningTheExecutable()
{
var resolver = new FixedResolver(_pid, SessionEndReason.Running, runningTicks: 3, pids: [777, 778]);
var probe = new RecordingProbe(new WindowView(false, _monitor, _monitor, 60));
CaptureOutcome r = await With(await StoreWithAsync(enabled: false), new CountingGuard(), resolver, display: probe)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.HeldUnhooked.Should().BeTrue();
probe.Calls.Should().HaveCount(3).And.OnlyContain(static c => c.Hwnd == 0 && c.Pids.SequenceEqual(new[] { 777, 778 }),
"nothing was injected to name a window, so every process running the executable is looked at, once per held tick");
r.Display.Should().NotBeNull();
r.Display!.ExclusiveMs.Should().Be(0, "exclusive fullscreen is the swap chain's answer, and nothing asked it");
r.Display.BorderlessMs.Should().Be(0);
r.Display.WindowedMs.Should().Be(0);
r.Display.Source.Should().Be(DisplaySource.Window);
r.Display.ExclusivityKnown.Should().BeFalse();
r.Display.Dominant.Should().Be(DisplayMode.CoversScreen, "a window covering its monitor that nothing could ask about is fullscreen OR borderless");
r.Display.MonitorHz.Should().Be(60);
}
[Fact]
public async Task WithoutAProbeNoDisplayIsRecorded()
{
using var sink = new FakeSink();
CaptureOutcome r = await Loop(await StoreWithAsync(), new CountingGuard(), sink)
.RunAsync(_exe, Fingerprint, "payload.dll", TestContext.Current.CancellationToken);
r.Display.Should().BeNull("the operator host composes no window reader, and an absent reader is not a session without a window");
}
}