feat(ipc): the command pipe, command half -- SetWatchlist, LaunchGame, SetHookEnabled (pre-scan, no stamp yet), pause/resume, StopSession, UpdateRules, Shutdown (P3 PR-1b) (#154)
07_IPC §Messages' UI->Agent rows, built under the one rule of §The pipe is not a
trust boundary: the Agent establishes each fact itself. Application.Ipc.AgentCommandHandler:
- SetHookEnabled false revokes through the store. SetHookEnabled true runs the static
pre-scan of the executable's directory, records a block or a "could not verify"
through RecordGuardBlockAsync and answers Refused { reason, family?, signal? }, and
answers a clean scan `Error DisclosureUnavailable` with NOTHING stamped -- FR-2.1's
reviewed text does not exist (PR-4), and a client's disclosureVersion is a claim,
not a disclosure shown.
- SetWatchlist ensures identity rows (hooking off when new) and removes nothing;
UpdateRules is the seeder's outcome and ignores any payload; Shutdown asks
IAgentLifetime (the host's under --serve, a logged no-op under --console).
- PauseCapture/ResumeCapture flip CapturePause, one in-memory flag every session
loop reads at its tick and tells the ring once per transition -- supervision never
pauses; StatusAck gains `paused`.
- StopSession cancels the session's OWN stop token (RecordRequest.StopToken; the
orchestrator now names every session it starts, RecordRequest.SessionGuid), which
the loop reads at its next tick and ends as the new SessionEndReason.StoppedByUser:
drained once more, finalized, exit_status normal, the target left running.
- LaunchGame is CaptureOrchestrator.LaunchAsync over the new ILaunchRecorderFactory
(the Agent's AgentLaunches: the Vulkan layer's environment unless the kill switch
is on, the console's `launch` shape), one session per game, the election after.
The orchestrator's running-session table has one lock now that the pipe's tasks
reach it (HANDOFF §P3 D12 as built: no Channel). IExecutableIdentitySource gains
Normalise. AgentRequestHandler resolves the command handler lazily: eagerly it is a
DI cycle (server -> handler -> commands -> orchestrator -> recorder -> observer ->
publisher -> server) that hung the first e2e run, measured and recorded.
Tests: AgentCommandHandlerTests (real SQLite consent store: the block recorded,
nothing stamped, a path in an UpdateRules payload ignored), CaptureSessionTests (a
stop token ends as StoppedByUser with the last drain run; the pause told once per
transition while the guard keeps scanning), CaptureOrchestratorTests (stop cancels
the request's own token; launch once per game, refused for what it cannot name, the
environment released with the session), ExitStatusMapper / RecordedSessionEvents
rows for StoppedByUser, and PipeEndToEndTests grows two scenarios over the real
composition and a real ring: watched -> narrated -> paused (status says so, state
stays capturing) -> resumed -> stopped by guid (StoppedByUser, normal, harness alive)
-> the session-less commands incl. a real pre-scan answered DisclosureUnavailable;
and LaunchGame starting the harness in launch mode, narrated to TargetExited.
Docs: 07_IPC §Messages (each command row as built), 04_CAPTURE (watcher row, the
user stop), 01_ARCHITECTURE, HANDOFF §P3 (row 1b landed, D12 as built), CHANGELOG.
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
9c8c4ec099
commit
bf3e9f22ba
39 files changed
+1639
-146
No files matched your search
@@ -19,6 +19,39 @@ GitHub release body, so a missing section will mean an empty release note.
|
||||
|
||||
### Added
|
||||
|
||||
- **P3 PR-1b — the command pipe, command half: `SetWatchlist`, `LaunchGame`, `SetHookEnabled` (pre-scan, no stamp
|
||||
yet), pause/resume, `StopSession`, `UpdateRules`, `Shutdown` (2026-09-13).** `Application.Ipc.AgentCommandHandler`
|
||||
answers every UI → Agent row of `07_IPC` §Messages under the one rule of §The pipe is not a trust boundary — the
|
||||
Agent establishes each fact itself. `SetHookEnabled false` revokes through the store; `SetHookEnabled true` runs
|
||||
the static pre-scan of the executable's directory, records a block or a "could not verify" through
|
||||
`RecordGuardBlockAsync` and answers `Refused { reason, family?, signal? }`, and answers a clean scan **`Error
|
||||
DisclosureUnavailable` with nothing stamped** — FR-2.1's reviewed text does not exist (PR-4), and a client's
|
||||
`disclosureVersion` is a claim, not a disclosure shown. `SetWatchlist` ensures identity rows (hooking off when
|
||||
new) and removes nothing; `UpdateRules` is the seeder's outcome and ignores any payload; `Shutdown` asks
|
||||
`IAgentLifetime` (the host's under `--serve`, a logged no-op under `--console`). `PauseCapture`/`ResumeCapture`
|
||||
flip `CapturePause`, one in-memory flag every session loop reads at its tick and tells the ring once per
|
||||
transition — supervision never pauses — and `StatusAck` gains `paused`. `StopSession` cancels the session's own
|
||||
stop token (`RecordRequest.StopToken`; the orchestrator now names every session it starts, `RecordRequest.SessionGuid`),
|
||||
which the loop reads at its next tick and ends as the new `SessionEndReason.StoppedByUser`: drained once more,
|
||||
finalized, `exit_status = normal`, the target left running. `LaunchGame` is `CaptureOrchestrator.LaunchAsync`
|
||||
over the new `ILaunchRecorderFactory` (the Agent's `AgentLaunches`: the Vulkan layer's environment unless the
|
||||
kill switch is on, the console's `launch` shape), one session per game, the launcher election after. The
|
||||
orchestrator's running-session table has one lock now that the pipe's tasks reach it (HANDOFF §P3 D12 as built:
|
||||
no `Channel`). `IExecutableIdentitySource` gains `Normalise`, so a client's spelling is never a key. In the gate:
|
||||
`AgentCommandHandlerTests` (over the real SQLite consent store: the block recorded, nothing stamped, a path in
|
||||
an `UpdateRules` payload ignored), `CaptureSessionTests` (a stop token ends as `StoppedByUser` with the last drain
|
||||
run; the pause told once per transition while the guard keeps scanning), `CaptureOrchestratorTests` (stop
|
||||
cancels the request's own token; launch once per game, refused for what it cannot name, the environment
|
||||
released with the session), and `PipeEndToEndTests` grows two scenarios over the real Agent composition and a
|
||||
real ring: the watched harness narrated → paused (status says so, state stays `capturing`) → resumed → stopped
|
||||
by guid (`StoppedByUser`, `normal`, harness still alive) → the session-less commands, including a real pre-scan
|
||||
answered `DisclosureUnavailable`; and `LaunchGame` starting the harness in launch mode and narrating it to
|
||||
`TargetExited`. **Measured on the way:** wiring the command handler into the request handler eagerly is a DI
|
||||
cycle (server → handler → commands → orchestrator → recorder → observer → publisher → server) that the
|
||||
container did not refuse and the first e2e run HUNG on (`--blame-hang` dump, 2026-09-13); the command handler is
|
||||
resolved lazily on the first command, and the e2e now writes the composition's Serilog lines to its scratch
|
||||
directory so the next hang leaves evidence. **Not in this PR:** the consent stamp (PR-4) and the App (PR-2).
|
||||
|
||||
- **P3 PR-1 — the command pipe, read half: `Shared.Ipc`, the Agent's pipe server, the session narration and the
|
||||
1 Hz live progress (2026-09-13).** `FrameLedger.Shared.Ipc` holds channel C's contract (`07_IPC` §C): the
|
||||
envelope, the read-half message set (`Hello`/`HelloAck`, `GetStatus`/`StatusAck`, `Ping`/`Pong`, `Error`, and
|
||||
|
||||
@@ -42,7 +42,9 @@
|
||||
> **The pipe's read half is built 2026-09-13 (P3 PR-1):** `--serve` listens on `\\.\pipe\FrameLedger.v2`,
|
||||
> answers `Hello` / `GetStatus` / `Ping`, and narrates every session (`SessionStarted` at the attach, `SessionProgress`
|
||||
> at 1 Hz, the safety and error events, `SessionCompleted`); `--console` still prints and hosts no pipe. The
|
||||
> command half — the messages a client sends to change a state — is PR-1b, and the App that connects is PR-2.
|
||||
> command half — the messages a client sends to change a state — ~~is PR-1b~~ is built the same day (PR-1b:
|
||||
> `SetWatchlist`, `LaunchGame`, `SetHookEnabled` with the pre-scan and no stamp until PR-4, pause/resume,
|
||||
> `StopSession`, `UpdateRules`, `Shutdown`), and the App that connects is PR-2.
|
||||
|
||||
## Why this shape
|
||||
|
||||
|
||||
+2
-1
@@ -252,7 +252,7 @@ What the Agent checks **before** asking the guard is the thing the native side s
|
||||
|---|---|---|---|
|
||||
| **Session loop** (`CaptureSession.RunAsync`, one async loop per session) | `Task.Delay(100 ms)` drain ticks; the 30 s guard scan is awaited inline | The ring reader, for the life of the session — drain, `PublishGuardResult`, `SetPaused`, `RequestLogFlush` — and the record buffer it fills | Samples foreground per tick, drains the telemetry queue per tick (PR-D), writes `.partial` itself (PR-D) |
|
||||
| **Telemetry** (`fl-telemetry`, `TelemetryPoller`, one per session) | 1 Hz, never faster than 500 ms | Its own `ConcurrentQueue` of `TelemetrySample` | Reads the composite source only; L2 has a thread of its own inside the library, and the composite is read from this thread and no other |
|
||||
| **Watcher** (built 2026-09-10, PR-F: `CaptureOrchestrator.RunAsync` on a `PeriodicTimer(1 s)`) | 1 Hz process snapshot | The watcher's events and the running-session table — `PollOnceAsync` is their only writer; there is no `Channel`, because there is no second consumer | The `games` rows (one read per poll) and never the ring; each session it starts runs on its own task |
|
||||
| **Watcher** (built 2026-09-10, PR-F: `CaptureOrchestrator.RunAsync` on a `PeriodicTimer(1 s)`) | 1 Hz process snapshot | The watcher's events and the running-session table — ~~`PollOnceAsync` is their only writer; there is no `Channel`, because there is no second consumer~~ **since 2026-09-13 (P3 PR-1b) the table has one lock**: `PollOnceAsync` on the timer, `LaunchAsync` and `StopSession` from the pipe's tasks (HANDOFF §P3 D12 as built — two commands do not justify a channel); the sessions themselves never take it | The `games` rows (one read per poll) and never the ring; each session it starts runs on its own task |
|
||||
| **Finalize** (PR-D) | Once, on the session loop's task | The one SQLite connection, behind a `SemaphoreSlim(1)` | `ApplicationStopping` cancels the loop; finalize gets a grace window, then the `.partial` stays for recovery |
|
||||
| **Pipe** (built 2026-09-13, P3 PR-1: `PipeServer.RunAsync` accepting, one reader and one writer task per client) | Per frame | Each client's bounded outbound queue (drop-oldest, so a publisher never waits) and the answer to each request | `Hello` / `GetStatus` / `Ping` read `AgentStatus`, an immutable snapshot the publisher swaps whole; **never the ring, never the recorder**. The events themselves are handed over ON the session loop's task by `SessionEventPublisher` (`ISessionObserver`, called after the recorder's own work each tick) — the loop enqueues a frame and returns |
|
||||
|
||||
@@ -338,6 +338,7 @@ because a layer cannot leave a running game's loader chain.
|
||||
- `unhooked_safety`: the guard fired mid-session.
|
||||
- `degraded`: Overlay self-disabled after faults, or ring layout mismatch mid-session.
|
||||
- `interrupted`: Agent died mid-session; recovered from `.partial` on next start.
|
||||
- A **user stop** (FR-3.6; `StopSession` over the pipe, P3 PR-1b) is `normal`: the loop ends as `SessionEndReason.StoppedByUser` at its next tick, drains once more and finalizes; the target keeps running, unhooked from here. It is the session's own stop token, not the host's cancellation — the latter leaves a `.partial`.
|
||||
|
||||
Crash-within-60s-of-injection happening twice for the same game ⇒ **hooking auto-disabled for that game** and the reason stored on the `games` row (`19_SAFETY` §Crash safety). The UI explains it and offers a manual re-enable after the user has, e.g., updated their GPU driver.
|
||||
|
||||
|
||||
+15
-9
@@ -274,9 +274,15 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
|
||||
> the server under `--serve` only — `--console` composes it and never starts it, so it publishes to nobody.
|
||||
> The events come from `Application.Ipc.SessionEventPublisher`, the recorder's second observer
|
||||
> (`ISessionObserver`), on each session's own task; `SessionProgress` is computed once a second and only
|
||||
> while a client is connected. **The command half — `SetWatchlist`, `SetHookEnabled`, `LaunchGame`,
|
||||
> while a client is connected. ~~**The command half — `SetWatchlist`, `SetHookEnabled`, `LaunchGame`,
|
||||
> `PauseCapture`/`ResumeCapture`, `StopSession`, `UpdateRules`, `Shutdown` — is PR-1b**: none of those types
|
||||
> is declared in `Shared.Ipc` until its handler exists, and the Agent answers them `Error UnknownType` today.
|
||||
> is declared in `Shared.Ipc` until its handler exists, and the Agent answers them `Error UnknownType` today.~~
|
||||
> **The command half is built the same day (P3 PR-1b): `Application.Ipc.AgentCommandHandler`**, every row
|
||||
> below with its ack, and the one rule §The pipe is not a trust boundary states is what each handler does —
|
||||
> the Agent establishes the fact itself. Two things a reader must not assume: `SetHookEnabled true` **stamps
|
||||
> nothing yet** (the pre-scan runs, a block is recorded, and a clean scan is answered `Error
|
||||
> DisclosureUnavailable` until FR-2.1's reviewed text ships in PR-4), and `SetWatchlist` **removes nothing**
|
||||
> (removal is FR-1.4's, with its "keep the sessions?" question — never a bulk message's).
|
||||
|
||||
- Message mode, single server (Agent), max 2 clients (UI + future CLI), `PIPE_REJECT_REMOTE_CLIENTS`. *(Built:
|
||||
`CreateNamedPipe` through CsWin32 with these flags stated in code, two instances, a semaphore slot per client
|
||||
@@ -302,13 +308,13 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
|
||||
|---|---|---|
|
||||
| `Hello` | UI→A | `{ appVersion, protocol: 2 }` → `HelloAck { agentVersion, protocol, pid, elevated, overlayBuildId, vulkanLayerRegistered, telemetrySource /* composite, e.g. l1+lhm+nvapi */, cpuTempAvailable, ~~etwAvailable~~ }` — `etwAvailable` struck 2026-09-13 with the tier it described (2026-08-28); `pid` added. `vulkanLayerRegistered` is **false by construction** today (the layer is per-launch, never registered) and `cpuTempAvailable` false unelevated; `telemetrySource` is the composite stood up once on the first `Hello` |
|
||||
| `GetStatus` | UI→A | → `StatusAck { state, activeSession?, tier? }` |
|
||||
| `SetWatchlist` | UI→A | `{ entries: [{ gameId, exePath }] }` — full replace; UI re-sends on connect. **Carries no hooking state** (see §The pipe is not a trust boundary) |
|
||||
| `LaunchGame` | UI→A | `{ gameId }` → suspended-launch + inject path (`04_CAPTURE` §Launch mode) |
|
||||
| `SetHookEnabled` | UI→A | `{ gameId, enabled }` — Agent re-runs the static AC pre-scan and may reply `Refused`. **The Agent stamps the consent timestamp itself** |
|
||||
| `PauseCapture` / `ResumeCapture` | UI→A | global |
|
||||
| `StopSession` | UI→A | `{ sessionGuid }` — graceful unhook + finalize |
|
||||
| `UpdateRules` | UI→A | **no payload** — a trigger, not a source. The Agent re-reads only its own `%LOCALAPPDATA%\FrameLedger\rules\` copy |
|
||||
| `Shutdown` | UI→A | graceful stop |
|
||||
| `SetWatchlist` | UI→A | `{ entries: [{ gameId?, exePath }] }` — ~~full replace~~ **ensure, never remove** (built 2026-09-13, PR-1b): each entry's path is normalised by the Agent, its row ensured with hooking OFF when new, and the ack is `WatchlistAck { games: [{ gameId, exePath, name }], unreadable: [exePath] }`; `gameId` in a request is a hint and never trusted over the path. UI re-sends on connect. **Carries no hooking state** (see §The pipe is not a trust boundary). *Since the App writes `games` rows itself under `06_DATA_MODEL` §Writer ownership (HANDOFF §P3 D15), this is the pipe's way of adding a row, not the only one; the watcher reads the table at 1 Hz either way.* |
|
||||
| `LaunchGame` | UI→A | `{ gameId, arguments? }` → ~~suspended-launch~~ launch mode as built ("inject late", `04_CAPTURE` §Launch mode) → `LaunchAck { gameId, accepted, outcome, sessionGuid? }` — `outcome` is `Accepted` · `UnknownGame` · `SessionRunning` (one per game at a time) · `Unavailable`. *(Built 2026-09-13, PR-1b: `CaptureOrchestrator.LaunchAsync` over an `ILaunchRecorderFactory` the Agent composes with the Vulkan layer's environment — or none when FR-2.4's switch is on — and the launcher election runs after, as the console's `launch` does; the elected session is not addressable by the launch's guid.)* |
|
||||
| `SetHookEnabled` | UI→A | `{ gameId, enabled, disclosureVersion? }` — Agent re-runs the static AC pre-scan and may reply `Refused`. **The Agent stamps the consent timestamp itself.** *(Built 2026-09-13, PR-1b, as far as it can be: `enabled: false` → `RevokeAsync` → `HookEnabledAck { gameId, enabled: false, outcome }`; `enabled: true` → the pre-scan of the executable's directory, a refusal or a "could not verify" recorded through `RecordGuardBlockAsync` and answered `Refused { gameId, reason, family?, signal? }`; a clean scan → **`Error DisclosureUnavailable`, nothing stamped** — the reviewed FR-2.1 text does not exist, and a client's `disclosureVersion` is a claim, not a disclosure shown. PR-4 replaces that last branch with the stamp: the Agent's own version compared, its own clock, `ConsentProvenance.ConsentDialog`.)* |
|
||||
| `PauseCapture` / `ResumeCapture` | UI→A | global → `PauseAck { paused }`; `StatusAck.paused` reports it. *(Built 2026-09-13, PR-1b: one in-memory flag, `CapturePause`, read by every session loop at its tick and told to the ring once per transition; supervision — the guard scan, the kill switch, the safety stop — never pauses. Not persisted: an Agent that restarts resumes.)* |
|
||||
| `StopSession` | UI→A | `{ sessionGuid }` — graceful ~~unhook~~ stop + finalize → `StopAck { sessionGuid, accepted, reason? }`. *(Built 2026-09-13, PR-1b: the orchestrator names every session it starts and cancels THAT session's stop token; the loop reads it at its next tick, drains once more, and ends as `SessionEndReason.StoppedByUser` — `exit_status = normal`, the row stored like any other, the target left running. A guid nobody runs is `accepted: false`. Distinct from the host's cancellation, which leaves a `.partial`.)* |
|
||||
| `UpdateRules` | UI→A | **no payload** — a trigger, not a source. The Agent re-reads only its own `%LOCALAPPDATA%\FrameLedger\rules\` copy → `UpdateRulesAck { outcome }`. *(Built 2026-09-13, PR-1b: the seeder's `EnsureSeededAsync` outcome; a payload naming a path is ignored, and a test sends one to prove it.)* |
|
||||
| `Shutdown` | UI→A | graceful stop → `ShutdownAck`, then the host stops (sessions finalize inside its grace window). *(Built 2026-09-13, PR-1b: `IAgentLifetime`, the host's under `--serve`, a logged no-op under `--console`.)* |
|
||||
| `SessionStarted` | A→UI | `{ sessionGuid, gameId, gameName, pid, tier, startedAt }` — **published at the attach**, i.e. when the session becomes Tier 1 and the live card has something to show; a session that never attaches has no `SessionStarted`, only its `SessionCompleted` (tier 2) and, when a refusal or error caused that, the event below that names it |
|
||||
| `SessionProgress` | A→UI | 1 Hz: `{ sessionGuid, elapsedS, presents5s, presentedFps5s?, presentedQualifier, nativeFps5s?, displayedFps5s?, fgFactor?, fgMode, upscaler?, upscalerQuality?, renderW/H?, outputW/H?, rtActive?, gpuTempC?, cpuTempC?, vramProcMb?, latencyUs? }` — a 5 s rolling window over the ring through the SAME Domain calculators the row uses (`SessionProgressCalculator`, D13). **Rule 6 at the wire (2026-09-13):** `nativeFps5s` / `displayedFps5s` / `fgFactor` are present only when frame generation was measured in the window; otherwise `presentedFps5s` stands alone with `presentedQualifier` (`census_not_run` · `no_fg_runtime` · `fg_runtime_loaded` · `none_withheld`, the row's `presented_qualifier` from the same function). Every unmeasured field is absent, never 0. Suppressed when no client is connected |
|
||||
| `SessionCompleted` | A→UI | `{ sessionGuid, sessionId?, exitStatus, tier, finalize, reason }` — UI loads the full row from SQLite; `sessionId` is null and `finalize` is `discarded` when the row was not stored (under the minimum length); `exitStatus` is the row's vocabulary (`normal` · `crashed` · `unhooked_safety` · `degraded`); `reason` is the loop's `SessionEndReason` |
|
||||
|
||||
+7
-2
@@ -1249,7 +1249,7 @@ because a criterion already true on `main` is decoration.
|
||||
|---|---|---|
|
||||
| 0 | P2 sweep: the doc/tool drift PR-G left (`coverage-gate.ps1` prose, `13_CI_CD`'s count and its signer-probe claim, `09_I18N`'s member count, `17_HOOK_ENGINE`'s §H9 cite, this file's D-labels, `ci.yml`'s census comment), this head, the roadmap amendment | `grep -n "exactly two members" docs/09_I18N.md` matched; `§H9` resolved to nothing; two START HEREs |
|
||||
| ~~1~~ | ~~**The pipe, read half**: `Shared.Ipc` contracts + `JsonSerializerContext`; the Agent's `PipeServerHostedService`; `Hello`/`HelloAck`, `GetStatus`/`StatusAck`, `Ping`/`Pong`; the events (`SessionStarted`/`Progress`/`Completed`/`CaptureRefused`/`CaptureDegraded`/`SafetyUnhook`/`CaptureError`); a 1 Hz `SessionProgress` publisher; `Infrastructure.Ipc.PipeClient`~~ **LANDED 2026-09-13** — status in `CHANGELOG.md`; `07_IPC` §C carries what was built and the one deviation (`etwAvailable` struck) | ~~`grep -rn NamedPipeServerStream src` is empty; `FrameLedger.Shared` holds no JSON type; `04_CAPTURE` §Live progress has no producer~~ |
|
||||
| 1b | **The pipe, command half**: `SetWatchlist` (identity only), `SetHookEnabled` (the Agent re-scans and stamps), `LaunchGame`, `PauseCapture`/`ResumeCapture`, `StopSession`, `UpdateRules` (a trigger, no payload), `Shutdown` | the Agent accepts no command from outside; `CaptureOrchestrator` has no stop/pause surface; `SetHookEnabled` has no handler |
|
||||
| ~~1b~~ | ~~**The pipe, command half**: `SetWatchlist` (identity only), `SetHookEnabled` (the Agent re-scans and stamps), `LaunchGame`, `PauseCapture`/`ResumeCapture`, `StopSession`, `UpdateRules` (a trigger, no payload), `Shutdown`~~ **LANDED 2026-09-13** — status in `CHANGELOG.md`; `07_IPC` §Messages carries each row as built. **One thing stayed with PR-4 on purpose:** `SetHookEnabled true` stamps nothing — the pre-scan runs and a block is recorded, then `Error DisclosureUnavailable` — because the reviewed text it would stamp against does not exist, and a member no code can produce is the §S29(c) shape | ~~the Agent accepts no command from outside; `CaptureOrchestrator` has no stop/pause surface; `SetHookEnabled` has no handler~~ |
|
||||
| 2 | **resx + the App shell**: `Strings.resx` en/vi/ja for App and Shared, the generated class, `tools/resx-audit.ps1` (+`-SelfTest`) as `build.ps1` step 15; the Generic Host bootstrap, `FluentWindow`, TitleBar/Menu/NavigationView, theme + persistence, `INavigationService`, Serilog `ui-*.log`, five empty pages, the Agent status pill over `Hello`, auto-start of `--serve` on connect failure; `tests/FrameLedger.App.Tests` | `find . -name '*.resx'` is empty; step 15 prints "skipped loudly"; `App.xaml` uses `StartupUri` and `MainWindow` is a plain `Window` |
|
||||
| 2b *(owner decides)* | `FL_MOCK=1` / `Agent --serve --mock`, `--data-dir` only: a `MockSessionSource` hosted service that emits pipe events and inserts synthesised sessions through `ISessionRepository` — and can never resolve `HookedCaptureGate` (asserted) | CLAUDE.md says "specified but not implemented"; `grep FL_MOCK src` is empty |
|
||||
| 3 | **Ports the UI reads and writes**: `ISessionRepository.ListByGameAsync` / segments / sensors, `ISessionAnnotationRepository`, `ILegalAcceptanceStore.RecordAsync`, `IGameRepository.UpdateMetadataAsync` / `RemoveAsync`, the **settings registry** (closes §G's row — D16 below), `IRtOverrideRepository` (FR-8.3), `display_res`/`display_hz` producer; tests for the four PR-B adapters that have none | no port lists sessions by game; `session_annotations` has no repository; `legal_acceptance` has no writer; `ISettingsStore`'s own doc calls the registry open |
|
||||
@@ -1287,7 +1287,12 @@ charts (6) after Games (5) because the summary opens from the Sessions tab; Sett
|
||||
is: the static pre-scan (`RecordGuardBlockAsync` on a block) → `RecordOperatorAcknowledgementAsync` with
|
||||
`Provenance = ConsentDialog`, the disclosure version from the Agent's own copy of the string, and
|
||||
`AcknowledgedAt` from the Agent's clock. A client can request; it cannot attest (`07_IPC` §The pipe is not a
|
||||
trust boundary).
|
||||
trust boundary). *(As built 2026-09-13, PR-1b: **no `Channel` and no `PipeCommandHostedService`** — the
|
||||
handler runs on the pipe client's reader task and the orchestrator's running-session table gained one lock;
|
||||
two commands did not justify a queue and a second place a start can wait. The pause is `CapturePause`, read by
|
||||
the loop at each tick and told to the ring once per transition. The stop is the session's own token in
|
||||
`RecordRequest`, ending the loop as `StoppedByUser`. The stamp branch is PR-4's, exactly as written above;
|
||||
until then it answers `DisclosureUnavailable`.)*
|
||||
- **D13 — `SessionProgress` is a third `ICaptureObserver`.** `ProgressPublisher` in `AgentRecording`,
|
||||
rate-limited to 1 Hz inside `Tick`, snapshots the live lists there and never holds them; `nativeFps5s` /
|
||||
`displayedFps5s` / `fgFactor` come from Domain's calculators over the last 5 s of records through
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Infrastructure.Capture;
|
||||
using FrameLedger.Infrastructure.Vulkan;
|
||||
|
||||
namespace FrameLedger.Agent.Composition;
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode for the pipe's <c>LaunchGame</c> (P3 PR-1b): the same environment the console's <c>launch</c>
|
||||
/// verb builds — the Vulkan layer's variables unless FR-2.4's switch is on (decision D7: the switch is honoured
|
||||
/// by NOT setting the enable variable) — and a recorder over it, unbounded, with the product's minimum length.
|
||||
/// </summary>
|
||||
internal sealed class AgentLaunches(AgentRecording recording, IKillSwitch killSwitch, AgentPaths paths) : ILaunchRecorderFactory
|
||||
{
|
||||
public async ValueTask<ILaunchRecording> PrepareAsync(string normalisedExePath, CancellationToken ct = default)
|
||||
{
|
||||
bool engaged = await killSwitch.IsEngagedAsync(ct).ConfigureAwait(false);
|
||||
VkLayerLaunchEnvironment? vulkan = engaged ? null : VkLayerLaunchEnvironment.Prepare(normalisedExePath, AgentPaths.VkLayerDll, paths.VkLayerDirectory);
|
||||
string description = engaged
|
||||
? "vulkan layer: NOT enabled - the global kill switch is on (FR-2.4), so the launched process gets no layer environment"
|
||||
: vulkan!.ManifestPath is null
|
||||
? "vulkan layer: NOT staged beside this binary - a Vulkan title will present unobserved"
|
||||
: $"vulkan layer: {vulkan.ManifestPath} (via {VkLayerLaunchEnvironment.ImplicitLayerPathVariable}; enable-list entry '{vulkan.ImageName}' for this session)";
|
||||
var launcher = new ProcessLauncher(vulkan?.Variables, enableVulkanLayer: !engaged);
|
||||
return new Recording(recording.Recorder(seconds: 0, launcher), vulkan, description);
|
||||
}
|
||||
|
||||
private sealed class Recording(ISessionRecorder recorder, VkLayerLaunchEnvironment? vulkan, string description) : ILaunchRecording
|
||||
{
|
||||
public ISessionRecorder Recorder { get; } = recorder;
|
||||
|
||||
public string Description { get; } = description;
|
||||
|
||||
public void Dispose() => vulkan?.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ internal sealed class AgentRecording
|
||||
private readonly SessionFinalizer _finalizer;
|
||||
private readonly ICrashEventSource _crashes;
|
||||
private readonly ISessionObserver _observer;
|
||||
private readonly CapturePause _pause;
|
||||
|
||||
public AgentRecording(
|
||||
IGameConsentStore store,
|
||||
@@ -49,7 +50,8 @@ internal sealed class AgentRecording
|
||||
IPartialSessionStore partials,
|
||||
SessionFinalizer finalizer,
|
||||
ICrashEventSource crashes,
|
||||
ISessionObserver observer)
|
||||
ISessionObserver observer,
|
||||
CapturePause pause)
|
||||
{
|
||||
_store = store;
|
||||
_gate = gate;
|
||||
@@ -67,6 +69,7 @@ internal sealed class AgentRecording
|
||||
_finalizer = finalizer;
|
||||
_crashes = crashes;
|
||||
_observer = observer;
|
||||
_pause = pause;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -156,7 +159,8 @@ internal sealed class AgentRecording
|
||||
_ngx,
|
||||
launcher,
|
||||
observer,
|
||||
_killSwitch);
|
||||
_killSwitch,
|
||||
_pause);
|
||||
|
||||
/// <summary>The session and its collaborators, wired the only way the Agent allows; the recorder supplies the observer.</summary>
|
||||
private sealed class Factory(AgentRecording owner, int seconds, IProcessLauncher? launcher) : ICaptureSessionFactory
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using FrameLedger.Agent.Hosting;
|
||||
using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Ipc;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Rules;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Infrastructure.AntiCheat;
|
||||
using FrameLedger.Infrastructure.Blobs;
|
||||
@@ -11,11 +13,13 @@ using FrameLedger.Infrastructure.Capture;
|
||||
using FrameLedger.Infrastructure.Ipc;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using FrameLedger.Infrastructure.Recording;
|
||||
using FrameLedger.Infrastructure.Rules;
|
||||
using FrameLedger.Infrastructure.Settings;
|
||||
using FrameLedger.Infrastructure.Telemetry;
|
||||
using FrameLedger.Infrastructure.Watch;
|
||||
using FrameLedger.Shared.Ipc;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
namespace FrameLedger.Agent.Composition;
|
||||
|
||||
@@ -99,10 +103,24 @@ internal static class AgentServices
|
||||
private static void AddPipe(IServiceCollection services, string? pipeName)
|
||||
{
|
||||
services.AddSingleton(new PipeServerOptions { PipeName = pipeName ?? IpcProtocol.PipeName });
|
||||
// The command half (PR-1b). The pause is the one global flag every session reads; the lifetime is the
|
||||
// host's under --serve and a logged no-op under --console (TryAdd: --serve registers its own first).
|
||||
services.AddSingleton<CapturePause>();
|
||||
services.TryAddSingleton<IAgentLifetime, NoAgentLifetime>();
|
||||
services.AddSingleton(static sp => new AgentCommandHandler(
|
||||
sp.GetRequiredService<IGameRepository>(),
|
||||
sp.GetRequiredService<IGameConsentStore>(),
|
||||
sp.GetRequiredService<IAntiCheatGuard>(),
|
||||
sp.GetRequiredService<IExecutableIdentitySource>(),
|
||||
sp.GetRequiredService<CaptureOrchestrator>(),
|
||||
sp.GetRequiredService<CapturePause>(),
|
||||
sp.GetRequiredService<IAgentLifetime>(),
|
||||
static async ct => (await new RulesSeeder(new FileSystemRulesStore()).EnsureSeededAsync(ct).ConfigureAwait(false)).ToString()));
|
||||
services.AddSingleton<IIpcRequestHandler>(static sp => new AgentRequestHandler(
|
||||
AgentIdentityFactory.OfThisProcess(),
|
||||
TelemetryDescriptor(),
|
||||
() => sp.GetRequiredService<SessionEventPublisher>().Status));
|
||||
() => sp.GetRequiredService<SessionEventPublisher>().Status,
|
||||
() => sp.GetRequiredService<AgentCommandHandler>()));
|
||||
services.AddSingleton(static sp => new PipeServer(
|
||||
sp.GetRequiredService<PipeServerOptions>(),
|
||||
sp.GetRequiredService<IIpcRequestHandler>(),
|
||||
@@ -116,7 +134,9 @@ internal static class AgentServices
|
||||
sp.GetRequiredService<IProcessSnapshotSource>(),
|
||||
sp.GetRequiredService<IExecutableIdentitySource>(),
|
||||
new OrchestratorOptions { PayloadPath = AgentPaths.Payload },
|
||||
static line => Serilog.Log.Information("{Line}", line)));
|
||||
static line => Serilog.Log.Information("{Line}", line),
|
||||
sp.GetRequiredService<ILaunchRecorderFactory>()));
|
||||
services.AddSingleton<ILaunchRecorderFactory, AgentLaunches>();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
using FrameLedger.Application.Ipc;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Serilog;
|
||||
|
||||
namespace FrameLedger.Agent.Hosting;
|
||||
|
||||
/// <summary><c>Shutdown</c> under <c>--serve</c>: the host stops, sessions finalize inside its grace window.</summary>
|
||||
internal sealed class HostAgentLifetime(IHostApplicationLifetime host) : IAgentLifetime
|
||||
{
|
||||
public void RequestShutdown()
|
||||
{
|
||||
Log.Information("pipe: Shutdown requested by a client; stopping the host");
|
||||
host.StopApplication();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using FrameLedger.Application.Ipc;
|
||||
using Serilog;
|
||||
|
||||
namespace FrameLedger.Agent.Hosting;
|
||||
|
||||
/// <summary>Under <c>--console</c> there is no host to stop; the request is logged and nothing else happens.</summary>
|
||||
internal sealed class NoAgentLifetime : IAgentLifetime
|
||||
{
|
||||
public void RequestShutdown() => Log.Information("pipe: Shutdown requested, but this process hosts no service (--console); ignored");
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
using FrameLedger.Agent.Cli;
|
||||
using FrameLedger.Agent.Composition;
|
||||
using FrameLedger.Agent.Hosting;
|
||||
using FrameLedger.Application.Ipc;
|
||||
using FrameLedger.Application.Rules;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using FrameLedger.Infrastructure.Rules;
|
||||
@@ -89,6 +90,8 @@ internal static class Program
|
||||
private static async Task<int> ServeAsync(LedgerDatabase db, AgentPaths paths)
|
||||
{
|
||||
HostApplicationBuilder builder = Host.CreateApplicationBuilder();
|
||||
// Before the composition, so its TryAdd keeps this one: Shutdown over the pipe stops the host (PR-1b).
|
||||
builder.Services.AddSingleton<IAgentLifetime, HostAgentLifetime>();
|
||||
builder.Services.AddFrameLedgerAgent(db, paths);
|
||||
builder.Services.AddHostedService<WatcherHostedService>();
|
||||
// The pipe (07_IPC §C), the product's UI channel: --serve only, never under --console (P3 PR-1).
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace FrameLedger.Application.Capture;
|
||||
|
||||
/// <summary>
|
||||
/// The one global pause flag (FR-3.9): flipped by the pipe's <c>PauseCapture</c> / <c>ResumeCapture</c>, read by
|
||||
/// every running session on its next tick. In memory only — a pause is a moment's intent, not a setting, and
|
||||
/// an Agent that restarts resumes.
|
||||
/// </summary>
|
||||
public sealed class CapturePause : ICapturePauseSource
|
||||
{
|
||||
private volatile bool _paused;
|
||||
|
||||
public bool IsPaused => _paused;
|
||||
|
||||
/// <summary>Returns the new state.</summary>
|
||||
public bool Set(bool paused)
|
||||
{
|
||||
_paused = paused;
|
||||
return paused;
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,8 @@ public sealed class CaptureSession(
|
||||
INgxDriverProbe? ngx = null,
|
||||
IProcessLauncher? launcher = null,
|
||||
ICaptureObserver? observer = null,
|
||||
IKillSwitch? killSwitch = null)
|
||||
IKillSwitch? killSwitch = null,
|
||||
ICapturePauseSource? pause = null)
|
||||
{
|
||||
/// <summary>Start one session, or say why not.</summary>
|
||||
/// <remarks>
|
||||
@@ -79,7 +80,7 @@ public sealed class CaptureSession(
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public async Task<CaptureOutcome> RunAsync(string normalisedExePath, ExecutableFingerprint? observed,
|
||||
string payloadPath, CancellationToken ct = default)
|
||||
string payloadPath, CancellationToken ct = default, CancellationToken stop = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(normalisedExePath);
|
||||
|
||||
@@ -101,7 +102,7 @@ public sealed class CaptureSession(
|
||||
return new CaptureOutcome { Reason = refused };
|
||||
}
|
||||
|
||||
return await SessionAsync(pid.Value, alive, record, observed!.Value, payloadPath, started: null, ct)
|
||||
return await SessionAsync(pid.Value, alive, record, observed!.Value, payloadPath, started: null, ct, stop)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -123,7 +124,7 @@ public sealed class CaptureSession(
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public async Task<CaptureOutcome> RunLaunchedAsync(string normalisedExePath, ExecutableFingerprint? observed,
|
||||
string payloadPath, string arguments, CancellationToken ct = default)
|
||||
string payloadPath, string arguments, CancellationToken ct = default, CancellationToken stop = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(normalisedExePath);
|
||||
if (launcher is null)
|
||||
@@ -145,7 +146,7 @@ public sealed class CaptureSession(
|
||||
return new CaptureOutcome { Reason = refused };
|
||||
}
|
||||
|
||||
return await SessionAsync(launched.Value.Pid, alive, record, observed!.Value, payloadPath, started, ct)
|
||||
return await SessionAsync(launched.Value.Pid, alive, record, observed!.Value, payloadPath, started, ct, stop)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -162,7 +163,7 @@ public sealed class CaptureSession(
|
||||
|
||||
/// <summary>Gate, attach, drain — shared by both modes; <paramref name="started"/> non-null is launch mode.</summary>
|
||||
private async Task<CaptureOutcome> SessionAsync(int pid, ITargetLiveness alive, GameConsentRecord record,
|
||||
ExecutableFingerprint observed, string payloadPath, Stopwatch? started, CancellationToken ct)
|
||||
ExecutableFingerprint observed, string payloadPath, Stopwatch? started, CancellationToken ct, CancellationToken stop)
|
||||
{
|
||||
int waitMs = started is null ? 0 : checked((int)options.LaunchWaitBudget.TotalMilliseconds);
|
||||
// THE FOURTH INPUT (FR-2.4, decision D7) is read here and handed to the request, so the refusal is
|
||||
@@ -197,7 +198,7 @@ public sealed class CaptureSession(
|
||||
using (sink)
|
||||
{
|
||||
observer?.Attached(pid, sink.Handshake);
|
||||
CaptureOutcome result = await DrainAsync(pid, alive, sink, verdict, ct).ConfigureAwait(false);
|
||||
CaptureOutcome result = await DrainAsync(pid, alive, sink, verdict, ct, stop).ConfigureAwait(false);
|
||||
return result with { LaunchWait = launchWait, TargetPid = pid, ExitCode = alive.ExitCode };
|
||||
}
|
||||
}
|
||||
@@ -247,11 +248,11 @@ public sealed class CaptureSession(
|
||||
}
|
||||
|
||||
private async Task<CaptureOutcome> DrainAsync(int pid, ITargetLiveness alive, ICaptureSink sink,
|
||||
AntiCheatVerdict verdict, CancellationToken ct)
|
||||
AntiCheatVerdict verdict, CancellationToken ct, CancellationToken stop)
|
||||
{
|
||||
var supervisor = new GuardSupervisor(guard);
|
||||
var state = new DrainState(new ModuleTally(modules, ngx));
|
||||
SessionEndReason end = await SuperviseAsync(pid, alive, sink, supervisor, state, ct).ConfigureAwait(false);
|
||||
SessionEndReason end = await SuperviseAsync(pid, alive, sink, supervisor, state, ct, stop).ConfigureAwait(false);
|
||||
|
||||
return new CaptureOutcome
|
||||
{
|
||||
@@ -315,7 +316,7 @@ public sealed class CaptureSession(
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
private async Task<SessionEndReason> SuperviseAsync(int pid, ITargetLiveness alive, ICaptureSink sink,
|
||||
GuardSupervisor supervisor, DrainState state, CancellationToken ct)
|
||||
GuardSupervisor supervisor, DrainState state, CancellationToken ct, CancellationToken stop)
|
||||
{
|
||||
var buffer = new FlFrameRecord[512];
|
||||
|
||||
@@ -331,13 +332,12 @@ public sealed class CaptureSession(
|
||||
Exception? faulted = null;
|
||||
while (mayContinue)
|
||||
{
|
||||
ApplyPause(sink, state);
|
||||
state.Focus.Sample(alive.IsForeground);
|
||||
DrainInto(sink, buffer, state);
|
||||
observer?.Tick(state.Progress(sink, supervisor));
|
||||
|
||||
end = SessionEndClassifier.Classify(
|
||||
alive.HasExited, sink.WriterState.Status, supervisor.UnhookRequested,
|
||||
DateTimeOffset.UtcNow > attachSettledAt);
|
||||
end = EndOf(alive, sink, supervisor, attachSettledAt, stop);
|
||||
if (end != SessionEndReason.Running || (hardStop is not null && DateTimeOffset.UtcNow >= hardStop))
|
||||
{
|
||||
break;
|
||||
@@ -456,12 +456,43 @@ public sealed class CaptureSession(
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tick's verdict: the classifier's, or — when the classifier says nothing ended and the user's stop
|
||||
/// token for THIS session is set (P3 PR-1b) — <see cref="SessionEndReason.StoppedByUser"/>. Read here, at a
|
||||
/// tick, so the last drain still runs and the session finalizes; the host's cancellation would not give it that.
|
||||
/// </summary>
|
||||
private static SessionEndReason EndOf(ITargetLiveness alive, ICaptureSink sink, GuardSupervisor supervisor,
|
||||
DateTimeOffset attachSettledAt, CancellationToken stop)
|
||||
{
|
||||
SessionEndReason end = SessionEndClassifier.Classify(
|
||||
alive.HasExited, sink.WriterState.Status, supervisor.UnhookRequested,
|
||||
DateTimeOffset.UtcNow > attachSettledAt);
|
||||
return end == SessionEndReason.Running && stop.IsCancellationRequested ? SessionEndReason.StoppedByUser : end;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// FR-3.9's global pause, applied on the tick it changes: the ring is told once per transition, and
|
||||
/// supervision continues regardless — a paused session is still a hooked process under a 30 s scan.
|
||||
/// </summary>
|
||||
private void ApplyPause(ICaptureSink sink, DrainState state)
|
||||
{
|
||||
bool paused = pause?.IsPaused ?? false;
|
||||
if (paused != state.Paused)
|
||||
{
|
||||
sink.SetPaused(paused);
|
||||
state.Paused = paused;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Everything one session accumulates, owned by the loop; the observer reads it between ticks.</summary>
|
||||
private sealed class DrainState(ModuleTally loaded)
|
||||
{
|
||||
/// <summary>Set when a scan boundary found FR-2.4's switch on and published the stop (P2 PR-F).</summary>
|
||||
public bool KillSwitchStopped { get; set; }
|
||||
|
||||
/// <summary>What the ring was last told about FR-3.9's pause (P3 PR-1b).</summary>
|
||||
public bool Paused { get; set; }
|
||||
|
||||
public List<FlFrameRecord> Records { get; } = [];
|
||||
|
||||
public List<ulong> Gaps { get; } = [];
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace FrameLedger.Application.Capture;
|
||||
|
||||
/// <summary>
|
||||
/// FR-3.9's global pause, as the capture loop reads it (P3 PR-1b): every drain tick compares it to what the
|
||||
/// ring was last told and publishes <c>pauseRequested</c> on a change. Supervision — the guard scan, the
|
||||
/// kill switch, the safety stop — never pauses; only the recording does.
|
||||
/// </summary>
|
||||
public interface ICapturePauseSource
|
||||
{
|
||||
bool IsPaused { get; }
|
||||
}
|
||||
@@ -135,4 +135,11 @@ public enum SessionEndReason
|
||||
/// <c>unhookRequested</c> and stopped. The user's stop, not a safety refusal — the guard never said no.
|
||||
/// </summary>
|
||||
KillSwitchEngaged,
|
||||
|
||||
/// <summary>
|
||||
/// The user asked for THIS session to end (<c>StopSession</c> over the pipe, P3 PR-1b; FR-3.6 "user stop"):
|
||||
/// the loop saw its stop token at a tick, drained once more and finalized. The target keeps running,
|
||||
/// unhooked from here — <c>exit_status</c> is <c>normal</c>, and the row is stored like any other.
|
||||
/// </summary>
|
||||
StoppedByUser,
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Shared.Ipc;
|
||||
|
||||
namespace FrameLedger.Application.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// The command half of <c>07_IPC</c> §Messages (P3 PR-1b): what a client may ASK for. <c>07_IPC</c> §The pipe is
|
||||
/// not a trust boundary is the rule every method here follows — no inbound message asserts a safety fact; the
|
||||
/// Agent establishes each one itself. <c>SetHookEnabled</c> is where that bites: the pre-scan runs here, a block
|
||||
/// is recorded here, and the consent stamp — the Agent's clock, the Agent's provenance — is stamped here or not
|
||||
/// at all. Until FR-2.1's reviewed disclosure exists (P3 PR-4) it is not at all: an enable is answered
|
||||
/// <c>Error DisclosureUnavailable</c> after the pre-scan, and nothing is written but a block.
|
||||
/// </summary>
|
||||
public sealed class AgentCommandHandler
|
||||
{
|
||||
private readonly IGameRepository _games;
|
||||
private readonly IGameConsentStore _consent;
|
||||
private readonly IAntiCheatGuard _guard;
|
||||
private readonly IExecutableIdentitySource _identity;
|
||||
private readonly CaptureOrchestrator _orchestrator;
|
||||
private readonly CapturePause _pause;
|
||||
private readonly IAgentLifetime _lifetime;
|
||||
private readonly Func<CancellationToken, ValueTask<string>> _updateRules;
|
||||
private readonly string? _disclosureVersion;
|
||||
|
||||
/// <summary>
|
||||
/// <c>disclosureVersion</c> is the version of FR-2.1's reviewed disclosure this Agent carries: null until P3
|
||||
/// PR-4 ships one, and while it is null no <c>SetHookEnabled true</c> stamps anything.
|
||||
/// </summary>
|
||||
public AgentCommandHandler(IGameRepository games, IGameConsentStore consent, IAntiCheatGuard guard, IExecutableIdentitySource identity,
|
||||
CaptureOrchestrator orchestrator, CapturePause pause, IAgentLifetime lifetime, Func<CancellationToken, ValueTask<string>> updateRules,
|
||||
string? disclosureVersion = null)
|
||||
{
|
||||
_games = games ?? throw new ArgumentNullException(nameof(games));
|
||||
_consent = consent ?? throw new ArgumentNullException(nameof(consent));
|
||||
_guard = guard ?? throw new ArgumentNullException(nameof(guard));
|
||||
_identity = identity ?? throw new ArgumentNullException(nameof(identity));
|
||||
_orchestrator = orchestrator ?? throw new ArgumentNullException(nameof(orchestrator));
|
||||
_pause = pause ?? throw new ArgumentNullException(nameof(pause));
|
||||
_lifetime = lifetime ?? throw new ArgumentNullException(nameof(lifetime));
|
||||
_updateRules = updateRules ?? throw new ArgumentNullException(nameof(updateRules));
|
||||
_disclosureVersion = disclosureVersion;
|
||||
}
|
||||
|
||||
/// <summary>FR-3.9's global pause, as <c>StatusAck.paused</c> reports it.</summary>
|
||||
public bool IsPaused => _pause.IsPaused;
|
||||
|
||||
/// <summary>The ack, or null when <paramref name="request"/> is not a command this half answers.</summary>
|
||||
public async ValueTask<byte[]?> HandleAsync(IpcEnvelope request, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return request.Type switch
|
||||
{
|
||||
IpcMessageType.SetWatchlist => await SetWatchlistAsync(request, ct).ConfigureAwait(false),
|
||||
IpcMessageType.LaunchGame => await LaunchAsync(request, ct).ConfigureAwait(false),
|
||||
IpcMessageType.SetHookEnabled => await SetHookEnabledAsync(request, ct).ConfigureAwait(false),
|
||||
IpcMessageType.PauseCapture => IpcCodec.Encode(IpcMessageType.PauseAck, request.Id, new PauseAck(_pause.Set(true))),
|
||||
IpcMessageType.ResumeCapture => IpcCodec.Encode(IpcMessageType.PauseAck, request.Id, new PauseAck(_pause.Set(false))),
|
||||
IpcMessageType.StopSession => Stop(request),
|
||||
IpcMessageType.UpdateRules => IpcCodec.Encode(IpcMessageType.UpdateRulesAck, request.Id, new UpdateRulesAck(await _updateRules(ct).ConfigureAwait(false))),
|
||||
IpcMessageType.Shutdown => Shutdown(request),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Identity only (<c>07_IPC</c>: "carries no hooking state"): every entry's row is ensured, hooking off when new.
|
||||
/// Nothing is removed — removing a game is the App's FR-1.4 (with its "keep the sessions?" question), never a
|
||||
/// bulk message's.
|
||||
/// </summary>
|
||||
private async ValueTask<byte[]> SetWatchlistAsync(IpcEnvelope request, CancellationToken ct)
|
||||
{
|
||||
SetWatchlistRequest? payload = IpcCodec.Payload<SetWatchlistRequest>(request);
|
||||
if (payload is null)
|
||||
{
|
||||
return Malformed(request, "SetWatchlist carries no payload");
|
||||
}
|
||||
|
||||
var games = new List<WatchlistGame>();
|
||||
var unreadable = new List<string>();
|
||||
foreach (WatchlistEntry entry in payload.Entries)
|
||||
{
|
||||
string path = _identity.Normalise(entry.ExePath);
|
||||
ExecutableFingerprint? fingerprint = _identity.Read(path);
|
||||
if (fingerprint is null)
|
||||
{
|
||||
unreadable.Add(entry.ExePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
GameRow row = await _games.EnsureAsync(fingerprint.Value, Path.GetFileNameWithoutExtension(path), ct).ConfigureAwait(false);
|
||||
games.Add(new WatchlistGame(row.Id, row.Fingerprint.ExePath, row.Name));
|
||||
}
|
||||
|
||||
return IpcCodec.Encode(IpcMessageType.WatchlistAck, request.Id, new WatchlistAck(games, unreadable));
|
||||
}
|
||||
|
||||
private async ValueTask<byte[]> LaunchAsync(IpcEnvelope request, CancellationToken ct)
|
||||
{
|
||||
LaunchGameRequest? payload = IpcCodec.Payload<LaunchGameRequest>(request);
|
||||
if (payload is null)
|
||||
{
|
||||
return Malformed(request, "LaunchGame carries no payload");
|
||||
}
|
||||
|
||||
LaunchResult result = await _orchestrator.LaunchAsync(payload.GameId, payload.Arguments ?? string.Empty, ct).ConfigureAwait(false);
|
||||
return IpcCodec.Encode(IpcMessageType.LaunchAck, request.Id,
|
||||
new LaunchAck(payload.GameId, result.Outcome == LaunchOutcome.Accepted, result.Outcome.ToString(), result.SessionGuid));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Agent re-runs the static pre-scan and stamps — or refuses — itself (<c>07_IPC</c> §The pipe is not a
|
||||
/// trust boundary). A revoke needs no scan. An enable: the scan first, a block recorded and answered
|
||||
/// <c>Refused</c>; a clean scan is then answered <c>Error DisclosureUnavailable</c> until the reviewed
|
||||
/// disclosure exists (PR-4), so nothing is ever stamped on the strength of a client's word.
|
||||
/// </summary>
|
||||
private async ValueTask<byte[]> SetHookEnabledAsync(IpcEnvelope request, CancellationToken ct)
|
||||
{
|
||||
SetHookEnabledRequest? payload = IpcCodec.Payload<SetHookEnabledRequest>(request);
|
||||
if (payload is null)
|
||||
{
|
||||
return Malformed(request, "SetHookEnabled carries no payload");
|
||||
}
|
||||
|
||||
GameRow? game = await FindGameAsync(payload.GameId, ct).ConfigureAwait(false);
|
||||
if (game is null)
|
||||
{
|
||||
return Error(request, IpcErrorCode.UnknownGame, $"no games row has id {payload.GameId}");
|
||||
}
|
||||
|
||||
string path = game.Fingerprint.ExePath;
|
||||
if (!payload.Enabled)
|
||||
{
|
||||
ConsentWriteOutcome revoked = await _consent.RevokeAsync(path, ct).ConfigureAwait(false);
|
||||
return IpcCodec.Encode(IpcMessageType.HookEnabledAck, request.Id, new HookEnabledAck(game.Id, Enabled: false, revoked.ToString(), Prescan: null));
|
||||
}
|
||||
|
||||
ExecutableFingerprint? fingerprint = _identity.Read(path);
|
||||
if (fingerprint is null)
|
||||
{
|
||||
return Error(request, IpcErrorCode.ExecutableUnreadable, $"{path} could not be read, so nothing can be scanned or stamped");
|
||||
}
|
||||
|
||||
string directory = Path.GetDirectoryName(path) ?? path;
|
||||
AntiCheatVerdict verdict = await _guard.PreScanGameDirectoryAsync(directory, ct).ConfigureAwait(false);
|
||||
if (!verdict.IsAllowed)
|
||||
{
|
||||
// A refusal, or a scan that reached no answer: the store records which (a default verdict is
|
||||
// "could not verify", never a block), and both are answered as a refusal to enable.
|
||||
await _consent.RecordGuardBlockAsync(fingerprint.Value, verdict, ct).ConfigureAwait(false);
|
||||
string reason = verdict.Reason == AntiCheatRefusalReason.Allow ? "PreScanCouldNotVerify" : verdict.Reason.ToString();
|
||||
return IpcCodec.Encode(IpcMessageType.Refused, request.Id,
|
||||
new RefusedAck(game.Id, reason, NullIfEmpty(verdict.Family), NullIfEmpty(verdict.Signal)));
|
||||
}
|
||||
|
||||
if (_disclosureVersion is null)
|
||||
{
|
||||
return Error(request, IpcErrorCode.DisclosureUnavailable,
|
||||
"the pre-scan is clean, and nothing was stamped: FR-2.1's reviewed consent dialog does not exist yet (P3 PR-4); "
|
||||
+ "until it does, hooking is enabled through `FrameLedger.Agent --console consent grant`");
|
||||
}
|
||||
|
||||
// PR-4 lands here: the disclosure version compared, the stamp with the Agent's clock and provenance.
|
||||
return Error(request, IpcErrorCode.DisclosureUnavailable, "the consent stamp is not wired yet (P3 PR-4)");
|
||||
}
|
||||
|
||||
private byte[] Stop(IpcEnvelope request)
|
||||
{
|
||||
StopSessionRequest? payload = IpcCodec.Payload<StopSessionRequest>(request);
|
||||
if (payload is null)
|
||||
{
|
||||
return Malformed(request, "StopSession carries no payload");
|
||||
}
|
||||
|
||||
bool accepted = _orchestrator.StopSession(payload.SessionGuid);
|
||||
return IpcCodec.Encode(IpcMessageType.StopAck, request.Id,
|
||||
new StopAck(payload.SessionGuid, accepted, accepted ? null : "no running session started by the watcher or a launch carries that guid"));
|
||||
}
|
||||
|
||||
private byte[] Shutdown(IpcEnvelope request)
|
||||
{
|
||||
byte[] ack = IpcCodec.Encode(IpcMessageType.ShutdownAck, request.Id, new ShutdownAck());
|
||||
_lifetime.RequestShutdown();
|
||||
return ack;
|
||||
}
|
||||
|
||||
private async ValueTask<GameRow?> FindGameAsync(long gameId, CancellationToken ct)
|
||||
{
|
||||
IReadOnlyList<GameRow> rows = await _games.ListAsync(ct).ConfigureAwait(false);
|
||||
return rows.FirstOrDefault(g => g.Id == gameId);
|
||||
}
|
||||
|
||||
private static byte[] Malformed(IpcEnvelope request, string message) => Error(request, IpcErrorCode.Malformed, message);
|
||||
|
||||
private static byte[] Error(IpcEnvelope request, string code, string message) =>
|
||||
IpcCodec.Encode(IpcMessageType.Error, request.Id, new ErrorAck(code, message));
|
||||
|
||||
private static string? NullIfEmpty(string? value) => string.IsNullOrEmpty(value) ? null : value;
|
||||
}
|
||||
@@ -3,8 +3,9 @@ using FrameLedger.Shared.Ipc;
|
||||
namespace FrameLedger.Application.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// The read half of <c>07_IPC</c> §Messages: <c>Hello</c>, <c>GetStatus</c>, <c>Ping</c>. Nothing here changes
|
||||
/// a state — the command half (PR-1b) is where <c>07_IPC</c> §The pipe is not a trust boundary starts to bite.
|
||||
/// The read half of <c>07_IPC</c> §Messages — <c>Hello</c>, <c>GetStatus</c>, <c>Ping</c> — and the front door
|
||||
/// for the command half: anything else is offered to <see cref="AgentCommandHandler"/> when one is composed, and
|
||||
/// answered <c>Error UnknownType</c> otherwise.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The telemetry descriptor is a function because composing the layers costs a library start; the identity is a
|
||||
@@ -15,25 +16,38 @@ public sealed class AgentRequestHandler : IIpcRequestHandler
|
||||
private readonly AgentIdentity _identity;
|
||||
private readonly Func<string?> _telemetryDescriptor;
|
||||
private readonly Func<AgentStatus> _status;
|
||||
private readonly Func<AgentCommandHandler?> _commands;
|
||||
|
||||
public AgentRequestHandler(AgentIdentity identity, Func<string?> telemetryDescriptor, Func<AgentStatus> status)
|
||||
/// <summary>
|
||||
/// <c>commands</c> is a function, resolved on the first command rather than at construction: the command
|
||||
/// handler reaches the orchestrator, which reaches the recorder, whose observer publishes through the pipe
|
||||
/// server that owns this handler — a cycle a container cannot build eagerly, and one a request can walk lazily.
|
||||
/// </summary>
|
||||
public AgentRequestHandler(AgentIdentity identity, Func<string?> telemetryDescriptor, Func<AgentStatus> status, Func<AgentCommandHandler?>? commands = null)
|
||||
{
|
||||
_identity = identity ?? throw new ArgumentNullException(nameof(identity));
|
||||
_telemetryDescriptor = telemetryDescriptor ?? throw new ArgumentNullException(nameof(telemetryDescriptor));
|
||||
_status = status ?? throw new ArgumentNullException(nameof(status));
|
||||
_commands = commands ?? (static () => null);
|
||||
}
|
||||
|
||||
public byte[] Handle(IpcEnvelope request)
|
||||
public async ValueTask<byte[]> HandleAsync(IpcEnvelope request, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return request.Type switch
|
||||
switch (request.Type)
|
||||
{
|
||||
IpcMessageType.Hello => Hello(request),
|
||||
IpcMessageType.GetStatus => IpcCodec.Encode(IpcMessageType.StatusAck, request.Id, _status().ToAck()),
|
||||
IpcMessageType.Ping => IpcCodec.Encode(IpcMessageType.Pong, request.Id, new PongAck()),
|
||||
_ => IpcCodec.Encode(IpcMessageType.Error, request.Id,
|
||||
new ErrorAck(IpcErrorCode.UnknownType, $"'{request.Type}' is not a request this Agent answers (07_IPC §Messages, read half)")),
|
||||
};
|
||||
case IpcMessageType.Hello:
|
||||
return Hello(request);
|
||||
case IpcMessageType.GetStatus:
|
||||
return IpcCodec.Encode(IpcMessageType.StatusAck, request.Id, _status().ToAck(_commands()?.IsPaused ?? false));
|
||||
case IpcMessageType.Ping:
|
||||
return IpcCodec.Encode(IpcMessageType.Pong, request.Id, new PongAck());
|
||||
default:
|
||||
AgentCommandHandler? commands = _commands();
|
||||
byte[]? command = commands is null ? null : await commands.HandleAsync(request, ct).ConfigureAwait(false);
|
||||
return command ?? IpcCodec.Encode(IpcMessageType.Error, request.Id,
|
||||
new ErrorAck(IpcErrorCode.UnknownType, $"'{request.Type}' is not a request this Agent answers (07_IPC §Messages)"));
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] Hello(IpcEnvelope request)
|
||||
|
||||
@@ -23,9 +23,10 @@ public sealed record AgentStatus(IReadOnlyList<ActiveSession> Sessions)
|
||||
: Sessions.Count > 0 ? RecordingState
|
||||
: IdleState;
|
||||
|
||||
public StatusAck ToAck()
|
||||
/// <summary>The ack; <paramref name="paused"/> is FR-3.9's global pause, which is not a session state and travels beside it.</summary>
|
||||
public StatusAck ToAck(bool paused = false)
|
||||
{
|
||||
ActiveSession? primary = Sessions.FirstOrDefault(static s => s.Tier == 1) ?? (Sessions.Count > 0 ? Sessions[0] : null);
|
||||
return new StatusAck(State, primary, primary?.Tier, Sessions);
|
||||
return new StatusAck(State, primary, primary?.Tier, Sessions, paused);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace FrameLedger.Application.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// <c>Shutdown</c>'s one effect (<c>07_IPC</c> §Messages): ask the host to stop gracefully — sessions finalize
|
||||
/// inside the host's grace window, as they do on Ctrl+C. The Agent adapts its <c>IHostApplicationLifetime</c>;
|
||||
/// under <c>--console</c> there is no host and the request is a logged no-op.
|
||||
/// </summary>
|
||||
public interface IAgentLifetime
|
||||
{
|
||||
void RequestShutdown();
|
||||
}
|
||||
@@ -9,5 +9,5 @@ namespace FrameLedger.Application.Ipc;
|
||||
public interface IIpcRequestHandler
|
||||
{
|
||||
/// <summary>The ack — <c>Error</c> when the type is unknown or the payload is not what the type needs.</summary>
|
||||
byte[] Handle(IpcEnvelope request);
|
||||
ValueTask<byte[]> HandleAsync(IpcEnvelope request, CancellationToken ct);
|
||||
}
|
||||
@@ -20,4 +20,16 @@ public sealed record RecordRequest
|
||||
|
||||
/// <summary>What the <c>games</c> row is called when it has to be created; defaults to the file name.</summary>
|
||||
public string? GameName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The session's identity, when the caller needs to know it before the session ends — the orchestrator
|
||||
/// chooses one so <c>StopSession</c> can name it (P3 PR-1b). Null: the recorder mints its own.
|
||||
/// </summary>
|
||||
public Guid? SessionGuid { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The user's stop for this one session (FR-3.6): the loop ends as <see cref="Capture.SessionEndReason.StoppedByUser"/>
|
||||
/// at its next tick and finalizes. Distinct from the host's cancellation, which leaves a <c>.partial</c>.
|
||||
/// </summary>
|
||||
public CancellationToken StopToken { get; init; }
|
||||
}
|
||||
@@ -67,7 +67,7 @@ public sealed class SessionRecorder : ISessionRecorder
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
DateTimeOffset startedAt = _clock.GetUtcNow();
|
||||
long qpcEpoch = _clock.GetTimestamp();
|
||||
var guid = Guid.NewGuid();
|
||||
Guid guid = request.SessionGuid ?? Guid.NewGuid();
|
||||
|
||||
ExecutableFingerprint fingerprint = request.Observed ?? new ExecutableFingerprint { ExePath = request.NormalisedExePath, SizeBytes = 0, MtimeUnixMs = 0 };
|
||||
GameRow game = await _games.EnsureAsync(fingerprint, request.GameName ?? Path.GetFileNameWithoutExtension(request.NormalisedExePath), ct).ConfigureAwait(false);
|
||||
@@ -130,8 +130,8 @@ public sealed class SessionRecorder : ISessionRecorder
|
||||
{
|
||||
CaptureSession session = _sessions.Create(run);
|
||||
return request.Mode == CaptureMode.Launch
|
||||
? await session.RunLaunchedAsync(request.NormalisedExePath, request.Observed, request.PayloadPath, request.Arguments, ct).ConfigureAwait(false)
|
||||
: await session.RunAsync(request.NormalisedExePath, request.Observed, request.PayloadPath, ct).ConfigureAwait(false);
|
||||
? await session.RunLaunchedAsync(request.NormalisedExePath, request.Observed, request.PayloadPath, request.Arguments, ct, request.StopToken).ConfigureAwait(false)
|
||||
: await session.RunAsync(request.NormalisedExePath, request.Observed, request.PayloadPath, ct, request.StopToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<RecordedSession> FinalizeAsync(RecordRequest request, GameRow game, PartialHeader header, CaptureOutcome outcome,
|
||||
|
||||
@@ -16,14 +16,23 @@ namespace FrameLedger.Application.Watch;
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Single consumer, by construction.</b> <see cref="PollOnceAsync"/> is the only writer of the running-session
|
||||
/// table and the only reader of the watcher; the sessions themselves run on their own tasks and touch nothing
|
||||
/// here. <c>04_CAPTURE</c> §Threading model's watcher row is this method on a <see cref="PeriodicTimer"/>.
|
||||
/// <b>The running-session table has one lock, and the sessions themselves never take it.</b> Until P3 PR-1b
|
||||
/// <see cref="PollOnceAsync"/> was the table's only writer; the pipe's <c>LaunchGame</c> and <c>StopSession</c>
|
||||
/// now reach it from the pipe's tasks too, so the table is guarded rather than queued (HANDOFF §P3 decision
|
||||
/// D12 as built: two commands do not justify a channel and a second place a start can wait). Each session
|
||||
/// runs on its own task and touches nothing here.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Attach mode only.</b> A watched process is one the user started elsewhere; launch mode is the console
|
||||
/// verb's, and the election after a launcher exits is <see cref="ElectAfterLaunchAsync"/>, called by that verb.
|
||||
/// A <see cref="TrackedProcessGone"/> starts nothing: the session's own loop sees the exit first.
|
||||
/// <b>Attach mode from the watcher, launch mode on request.</b> A watched process is one the user started
|
||||
/// elsewhere; <see cref="LaunchAsync"/> starts the title itself through the <see cref="ILaunchRecorderFactory"/>
|
||||
/// the composition root supplies (the console's <c>launch</c> verb builds the same by hand), and the election
|
||||
/// after a launcher exits is <see cref="ElectAfterLaunchAsync"/>, which both share. A
|
||||
/// <see cref="TrackedProcessGone"/> starts nothing: the session's own loop sees the exit first.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>A stop is a token, not a cancellation.</b> <see cref="StopSession"/> cancels the session's own stop
|
||||
/// token, which the loop reads at its next tick and ends as <see cref="SessionEndReason.StoppedByUser"/> —
|
||||
/// drained, finalized, stored — where the host's cancellation would leave a <c>.partial</c> for recovery.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class CaptureOrchestrator
|
||||
@@ -34,11 +43,13 @@ public sealed class CaptureOrchestrator
|
||||
private readonly IExecutableIdentitySource _identity;
|
||||
private readonly OrchestratorOptions _options;
|
||||
private readonly Action<string> _log;
|
||||
private readonly ILaunchRecorderFactory? _launches;
|
||||
private readonly ProcessWatcher _watcher = new();
|
||||
private readonly Dictionary<long, Task> _running = new();
|
||||
private readonly Lock _table = new();
|
||||
private readonly Dictionary<long, Running> _running = [];
|
||||
|
||||
public CaptureOrchestrator(ISessionRecorder recorder, IGameRepository games, IProcessSnapshotSource processes,
|
||||
IExecutableIdentitySource identity, OrchestratorOptions options, Action<string> log)
|
||||
IExecutableIdentitySource identity, OrchestratorOptions options, Action<string> log, ILaunchRecorderFactory? launches = null)
|
||||
{
|
||||
_recorder = recorder ?? throw new ArgumentNullException(nameof(recorder));
|
||||
_games = games ?? throw new ArgumentNullException(nameof(games));
|
||||
@@ -46,10 +57,20 @@ public sealed class CaptureOrchestrator
|
||||
_identity = identity ?? throw new ArgumentNullException(nameof(identity));
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_launches = launches;
|
||||
}
|
||||
|
||||
/// <summary>Sessions started here that have not finished.</summary>
|
||||
public int RunningSessions => _running.Values.Count(static t => !t.IsCompleted);
|
||||
public int RunningSessions
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_table)
|
||||
{
|
||||
return _running.Values.Count(static r => !r.Task.IsCompleted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Poll until cancelled, then wait for every running session to finalize.</summary>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
@@ -97,6 +118,62 @@ public sealed class CaptureOrchestrator
|
||||
return events;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>StopSession</c> (P3 PR-1b): ask the session with this guid to end at its next tick. False when no running
|
||||
/// session started here carries it — an elected session after a launch, or a console capture, is not addressable.
|
||||
/// </summary>
|
||||
public bool StopSession(Guid sessionGuid)
|
||||
{
|
||||
lock (_table)
|
||||
{
|
||||
foreach (Running r in _running.Values)
|
||||
{
|
||||
if (r.SessionGuid == sessionGuid && !r.Task.IsCompleted)
|
||||
{
|
||||
r.Stop.Cancel();
|
||||
_log($"session {sessionGuid:N}: stop requested; the loop ends at its next tick");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>LaunchGame</c> (P3 PR-1b): start the game with id <paramref name="gameId"/> in launch mode, under the
|
||||
/// one-session-per-game rule, and run the launcher election after it. Consent is still the gate's, one process
|
||||
/// later; this method decides only that a session starts.
|
||||
/// </summary>
|
||||
public async ValueTask<LaunchResult> LaunchAsync(long gameId, string arguments, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(arguments);
|
||||
if (_launches is null)
|
||||
{
|
||||
return LaunchResult.Of(LaunchOutcome.Unavailable);
|
||||
}
|
||||
|
||||
IReadOnlyList<GameRow> rows = await _games.ListAsync(ct).ConfigureAwait(false);
|
||||
GameRow? game = rows.FirstOrDefault(g => g.Id == gameId);
|
||||
if (game is null)
|
||||
{
|
||||
return LaunchResult.Of(LaunchOutcome.UnknownGame);
|
||||
}
|
||||
|
||||
lock (_table)
|
||||
{
|
||||
if (_running.TryGetValue(gameId, out Running? current) && !current.Task.IsCompleted)
|
||||
{
|
||||
return LaunchResult.Of(LaunchOutcome.SessionRunning);
|
||||
}
|
||||
|
||||
var running = new Running(Guid.NewGuid());
|
||||
running.Task = RunLaunchAsync(game, arguments, running.SessionGuid, running.Stop.Token, ct);
|
||||
_running[gameId] = running;
|
||||
return new LaunchResult(LaunchOutcome.Accepted, running.SessionGuid);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// After a launch-mode session ended with the launcher gone (<see cref="SessionEndReason.LaunchTargetExited"/>)
|
||||
/// or sitting on its window (<see cref="SessionEndReason.LaunchNoPresentationRuntime"/>): elect the newest
|
||||
@@ -121,31 +198,36 @@ public sealed class CaptureOrchestrator
|
||||
}
|
||||
|
||||
_log($"election: pid {elected.Value.Pid} ({path}) is the newest tracked descendant; attaching");
|
||||
return await _recorder.RecordAsync(Attach(path, null), ct).ConfigureAwait(false);
|
||||
return await _recorder.RecordAsync(Attach(path, null, null, default), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private void Start(TrackedProcessAppeared appeared, CancellationToken ct)
|
||||
{
|
||||
if (_running.TryGetValue(appeared.Game.Id, out Task? running) && !running.IsCompleted)
|
||||
lock (_table)
|
||||
{
|
||||
_log($"watch: pid {appeared.Pid} ({appeared.Game.Name}) appeared while a session for that game is running; one at a time");
|
||||
return;
|
||||
}
|
||||
if (_running.TryGetValue(appeared.Game.Id, out Running? current) && !current.Task.IsCompleted)
|
||||
{
|
||||
_log($"watch: pid {appeared.Pid} ({appeared.Game.Name}) appeared while a session for that game is running; one at a time");
|
||||
return;
|
||||
}
|
||||
|
||||
_log(appeared.StalePath
|
||||
? $"watch: pid {appeared.Pid} matched {appeared.Game.Name} BY FILE NAME ONLY — it runs from {appeared.ImagePath}, not the path on record; the session is keyed on the real path"
|
||||
: $"watch: pid {appeared.Pid} ({appeared.Game.Name}) appeared; starting a session");
|
||||
RecordRequest request = Attach(appeared.ImagePath, appeared.Game.Name);
|
||||
_running[appeared.Game.Id] = RunAndReportAsync(request, ct);
|
||||
_log(appeared.StalePath
|
||||
? $"watch: pid {appeared.Pid} matched {appeared.Game.Name} BY FILE NAME ONLY — it runs from {appeared.ImagePath}, not the path on record; the session is keyed on the real path"
|
||||
: $"watch: pid {appeared.Pid} ({appeared.Game.Name}) appeared; starting a session");
|
||||
var running = new Running(Guid.NewGuid());
|
||||
RecordRequest request = Attach(appeared.ImagePath, appeared.Game.Name, running.SessionGuid, running.Stop.Token);
|
||||
running.Task = RunAndReportAsync(_recorder, request, ct);
|
||||
_running[appeared.Game.Id] = running;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The session on its own task, reporting its own end; nothing else awaits a stored task.</summary>
|
||||
private async Task RunAndReportAsync(RecordRequest request, CancellationToken ct)
|
||||
private async Task RunAndReportAsync(ISessionRecorder recorder, RecordRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
RecordedSession r = await Task.Run(() => _recorder.RecordAsync(request, ct), ct).ConfigureAwait(false);
|
||||
_log($"session {r.SessionGuid:N}: {r.Outcome.Reason}; {r.Finalize.Status} (tier {(int)r.Row.Tier}, exit={r.ExitStatus}, frames={r.Row.FrameCount})");
|
||||
RecordedSession r = await Task.Run(() => recorder.RecordAsync(request, ct), ct).ConfigureAwait(false);
|
||||
Report(r);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
@@ -157,7 +239,48 @@ public sealed class CaptureOrchestrator
|
||||
}
|
||||
}
|
||||
|
||||
private RecordRequest Attach(string normalisedExePath, string? gameName)
|
||||
/// <summary>Launch mode on its own task: the environment, the session, the election, each reported.</summary>
|
||||
private async Task RunLaunchAsync(GameRow game, string arguments, Guid sessionGuid, CancellationToken stop, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
string path = game.Fingerprint.ExePath;
|
||||
using ILaunchRecording launch = await _launches!.PrepareAsync(path, ct).ConfigureAwait(false);
|
||||
_log($"launch: {game.Name}: {launch.Description}");
|
||||
var request = new RecordRequest
|
||||
{
|
||||
NormalisedExePath = path,
|
||||
Observed = _identity.Read(path),
|
||||
PayloadPath = _options.PayloadPath,
|
||||
Mode = CaptureMode.Launch,
|
||||
Arguments = arguments,
|
||||
GameName = game.Name,
|
||||
SessionGuid = sessionGuid,
|
||||
StopToken = stop,
|
||||
};
|
||||
RecordedSession r = await Task.Run(() => launch.Recorder.RecordAsync(request, ct), ct).ConfigureAwait(false);
|
||||
Report(r);
|
||||
|
||||
RecordedSession? elected = await ElectAfterLaunchAsync(r, ct).ConfigureAwait(false);
|
||||
if (elected is not null)
|
||||
{
|
||||
Report(elected);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_log("session: cancelled before it could finalize; the .partial stays for recovery");
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log($"session: FAULTED {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void Report(RecordedSession r) =>
|
||||
_log($"session {r.SessionGuid:N}: {r.Outcome.Reason}; {r.Finalize.Status} (tier {(int)r.Row.Tier}, exit={r.ExitStatus}, frames={r.Row.FrameCount})");
|
||||
|
||||
private RecordRequest Attach(string normalisedExePath, string? gameName, Guid? sessionGuid, CancellationToken stop)
|
||||
{
|
||||
ExecutableFingerprint? observed = _identity.Read(normalisedExePath);
|
||||
return new RecordRequest
|
||||
@@ -167,24 +290,51 @@ public sealed class CaptureOrchestrator
|
||||
PayloadPath = _options.PayloadPath,
|
||||
Mode = CaptureMode.Attach,
|
||||
GameName = gameName,
|
||||
SessionGuid = sessionGuid,
|
||||
StopToken = stop,
|
||||
};
|
||||
}
|
||||
|
||||
private void Reap()
|
||||
{
|
||||
foreach ((long gameId, Task task) in _running.ToArray())
|
||||
lock (_table)
|
||||
{
|
||||
if (task.IsCompleted)
|
||||
foreach ((long gameId, Running running) in _running.ToArray())
|
||||
{
|
||||
_running.Remove(gameId);
|
||||
if (running.Task.IsCompleted)
|
||||
{
|
||||
_running.Remove(gameId);
|
||||
running.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Task DrainRunningAsync()
|
||||
private async Task DrainRunningAsync()
|
||||
{
|
||||
Task[] all = [.. _running.Values];
|
||||
_running.Clear();
|
||||
return Task.WhenAll(all);
|
||||
Running[] all;
|
||||
lock (_table)
|
||||
{
|
||||
all = [.. _running.Values];
|
||||
_running.Clear();
|
||||
}
|
||||
|
||||
await Task.WhenAll(all.Select(static r => r.Task)).ConfigureAwait(false);
|
||||
foreach (Running r in all)
|
||||
{
|
||||
r.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One started session: its guid (chosen here, so the stop is addressable), its task, its stop token.</summary>
|
||||
private sealed class Running(Guid sessionGuid) : IDisposable
|
||||
{
|
||||
public Guid SessionGuid { get; } = sessionGuid;
|
||||
|
||||
public CancellationTokenSource Stop { get; } = new();
|
||||
|
||||
public Task Task { get; set; } = System.Threading.Tasks.Task.CompletedTask;
|
||||
|
||||
public void Dispose() => Stop.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -10,4 +10,7 @@ public interface IExecutableIdentitySource
|
||||
{
|
||||
/// <summary>The fingerprint of <paramref name="normalisedExePath"/>, or null when the file cannot be read.</summary>
|
||||
ExecutableFingerprint? Read(string normalisedExePath);
|
||||
|
||||
/// <summary>The path as the <c>games</c> table keys it (P3 PR-1b: a client's path arrives however the client spelled it).</summary>
|
||||
string Normalise(string exePath);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FrameLedger.Application.Recording;
|
||||
|
||||
namespace FrameLedger.Application.Watch;
|
||||
|
||||
/// <summary>
|
||||
/// Launch mode for the orchestrator (P3 PR-1b, <c>LaunchGame</c>): a recorder whose session STARTS the title,
|
||||
/// with whatever environment the launched process is owed — the Vulkan layer's variables unless FR-2.4's switch
|
||||
/// is on. The composition root builds it, because the environment needs paths the Application layer does not
|
||||
/// know; the console's <c>launch</c> verb does the same by hand.
|
||||
/// </summary>
|
||||
public interface ILaunchRecorderFactory
|
||||
{
|
||||
/// <summary>A recorder and its environment for one launch of <paramref name="normalisedExePath"/>; disposed when the session is over.</summary>
|
||||
ValueTask<ILaunchRecording> PrepareAsync(string normalisedExePath, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using FrameLedger.Application.Recording;
|
||||
|
||||
namespace FrameLedger.Application.Watch;
|
||||
|
||||
/// <summary>One launch's recorder; <see cref="Description"/> is what the log says about the environment it got.</summary>
|
||||
public interface ILaunchRecording : IDisposable
|
||||
{
|
||||
ISessionRecorder Recorder { get; }
|
||||
|
||||
string Description { get; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace FrameLedger.Application.Watch;
|
||||
|
||||
/// <summary>What <see cref="CaptureOrchestrator.LaunchAsync"/> decided.</summary>
|
||||
public enum LaunchOutcome
|
||||
{
|
||||
/// <summary>Nobody decided. The zero value, never a result.</summary>
|
||||
NotEvaluated = 0,
|
||||
|
||||
/// <summary>The session task is running; <see cref="LaunchResult.SessionGuid"/> names it.</summary>
|
||||
Accepted,
|
||||
|
||||
/// <summary>No <c>games</c> row has that id.</summary>
|
||||
UnknownGame,
|
||||
|
||||
/// <summary>A session for that game is already running (one at a time).</summary>
|
||||
SessionRunning,
|
||||
|
||||
/// <summary>This orchestrator was composed without launch mode (the console's election-only instance, or a test).</summary>
|
||||
Unavailable,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace FrameLedger.Application.Watch;
|
||||
|
||||
[StructLayout(LayoutKind.Auto)]
|
||||
public readonly record struct LaunchResult(LaunchOutcome Outcome, Guid? SessionGuid)
|
||||
{
|
||||
public static LaunchResult Of(LaunchOutcome outcome) => new(outcome, null);
|
||||
}
|
||||
@@ -220,7 +220,7 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
return false;
|
||||
}
|
||||
|
||||
private byte[] Answer(byte[] frame)
|
||||
private async ValueTask<byte[]> AnswerAsync(byte[] frame, CancellationToken ct)
|
||||
{
|
||||
IpcEnvelope request;
|
||||
try
|
||||
@@ -234,7 +234,7 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
|
||||
try
|
||||
{
|
||||
return _handler.Handle(request);
|
||||
return await _handler.HandleAsync(request, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
@@ -349,7 +349,7 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
identified = true;
|
||||
}
|
||||
|
||||
Enqueue(_owner.Answer(frame));
|
||||
Enqueue(await _owner.AnswerAsync(frame, ct).ConfigureAwait(false));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,5 +8,7 @@ namespace FrameLedger.Infrastructure.Watch;
|
||||
public sealed class ExecutableIdentitySource : IExecutableIdentitySource
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Normalise(string exePath) => ExecutableIdentity.Normalise(exePath);
|
||||
|
||||
public ExecutableFingerprint? Read(string normalisedExePath) => ExecutableIdentity.Read(normalisedExePath);
|
||||
}
|
||||
@@ -28,6 +28,24 @@ namespace FrameLedger.Shared.Ipc;
|
||||
[JsonSerializable(typeof(CaptureDegradedEvent))]
|
||||
[JsonSerializable(typeof(SafetyUnhookEvent))]
|
||||
[JsonSerializable(typeof(CaptureErrorEvent))]
|
||||
[JsonSerializable(typeof(WatchlistEntry))]
|
||||
[JsonSerializable(typeof(SetWatchlistRequest))]
|
||||
[JsonSerializable(typeof(WatchlistGame))]
|
||||
[JsonSerializable(typeof(WatchlistAck))]
|
||||
[JsonSerializable(typeof(LaunchGameRequest))]
|
||||
[JsonSerializable(typeof(LaunchAck))]
|
||||
[JsonSerializable(typeof(SetHookEnabledRequest))]
|
||||
[JsonSerializable(typeof(HookEnabledAck))]
|
||||
[JsonSerializable(typeof(RefusedAck))]
|
||||
[JsonSerializable(typeof(PauseCaptureRequest))]
|
||||
[JsonSerializable(typeof(ResumeCaptureRequest))]
|
||||
[JsonSerializable(typeof(PauseAck))]
|
||||
[JsonSerializable(typeof(StopSessionRequest))]
|
||||
[JsonSerializable(typeof(StopAck))]
|
||||
[JsonSerializable(typeof(UpdateRulesRequest))]
|
||||
[JsonSerializable(typeof(UpdateRulesAck))]
|
||||
[JsonSerializable(typeof(ShutdownRequest))]
|
||||
[JsonSerializable(typeof(ShutdownAck))]
|
||||
public sealed partial class IpcJsonContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// The message set of 07_IPC §Messages — the READ half as of P3 PR-1 (2026-09-13): Hello/GetStatus/Ping and
|
||||
// the Agent → UI events. The command half (SetWatchlist, SetHookEnabled, LaunchGame, Pause/Resume, StopSession,
|
||||
// UpdateRules, Shutdown) is PR-1b (HANDOFF §P3), and none of it is declared here until it has a handler — a
|
||||
// declared message nobody answers is the §S29(c) shape.
|
||||
// The message set of 07_IPC §Messages: the READ half (P3 PR-1, 2026-09-13: Hello/GetStatus/Ping and the
|
||||
// Agent → UI events) and the COMMAND half (P3 PR-1b, the same day: SetWatchlist, LaunchGame, SetHookEnabled,
|
||||
// Pause/Resume, StopSession, UpdateRules, Shutdown). Every type here has a handler in AgentRequestHandler or
|
||||
// AgentCommandHandler — a declared message nobody answers is the §S29(c) shape.
|
||||
//
|
||||
// ONE FILE FOR THE WHOLE SET, deliberately (MA0048 is suppressed for this project, see the csproj): the types
|
||||
// are one wire contract read against one table in 07_IPC, and the property names ARE the JSON — camelCase by the
|
||||
@@ -24,6 +24,26 @@ public static class IpcMessageType
|
||||
/// <summary>The Agent's answer when it cannot answer: unknown type, malformed payload, protocol mismatch.</summary>
|
||||
public const string Error = "Error";
|
||||
|
||||
public const string SetWatchlist = "SetWatchlist";
|
||||
public const string WatchlistAck = "WatchlistAck";
|
||||
public const string LaunchGame = "LaunchGame";
|
||||
public const string LaunchAck = "LaunchAck";
|
||||
public const string SetHookEnabled = "SetHookEnabled";
|
||||
public const string HookEnabledAck = "HookEnabledAck";
|
||||
|
||||
/// <summary>The Agent's answer to <c>SetHookEnabled</c> when its own pre-scan said no (07_IPC: "may reply Refused").</summary>
|
||||
public const string Refused = "Refused";
|
||||
|
||||
public const string PauseCapture = "PauseCapture";
|
||||
public const string ResumeCapture = "ResumeCapture";
|
||||
public const string PauseAck = "PauseAck";
|
||||
public const string StopSession = "StopSession";
|
||||
public const string StopAck = "StopAck";
|
||||
public const string UpdateRules = "UpdateRules";
|
||||
public const string UpdateRulesAck = "UpdateRulesAck";
|
||||
public const string Shutdown = "Shutdown";
|
||||
public const string ShutdownAck = "ShutdownAck";
|
||||
|
||||
public const string SessionStarted = "SessionStarted";
|
||||
public const string SessionProgress = "SessionProgress";
|
||||
public const string SessionCompleted = "SessionCompleted";
|
||||
@@ -40,6 +60,13 @@ public static class IpcErrorCode
|
||||
public const string Malformed = "Malformed";
|
||||
public const string ProtocolMismatch = "ProtocolMismatch";
|
||||
public const string HandlerFaulted = "HandlerFaulted";
|
||||
|
||||
/// <summary><c>SetHookEnabled true</c> passed the pre-scan and was NOT stamped: FR-2.1's reviewed disclosure does not exist yet (P3 PR-4).</summary>
|
||||
public const string DisclosureUnavailable = "DisclosureUnavailable";
|
||||
|
||||
public const string UnknownGame = "UnknownGame";
|
||||
|
||||
public const string ExecutableUnreadable = "ExecutableUnreadable";
|
||||
}
|
||||
|
||||
/// <summary>Codes a <see cref="CaptureErrorEvent"/> carries (<c>07_IPC</c> §Messages, <c>CaptureError</c>).</summary>
|
||||
@@ -83,7 +110,7 @@ public sealed record ActiveSession(Guid SessionGuid, long GameId, string? GameNa
|
||||
/// <c>StatusAck</c>. <see cref="State"/> is <c>idle</c>, <c>recording</c> (a session runs, nothing hooked) or
|
||||
/// <c>capturing</c> (at least one ring attached); <see cref="ActiveSession"/> is the hooked one when there is one.
|
||||
/// </summary>
|
||||
public sealed record StatusAck(string State, ActiveSession? ActiveSession, int? Tier, IReadOnlyList<ActiveSession> ActiveSessions);
|
||||
public sealed record StatusAck(string State, ActiveSession? ActiveSession, int? Tier, IReadOnlyList<ActiveSession> ActiveSessions, bool Paused = false);
|
||||
|
||||
public sealed record PingRequest;
|
||||
|
||||
@@ -170,3 +197,54 @@ public sealed record CaptureDegradedEvent(Guid SessionGuid, int From, int To, st
|
||||
public sealed record SafetyUnhookEvent(Guid SessionGuid, string? Family, string? Signal);
|
||||
|
||||
public sealed record CaptureErrorEvent(Guid? SessionGuid, string Code, string Message);
|
||||
|
||||
// ----------------------------------------------------------------------------------------------------------------
|
||||
// The command half (P3 PR-1b). 07_IPC §The pipe is not a trust boundary: none of these carries a verdict, a
|
||||
// clearance, a consent record or a rules source — a client asks, the Agent establishes the fact itself.
|
||||
// ----------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>One watchlist entry: identity only. <c>GameId</c> is the client's hint and is never trusted over the path.</summary>
|
||||
public sealed record WatchlistEntry(long? GameId, string ExePath);
|
||||
|
||||
/// <summary><c>SetWatchlist</c>: ensure a <c>games</c> row per entry (hooking OFF when new). Removal is FR-1.4's, not this message's.</summary>
|
||||
public sealed record SetWatchlistRequest(IReadOnlyList<WatchlistEntry> Entries);
|
||||
|
||||
public sealed record WatchlistGame(long GameId, string ExePath, string Name);
|
||||
|
||||
public sealed record WatchlistAck(IReadOnlyList<WatchlistGame> Games, IReadOnlyList<string> Unreadable);
|
||||
|
||||
/// <summary><c>LaunchGame</c>: start the title in launch mode (<c>04_CAPTURE</c> §Launch mode) and run the launcher election after it.</summary>
|
||||
public sealed record LaunchGameRequest(long GameId, string? Arguments);
|
||||
|
||||
public sealed record LaunchAck(long GameId, bool Accepted, string Outcome, Guid? SessionGuid);
|
||||
|
||||
/// <summary>
|
||||
/// <c>SetHookEnabled</c>. <c>DisclosureVersion</c> is the version of the reviewed FR-2.1 text the client showed; the
|
||||
/// Agent compares it to its own and stamps from its own clock (P3 PR-4). It is never a consent timestamp.
|
||||
/// </summary>
|
||||
public sealed record SetHookEnabledRequest(long GameId, bool Enabled, string? DisclosureVersion);
|
||||
|
||||
/// <summary><c>Outcome</c> is the store's word (<c>Written</c>, <c>NotFound</c>, …); <c>Prescan</c> is <c>clean</c> when one ran and passed.</summary>
|
||||
public sealed record HookEnabledAck(long GameId, bool Enabled, string Outcome, string? Prescan);
|
||||
|
||||
/// <summary>The Agent's pre-scan refused to enable: the reason, and the family/signal when it named one. The block is on the row.</summary>
|
||||
public sealed record RefusedAck(long GameId, string Reason, string? Family, string? Signal);
|
||||
|
||||
public sealed record PauseCaptureRequest;
|
||||
|
||||
public sealed record ResumeCaptureRequest;
|
||||
|
||||
public sealed record PauseAck(bool Paused);
|
||||
|
||||
public sealed record StopSessionRequest(Guid SessionGuid);
|
||||
|
||||
public sealed record StopAck(Guid SessionGuid, bool Accepted, string? Reason);
|
||||
|
||||
/// <summary><c>UpdateRules</c>: a trigger, no payload — the Agent re-reads only its own rules copy (07_IPC).</summary>
|
||||
public sealed record UpdateRulesRequest;
|
||||
|
||||
public sealed record UpdateRulesAck(string Outcome);
|
||||
|
||||
public sealed record ShutdownRequest;
|
||||
|
||||
public sealed record ShutdownAck;
|
||||
@@ -28,6 +28,8 @@
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
<PackageReference Include="FluentAssertions" />
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<!-- The pipe e2e logs the composition's Serilog lines to its scratch directory, so a hang leaves evidence. -->
|
||||
<PackageReference Include="Serilog.Sinks.File" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -2,20 +2,23 @@ using System.Diagnostics;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Agent.Composition;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Ipc;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Infrastructure.Ipc;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using FrameLedger.Shared.Ipc;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Serilog;
|
||||
|
||||
namespace FrameLedger.Agent.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The pipe's read half end to end (P3 PR-1): the Agent's own composition — the watcher, the recorder, the pipe
|
||||
/// server — in this process over a scratch ledger and a pipe named for this test, our harness discovered by the
|
||||
/// watcher, and a client that hears <c>SessionStarted</c>, at least three <c>SessionProgress</c> a second apart,
|
||||
/// and <c>SessionCompleted</c> for the same guid. Then <c>GetStatus</c> is idle again.
|
||||
/// The pipe end to end (P3 PR-1 read half, PR-1b command half): the Agent's own composition — the watcher, the
|
||||
/// recorder, the pipe server — in this process over a scratch ledger and a pipe named for this test, our
|
||||
/// harness discovered by the watcher or started by <c>LaunchGame</c>, and a client that hears the session's
|
||||
/// story and drives it: pause, resume, stop; then the commands that touch no session.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -38,6 +41,7 @@ namespace FrameLedger.Agent.Tests;
|
||||
public sealed class PipeEndToEndTests : IDisposable
|
||||
{
|
||||
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(45);
|
||||
private static readonly TimeSpan _ack = TimeSpan.FromSeconds(20);
|
||||
|
||||
private static string Harness => Path.Combine(AppContext.BaseDirectory, "hook-harness.exe");
|
||||
|
||||
@@ -71,15 +75,29 @@ public sealed class PipeEndToEndTests : IDisposable
|
||||
_pipeName.Should().NotBe(IpcProtocol.PipeName, "a test must never answer on the product's pipe");
|
||||
}
|
||||
|
||||
private void StageTarget()
|
||||
[Fact]
|
||||
public async Task AWatchedHarnessSessionIsNarratedPausedResumedAndStoppedOverThePipe()
|
||||
{
|
||||
File.Exists(Harness).Should().BeTrue("hook-harness.exe must be staged beside the test binary (FrameLedger.DrainFixtures.targets)");
|
||||
Directory.CreateDirectory(_dataDir);
|
||||
File.Copy(Harness, ConsentedExecutable, overwrite: true);
|
||||
StageTarget();
|
||||
var paths = new AgentPaths(_dataDir);
|
||||
Directory.CreateDirectory(paths.Logs);
|
||||
Directory.CreateDirectory(paths.Tmp);
|
||||
|
||||
LedgerDatabase db = await LedgerDatabase.OpenAsync(paths.Database, ct: Ct).ConfigureAwait(true);
|
||||
await using (db.ConfigureAwait(true))
|
||||
{
|
||||
await GrantConsentAsync(db).ConfigureAwait(true);
|
||||
var lifetime = new RecordingLifetime();
|
||||
ServiceProvider services = new ServiceCollection().AddSingleton<IAgentLifetime>(lifetime).AddFrameLedgerAgent(db, paths, _pipeName).BuildServiceProvider();
|
||||
await using (services.ConfigureAwait(true))
|
||||
{
|
||||
await RunWatchedScenarioAsync(services, lifetime).ConfigureAwait(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AWatchedHarnessSessionIsNarratedOverThePipeFromStartToCompletion()
|
||||
public async Task LaunchGameStartsTheHarnessInLaunchModeAndNarratesItToTheEnd()
|
||||
{
|
||||
StageTarget();
|
||||
var paths = new AgentPaths(_dataDir);
|
||||
@@ -93,11 +111,24 @@ public sealed class PipeEndToEndTests : IDisposable
|
||||
ServiceProvider services = new ServiceCollection().AddFrameLedgerAgent(db, paths, _pipeName).BuildServiceProvider();
|
||||
await using (services.ConfigureAwait(true))
|
||||
{
|
||||
await RunAgentAndNarrateAsync(services).ConfigureAwait(true);
|
||||
await RunLaunchScenarioAsync(services).ConfigureAwait(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void StageTarget()
|
||||
{
|
||||
File.Exists(Harness).Should().BeTrue("hook-harness.exe must be staged beside the test binary (FrameLedger.DrainFixtures.targets)");
|
||||
Directory.CreateDirectory(_dataDir);
|
||||
File.Copy(Harness, ConsentedExecutable, overwrite: true);
|
||||
// The composition logs through Serilog's static logger; in this process nothing configures it, so the
|
||||
// orchestrator's and the pipe's lines would vanish. A file in the scratch directory is what a hang leaves behind.
|
||||
Directory.CreateDirectory(Path.Combine(_dataDir, "logs"));
|
||||
Log.Logger = new LoggerConfiguration().MinimumLevel.Information()
|
||||
.WriteTo.File(Path.Combine(_dataDir, "logs", "e2e-.log"), formatProvider: System.Globalization.CultureInfo.InvariantCulture, rollingInterval: RollingInterval.Day)
|
||||
.CreateLogger();
|
||||
}
|
||||
|
||||
private async Task GrantConsentAsync(LedgerDatabase db)
|
||||
{
|
||||
ExecutableFingerprint fingerprint = FrameLedger.Infrastructure.Io.ExecutableIdentity.Read(ConsentedExecutable)!.Value;
|
||||
@@ -111,8 +142,15 @@ public sealed class PipeEndToEndTests : IDisposable
|
||||
written.Should().Be(ConsentWriteOutcome.Written);
|
||||
}
|
||||
|
||||
/// <summary>The Agent's serve loop and pipe, a client, the harness, and the story the client hears.</summary>
|
||||
private async Task RunAgentAndNarrateAsync(ServiceProvider services)
|
||||
private sealed class RecordingLifetime : IAgentLifetime
|
||||
{
|
||||
public int ShutdownRequests { get; private set; }
|
||||
|
||||
public void RequestShutdown() => ShutdownRequests++;
|
||||
}
|
||||
|
||||
/// <summary>The Agent's serve loop and pipe, a client, the harness, and the story the client hears and drives.</summary>
|
||||
private async Task RunWatchedScenarioAsync(ServiceProvider services, RecordingLifetime lifetime)
|
||||
{
|
||||
PipeServer server = services.GetRequiredService<PipeServer>();
|
||||
CaptureOrchestrator orchestrator = services.GetRequiredService<CaptureOrchestrator>();
|
||||
@@ -126,68 +164,212 @@ public sealed class PipeEndToEndTests : IDisposable
|
||||
{
|
||||
client = NewClient();
|
||||
await client.ConnectAsync(TimeSpan.FromSeconds(10), Ct).ConfigureAwait(false);
|
||||
HelloAck hello = await client.HelloAsync("test", _timeout, Ct).ConfigureAwait(false);
|
||||
hello.Protocol.Should().Be(IpcProtocol.Version);
|
||||
hello.OverlayBuildId.Should().NotBeNullOrEmpty("the guard answers its build id");
|
||||
hello.TelemetrySource.Should().Contain("l1", "the Agent composes L1 + L2 + L3");
|
||||
hello.Pid.Should().Be(Environment.ProcessId);
|
||||
(await client.GetStatusAsync(_timeout, Ct).ConfigureAwait(false)).State.Should().Be("idle");
|
||||
await HelloAsync(client).ConfigureAwait(false);
|
||||
|
||||
harness = Process.Start(new ProcessStartInfo(ConsentedExecutable, "--real --hold-presenting 12") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true })!;
|
||||
harness = Process.Start(new ProcessStartInfo(ConsentedExecutable, "--real --hold-presenting 40") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true })!;
|
||||
int pid = harness.Id;
|
||||
Narration story = await ReadStoryAsync(client, s => s.Pid == pid, s => s.Progress.Count >= 3).ConfigureAwait(false);
|
||||
AssertNarration(story, pid);
|
||||
|
||||
Narration story = await ReadStoryAsync(client, harness.Id).ConfigureAwait(false);
|
||||
AssertStory(story, harness.Id);
|
||||
|
||||
(await client.GetStatusAsync(_timeout, Ct).ConfigureAwait(false)).State.Should().Be("idle");
|
||||
await PauseResumeAsync(client).ConfigureAwait(false);
|
||||
await StopAndAssertAsync(client, story, harness).ConfigureAwait(false);
|
||||
await SessionlessCommandsAsync(client, services, lifetime).ConfigureAwait(false);
|
||||
server.RejectedClients.Should().Be(0);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (client is not null)
|
||||
await TearDownAsync(client, harness, stop).ConfigureAwait(false);
|
||||
await JoinAsync(serving, watching).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunLaunchScenarioAsync(ServiceProvider services)
|
||||
{
|
||||
PipeServer server = services.GetRequiredService<PipeServer>();
|
||||
CaptureOrchestrator orchestrator = services.GetRequiredService<CaptureOrchestrator>();
|
||||
long gameId = (await services.GetRequiredService<IGameRepository>().FindAsync(ConsentedExecutable, Ct).ConfigureAwait(false))!.Id;
|
||||
using var stop = new CancellationTokenSource();
|
||||
Task serving = server.RunAsync(stop.Token);
|
||||
Task watching = orchestrator.RunAsync(stop.Token);
|
||||
|
||||
PipeClient? client = null;
|
||||
int launchedPid = 0;
|
||||
try
|
||||
{
|
||||
client = NewClient();
|
||||
await client.ConnectAsync(TimeSpan.FromSeconds(10), Ct).ConfigureAwait(false);
|
||||
await HelloAsync(client).ConfigureAwait(false);
|
||||
|
||||
LaunchAck launch = await client.RequestAsync<LaunchGameRequest, LaunchAck>(IpcMessageType.LaunchGame,
|
||||
new LaunchGameRequest(gameId, "--real --hold-presenting 8"), IpcMessageType.LaunchAck, _ack, Ct).ConfigureAwait(false);
|
||||
launch.Accepted.Should().BeTrue(launch.Outcome);
|
||||
launch.SessionGuid.Should().NotBeNull();
|
||||
|
||||
LaunchAck again = await client.RequestAsync<LaunchGameRequest, LaunchAck>(IpcMessageType.LaunchGame,
|
||||
new LaunchGameRequest(gameId, ""), IpcMessageType.LaunchAck, _ack, Ct).ConfigureAwait(false);
|
||||
again.Accepted.Should().BeFalse("one session per game at a time");
|
||||
again.Outcome.Should().Be(nameof(LaunchOutcome.SessionRunning));
|
||||
|
||||
Narration story = await ReadStoryAsync(client, s => s.SessionGuid == launch.SessionGuid, static s => s.Completed is not null).ConfigureAwait(false);
|
||||
story.Started.Should().NotBeNull("the Agent started the harness itself and attached to its ring");
|
||||
launchedPid = story.Started!.Pid;
|
||||
story.Started.Tier.Should().Be(1);
|
||||
story.Progress.Count.Should().BeGreaterThanOrEqualTo(2, "1 Hz over an 8 s hold");
|
||||
story.Completed!.Reason.Should().Be(nameof(Application.Capture.SessionEndReason.TargetExited), "the harness ended its hold");
|
||||
story.Completed.Tier.Should().Be(1);
|
||||
(await client.GetStatusAsync(_ack, Ct).ConfigureAwait(false)).State.Should().Be("idle");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (launchedPid != 0)
|
||||
{
|
||||
await client.DisposeAsync().ConfigureAwait(false);
|
||||
KillIfRunning(launchedPid);
|
||||
}
|
||||
|
||||
if (harness is not null)
|
||||
{
|
||||
if (!harness.HasExited)
|
||||
{
|
||||
harness.Kill(entireProcessTree: true);
|
||||
}
|
||||
await TearDownAsync(client, null, stop).ConfigureAwait(false);
|
||||
await JoinAsync(serving, watching).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
harness.Dispose();
|
||||
/// <summary>The serve loop and the pipe end with the token; both tasks are locals of the caller, joined here.</summary>
|
||||
private static async Task JoinAsync(Task serving, Task watching)
|
||||
{
|
||||
Task both = Task.WhenAll(serving, watching);
|
||||
try
|
||||
{
|
||||
await both.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task HelloAsync(PipeClient client)
|
||||
{
|
||||
HelloAck hello = await client.HelloAsync("test", _ack, Ct).ConfigureAwait(false);
|
||||
hello.Protocol.Should().Be(IpcProtocol.Version);
|
||||
hello.OverlayBuildId.Should().NotBeNullOrEmpty("the guard answers its build id");
|
||||
hello.TelemetrySource.Should().Contain("l1", "the Agent composes L1 + L2 + L3");
|
||||
hello.Pid.Should().Be(Environment.ProcessId);
|
||||
(await client.GetStatusAsync(_ack, Ct).ConfigureAwait(false)).State.Should().Be("idle");
|
||||
}
|
||||
|
||||
private static void AssertNarration(Narration story, int harnessPid)
|
||||
{
|
||||
story.Started.Should().NotBeNull("the watcher found the harness and the ring was attached");
|
||||
story.Started!.Tier.Should().Be(1);
|
||||
story.Started.Pid.Should().Be(harnessPid);
|
||||
story.Progress.Count.Should().BeGreaterThanOrEqualTo(3, "1 Hz while the harness presents");
|
||||
story.Progress.Should().AllSatisfy(p => p.SessionGuid.Should().Be(story.Started.SessionGuid));
|
||||
story.Progress.Skip(1).Should().Contain(static p => p.PresentedFps5s > 0, "the harness presents at ~120/s");
|
||||
story.Progress.Should().AllSatisfy(static p => p.NativeFps5s.Should().BeNull("the harness has no frame generation, so no Native number may appear"));
|
||||
story.ProgressSpacing.Min().Should().BeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(850), "rate-limited to the interval");
|
||||
}
|
||||
|
||||
private static async Task PauseResumeAsync(PipeClient client)
|
||||
{
|
||||
PauseAck paused = await client.RequestAsync<PauseCaptureRequest, PauseAck>(IpcMessageType.PauseCapture, new PauseCaptureRequest(), IpcMessageType.PauseAck, _ack, Ct).ConfigureAwait(false);
|
||||
paused.Paused.Should().BeTrue();
|
||||
StatusAck status = await client.GetStatusAsync(_ack, Ct).ConfigureAwait(false);
|
||||
status.Paused.Should().BeTrue("FR-3.9's pause rides beside the session state");
|
||||
status.State.Should().Be("capturing", "a paused session is still a hooked, supervised session");
|
||||
|
||||
PauseAck resumed = await client.RequestAsync<ResumeCaptureRequest, PauseAck>(IpcMessageType.ResumeCapture, new ResumeCaptureRequest(), IpcMessageType.PauseAck, _ack, Ct).ConfigureAwait(false);
|
||||
resumed.Paused.Should().BeFalse();
|
||||
(await client.GetStatusAsync(_ack, Ct).ConfigureAwait(false)).Paused.Should().BeFalse();
|
||||
}
|
||||
|
||||
private static async Task StopAndAssertAsync(PipeClient client, Narration story, Process harness)
|
||||
{
|
||||
Guid guid = story.Started!.SessionGuid;
|
||||
StopAck stopAck = await client.RequestAsync<StopSessionRequest, StopAck>(IpcMessageType.StopSession, new StopSessionRequest(guid), IpcMessageType.StopAck, _ack, Ct).ConfigureAwait(false);
|
||||
stopAck.Accepted.Should().BeTrue(stopAck.Reason);
|
||||
|
||||
Narration ended = await ReadStoryAsync(client, s => s.SessionGuid == guid, static s => s.Completed is not null, guid).ConfigureAwait(false);
|
||||
ended.Completed.Should().NotBeNull("the stop ends the session at its next tick");
|
||||
ended.Completed!.SessionGuid.Should().Be(guid);
|
||||
ended.Completed.Reason.Should().Be(nameof(Application.Capture.SessionEndReason.StoppedByUser));
|
||||
ended.Completed.Tier.Should().Be(1);
|
||||
ended.Completed.ExitStatus.Should().Be("normal", "a user stop is not a crash and not a safety stop");
|
||||
harness.HasExited.Should().BeFalse("the stop is the session's, never the target's");
|
||||
(await client.GetStatusAsync(_ack, Ct).ConfigureAwait(false)).State.Should().Be("idle");
|
||||
|
||||
// A second stop for the same guid may still be accepted for a moment: SessionCompleted is published from
|
||||
// the recorder's Ended, a few microseconds before the session's task completes and is reaped — measured
|
||||
// 2026-09-13 — and a stop of an ending session is harmless. A guid nobody ever ran is the honest negative.
|
||||
StopAck stranger = await client.RequestAsync<StopSessionRequest, StopAck>(IpcMessageType.StopSession, new StopSessionRequest(Guid.NewGuid()), IpcMessageType.StopAck, _ack, Ct).ConfigureAwait(false);
|
||||
stranger.Accepted.Should().BeFalse("nothing runs under a guid nobody started");
|
||||
}
|
||||
|
||||
private async Task SessionlessCommandsAsync(PipeClient client, ServiceProvider services, RecordingLifetime lifetime)
|
||||
{
|
||||
long gameId = (await services.GetRequiredService<IGameRepository>().FindAsync(ConsentedExecutable, Ct).ConfigureAwait(false))!.Id;
|
||||
|
||||
WatchlistAck watchlist = await client.RequestAsync<SetWatchlistRequest, WatchlistAck>(IpcMessageType.SetWatchlist,
|
||||
new SetWatchlistRequest([new WatchlistEntry(null, ConsentedExecutable), new WatchlistEntry(null, Path.Combine(_dataDir, "nothing-here.exe"))]),
|
||||
IpcMessageType.WatchlistAck, _ack, Ct).ConfigureAwait(false);
|
||||
watchlist.Games.Should().ContainSingle().Which.GameId.Should().Be(gameId, "the existing row is ensured, not duplicated");
|
||||
watchlist.Unreadable.Should().ContainSingle();
|
||||
|
||||
HookEnabledAck revoked = await client.RequestAsync<SetHookEnabledRequest, HookEnabledAck>(IpcMessageType.SetHookEnabled,
|
||||
new SetHookEnabledRequest(gameId, Enabled: false, null), IpcMessageType.HookEnabledAck, _ack, Ct).ConfigureAwait(false);
|
||||
revoked.Enabled.Should().BeFalse();
|
||||
revoked.Outcome.Should().Be(nameof(ConsentWriteOutcome.Written));
|
||||
|
||||
Func<Task> enable = async () => await client.RequestAsync<SetHookEnabledRequest, HookEnabledAck>(IpcMessageType.SetHookEnabled,
|
||||
new SetHookEnabledRequest(gameId, Enabled: true, "client-says-so"), IpcMessageType.HookEnabledAck, _ack, Ct).ConfigureAwait(false);
|
||||
(await enable.Should().ThrowAsync<IpcRequestException>().ConfigureAwait(false)).Which.Code.Should().Be(IpcErrorCode.DisclosureUnavailable,
|
||||
"the real pre-scan of the scratch directory is clean, and nothing is stamped without the reviewed disclosure (PR-4)");
|
||||
(await new SqliteGameConsentStore(services.GetRequiredService<LedgerDatabase>()).FindAsync(ConsentedExecutable, Ct).ConfigureAwait(false)).HookEnabled.Should().BeFalse();
|
||||
|
||||
UpdateRulesAck rules = await client.RequestAsync<UpdateRulesRequest, UpdateRulesAck>(IpcMessageType.UpdateRules, new UpdateRulesRequest(), IpcMessageType.UpdateRulesAck, _ack, Ct).ConfigureAwait(false);
|
||||
rules.Outcome.Should().NotBeNullOrEmpty();
|
||||
|
||||
await client.RequestAsync<ShutdownRequest, ShutdownAck>(IpcMessageType.Shutdown, new ShutdownRequest(), IpcMessageType.ShutdownAck, _ack, Ct).ConfigureAwait(false);
|
||||
lifetime.ShutdownRequests.Should().Be(1, "Shutdown asks the host's lifetime and nothing else");
|
||||
}
|
||||
|
||||
private static async Task TearDownAsync(PipeClient? client, Process? harness, CancellationTokenSource stop)
|
||||
{
|
||||
if (client is not null)
|
||||
{
|
||||
await client.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (harness is not null)
|
||||
{
|
||||
if (!harness.HasExited)
|
||||
{
|
||||
harness.Kill(entireProcessTree: true);
|
||||
}
|
||||
|
||||
await stop.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(serving, watching).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
harness.Dispose();
|
||||
}
|
||||
|
||||
await stop.CancelAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static void KillIfRunning(int pid)
|
||||
{
|
||||
try
|
||||
{
|
||||
using Process p = Process.GetProcessById(pid);
|
||||
if (!p.HasExited)
|
||||
{
|
||||
p.Kill(entireProcessTree: true);
|
||||
}
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Born here so the caller's try/finally owns it; CA2000 tracks only what a method news itself.</summary>
|
||||
private PipeClient NewClient() => new(_pipeName);
|
||||
|
||||
private static void AssertStory(Narration story, int harnessPid)
|
||||
{
|
||||
story.Started.Should().NotBeNull("the watcher found the harness and the ring was attached");
|
||||
story.Started!.Tier.Should().Be(1);
|
||||
story.Started.Pid.Should().Be(harnessPid);
|
||||
story.Progress.Count.Should().BeGreaterThanOrEqualTo(3, "1 Hz over a 12 s hold");
|
||||
story.Progress.Should().AllSatisfy(p => p.SessionGuid.Should().Be(story.Started.SessionGuid));
|
||||
story.Progress.Skip(1).Should().Contain(static p => p.PresentedFps5s > 0, "the harness presents at ~120/s");
|
||||
story.Progress.Should().AllSatisfy(static p => p.NativeFps5s.Should().BeNull("the harness has no frame generation, so no Native number may appear"));
|
||||
story.ProgressSpacing.Min().Should().BeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(850), "rate-limited to the interval");
|
||||
story.Completed.Should().NotBeNull();
|
||||
story.Completed!.SessionGuid.Should().Be(story.Started.SessionGuid);
|
||||
story.Completed.Tier.Should().Be(1);
|
||||
story.Completed.Finalize.Should().Be("discarded", "12 s is under the product's 30 s minimum; the pipe, not the row, is under test");
|
||||
}
|
||||
|
||||
private sealed class Narration
|
||||
{
|
||||
public SessionStartedEvent? Started { get; set; }
|
||||
@@ -199,13 +381,21 @@ public sealed class PipeEndToEndTests : IDisposable
|
||||
public SessionCompletedEvent? Completed { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Our harness's story only: keyed on its pid at the start, on the guid from then on; other sessions are ignored.</summary>
|
||||
private static async Task<Narration> ReadStoryAsync(PipeClient client, int harnessPid)
|
||||
/// <summary>
|
||||
/// One session's story: started when <paramref name="mine"/> says so (or already known by <paramref name="known"/>),
|
||||
/// then its progress and completion by guid, until <paramref name="done"/> or the timeout. Other sessions' events are ignored.
|
||||
/// </summary>
|
||||
private static async Task<Narration> ReadStoryAsync(PipeClient client, Func<SessionStartedEvent, bool> mine, Func<Narration, bool> done, Guid? known = null)
|
||||
{
|
||||
var story = new Narration();
|
||||
if (known is { } g0)
|
||||
{
|
||||
story.Started = new SessionStartedEvent(g0, 0, null, 0, 1, DateTimeOffset.UtcNow);
|
||||
}
|
||||
|
||||
var clock = Stopwatch.StartNew();
|
||||
TimeSpan? lastProgress = null;
|
||||
while (clock.Elapsed < _timeout)
|
||||
while (clock.Elapsed < _timeout && !done(story))
|
||||
{
|
||||
IpcEnvelope e = await client.Events.ReadAsync(Ct).AsTask().WaitAsync(_timeout - clock.Elapsed, Ct).ConfigureAwait(false);
|
||||
Guid? ours = story.Started?.SessionGuid;
|
||||
@@ -213,7 +403,7 @@ public sealed class PipeEndToEndTests : IDisposable
|
||||
{
|
||||
case IpcMessageType.SessionStarted when ours is null:
|
||||
SessionStartedEvent? started = IpcCodec.Payload<SessionStartedEvent>(e);
|
||||
if (started?.Pid == harnessPid)
|
||||
if (started is not null && mine(started))
|
||||
{
|
||||
story.Started = started;
|
||||
}
|
||||
@@ -239,7 +429,6 @@ public sealed class PipeEndToEndTests : IDisposable
|
||||
if (completed.SessionGuid == g)
|
||||
{
|
||||
story.Completed = completed;
|
||||
return story;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
@@ -235,7 +235,7 @@ public sealed class CaptureSessionTests : IAsyncDisposable
|
||||
|
||||
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) =>
|
||||
CaptureOptions? options = null, IKillSwitch? killSwitch = null, ICapturePauseSource? pause = null) =>
|
||||
new(store,
|
||||
new HookedCaptureGate(guard),
|
||||
guard,
|
||||
@@ -250,7 +250,111 @@ public sealed class CaptureSessionTests : IAsyncDisposable
|
||||
MaxDuration = TimeSpan.FromMilliseconds(120),
|
||||
LogFlushGrace = TimeSpan.FromMilliseconds(1),
|
||||
},
|
||||
killSwitch: killSwitch);
|
||||
killSwitch: killSwitch,
|
||||
pause: pause);
|
||||
|
||||
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 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");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheModuleSnapshotIsTakenBesideEveryGuardScanAndOnceMoreBeforeTheLastDrain()
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
using System.Text;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.AntiCheat;
|
||||
using FrameLedger.Application.Capture;
|
||||
using FrameLedger.Application.Consent;
|
||||
using FrameLedger.Application.Ipc;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Tests.Recording;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Domain.AntiCheat;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using FrameLedger.Shared.Ipc;
|
||||
|
||||
namespace FrameLedger.Application.Tests.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// The command half (<c>07_IPC</c> §Messages, UI → Agent) over fakes and the real SQLite consent store: every
|
||||
/// message asks, and what the Agent establishes for itself is observed on the store, the orchestrator, the pause
|
||||
/// and the lifetime. The rule under test is <c>07_IPC</c> §The pipe is not a trust boundary — in particular that
|
||||
/// <c>SetHookEnabled true</c> runs the pre-scan, records a block, and stamps NOTHING while the reviewed
|
||||
/// disclosure does not exist.
|
||||
/// </summary>
|
||||
public sealed class AgentCommandHandlerTests : IAsyncDisposable
|
||||
{
|
||||
private const string _exe = @"C:\Games\Title\game.exe";
|
||||
|
||||
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-commands-" + Guid.NewGuid().ToString("N"));
|
||||
private LedgerDatabase? _db;
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
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)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeGuard : IAntiCheatGuard
|
||||
{
|
||||
public AntiCheatVerdict PreScan { get; set; } = AntiCheatVerdict.Allowed();
|
||||
|
||||
public List<string> Scanned { get; } = [];
|
||||
|
||||
public ValueTask<AntiCheatVerdict> EvaluateAsync(int targetPid, CancellationToken ct = default) => ValueTask.FromResult(AntiCheatVerdict.Allowed());
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectAsync(int targetPid, string payloadPath, CancellationToken ct = default) =>
|
||||
throw new InvalidOperationException("a command never injects");
|
||||
|
||||
public ValueTask<AntiCheatVerdict> GuardedInjectWhenReadyAsync(int targetPid, string payloadPath, int timeoutMs, CancellationToken ct = default) =>
|
||||
throw new InvalidOperationException("a command never injects");
|
||||
|
||||
public ValueTask<AntiCheatVerdict> PreScanGameDirectoryAsync(string gameDirectory, CancellationToken ct = default)
|
||||
{
|
||||
Scanned.Add(gameDirectory);
|
||||
return ValueTask.FromResult(PreScan);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeIdentity : IExecutableIdentitySource
|
||||
{
|
||||
public HashSet<string> Unreadable { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public ExecutableFingerprint? Read(string normalisedExePath) =>
|
||||
Unreadable.Contains(normalisedExePath) ? null : new ExecutableFingerprint { ExePath = normalisedExePath, SizeBytes = 90_000, MtimeUnixMs = 1_700_000_000_000 };
|
||||
|
||||
public string Normalise(string exePath) => exePath.ToUpperInvariant();
|
||||
}
|
||||
|
||||
private sealed class FakeRecorder : ISessionRecorder
|
||||
{
|
||||
public async Task<RecordedSession> RecordAsync(RecordRequest request, CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(Timeout.InfiniteTimeSpan, ct).ConfigureAwait(false);
|
||||
throw new OperationCanceledException(ct);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeSnapshots : IProcessSnapshotSource
|
||||
{
|
||||
public IReadOnlyList<ProcessSnapshot> Take() => [];
|
||||
}
|
||||
|
||||
private sealed class FakeLifetime : IAgentLifetime
|
||||
{
|
||||
public int Requests { get; private set; }
|
||||
|
||||
public void RequestShutdown() => Requests++;
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public required AgentCommandHandler Handler { get; init; }
|
||||
|
||||
public required FakeGameRepository Games { get; init; }
|
||||
|
||||
public required SqliteGameConsentStore Consent { get; init; }
|
||||
|
||||
public required FakeGuard Guard { get; init; }
|
||||
|
||||
public required FakeIdentity Identity { get; init; }
|
||||
|
||||
public required CaptureOrchestrator Orchestrator { get; init; }
|
||||
|
||||
public required CapturePause Pause { get; init; }
|
||||
|
||||
public required FakeLifetime Lifetime { get; init; }
|
||||
|
||||
public int RulesUpdates { get; set; }
|
||||
}
|
||||
|
||||
private async Task<Harness> BuildAsync(bool consented = true)
|
||||
{
|
||||
_db ??= await LedgerDatabase.OpenAsync(Path.Combine(_dir, LedgerPaths.DatabaseFileName), ct: Ct).ConfigureAwait(false);
|
||||
var consent = new SqliteGameConsentStore(_db);
|
||||
var games = new FakeGameRepository();
|
||||
var identity = new FakeIdentity();
|
||||
var guard = new FakeGuard();
|
||||
var pause = new CapturePause();
|
||||
var lifetime = new FakeLifetime();
|
||||
await games.EnsureAsync(identity.Read(_exe)!.Value, "Title", Ct).ConfigureAwait(false);
|
||||
if (consented)
|
||||
{
|
||||
await consent.RecordOperatorAcknowledgementAsync(new OperatorAcknowledgement
|
||||
{
|
||||
Fingerprint = identity.Read(_exe)!.Value,
|
||||
DisclosureVersion = "test/1",
|
||||
AcknowledgedAt = DateTimeOffset.UnixEpoch,
|
||||
}, Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var orchestrator = new CaptureOrchestrator(new FakeRecorder(), games, new FakeSnapshots(), identity,
|
||||
new OrchestratorOptions { PayloadPath = @"C:\FL\FrameLedger.Overlay.dll" }, static _ => { });
|
||||
Harness h = null!;
|
||||
var handler = new AgentCommandHandler(games, consent, guard, identity, orchestrator, pause, lifetime,
|
||||
_ => { h.RulesUpdates++; return ValueTask.FromResult("AlreadyCurrent"); });
|
||||
h = new Harness
|
||||
{
|
||||
Handler = handler,
|
||||
Games = games,
|
||||
Consent = consent,
|
||||
Guard = guard,
|
||||
Identity = identity,
|
||||
Orchestrator = orchestrator,
|
||||
Pause = pause,
|
||||
Lifetime = lifetime,
|
||||
};
|
||||
return h;
|
||||
}
|
||||
|
||||
private static async Task<IpcEnvelope> AskAsync<T>(AgentCommandHandler handler, string type, T payload)
|
||||
where T : class
|
||||
{
|
||||
byte[]? ack = await handler.HandleAsync(IpcCodec.Decode(IpcCodec.Encode(type, "1", payload)), Ct).ConfigureAwait(false);
|
||||
ack.Should().NotBeNull($"{type} is a command");
|
||||
return IpcCodec.Decode(ack!);
|
||||
}
|
||||
|
||||
private static async Task<IpcEnvelope> AskAsync(AgentCommandHandler handler, string type)
|
||||
{
|
||||
byte[]? ack = await handler.HandleAsync(IpcCodec.Decode(IpcCodec.Encode(type, "1")), Ct).ConfigureAwait(false);
|
||||
ack.Should().NotBeNull($"{type} is a command");
|
||||
return IpcCodec.Decode(ack!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARequestThatIsNotACommandIsNotAnswered()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
(await h.Handler.HandleAsync(IpcCodec.Decode(IpcCodec.Encode(IpcMessageType.Hello, "1")), Ct).ConfigureAwait(true)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetWatchlistEnsuresIdentityRowsWithHookingOffAndNamesWhatItCouldNotRead()
|
||||
{
|
||||
Harness h = await BuildAsync(consented: false).ConfigureAwait(true);
|
||||
h.Identity.Unreadable.Add(@"D:\GONE\MISSING.EXE");
|
||||
|
||||
IpcEnvelope ack = await AskAsync(h.Handler, IpcMessageType.SetWatchlist,
|
||||
new SetWatchlistRequest([new WatchlistEntry(null, @"c:\games\other\other.exe"), new WatchlistEntry(7, @"d:\gone\missing.exe")])).ConfigureAwait(true);
|
||||
|
||||
ack.Type.Should().Be(IpcMessageType.WatchlistAck);
|
||||
ack.Id.Should().Be("1");
|
||||
WatchlistAck payload = IpcCodec.Payload<WatchlistAck>(ack)!;
|
||||
payload.Games.Should().ContainSingle().Which.ExePath.Should().Be(@"C:\GAMES\OTHER\OTHER.EXE", "the Agent normalises; the client's spelling is never the key");
|
||||
payload.Games[0].Name.Should().Be("OTHER");
|
||||
payload.Unreadable.Should().Equal(@"d:\gone\missing.exe");
|
||||
h.Games.Rows[@"C:\GAMES\OTHER\OTHER.EXE"].HookEnabled.Should().BeFalse("identity only; hooking is never enabled by a watchlist");
|
||||
h.Games.Rows.Should().HaveCount(2, "the existing row stays; nothing is removed by this message");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetHookEnabledFalseRevokesThroughTheStore()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
long gameId = h.Games.Rows[_exe].Id;
|
||||
(await h.Consent.FindAsync(_exe, Ct).ConfigureAwait(true)).HookEnabled.Should().BeTrue();
|
||||
|
||||
IpcEnvelope ack = await AskAsync(h.Handler, IpcMessageType.SetHookEnabled, new SetHookEnabledRequest(gameId, Enabled: false, null)).ConfigureAwait(true);
|
||||
|
||||
ack.Type.Should().Be(IpcMessageType.HookEnabledAck);
|
||||
HookEnabledAck payload = IpcCodec.Payload<HookEnabledAck>(ack)!;
|
||||
payload.Enabled.Should().BeFalse();
|
||||
payload.Outcome.Should().Be(nameof(ConsentWriteOutcome.Written));
|
||||
(await h.Consent.FindAsync(_exe, Ct).ConfigureAwait(true)).HookEnabled.Should().BeFalse();
|
||||
h.Guard.Scanned.Should().BeEmpty("a revoke needs no scan");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetHookEnabledTrueRunsThePreScanAndABlockIsRecordedAndAnsweredRefused()
|
||||
{
|
||||
Harness h = await BuildAsync(consented: false).ConfigureAwait(true);
|
||||
long gameId = h.Games.Rows[_exe].Id;
|
||||
h.Guard.PreScan = AntiCheatVerdict.Refused(AntiCheatRefusalReason.BlockedModule, "eac", "EasyAntiCheat_EOS.dll");
|
||||
|
||||
IpcEnvelope ack = await AskAsync(h.Handler, IpcMessageType.SetHookEnabled, new SetHookEnabledRequest(gameId, Enabled: true, "whatever-the-client-says")).ConfigureAwait(true);
|
||||
|
||||
ack.Type.Should().Be(IpcMessageType.Refused);
|
||||
RefusedAck refused = IpcCodec.Payload<RefusedAck>(ack)!;
|
||||
refused.GameId.Should().Be(gameId);
|
||||
refused.Reason.Should().Be(nameof(AntiCheatRefusalReason.BlockedModule));
|
||||
refused.Family.Should().Be("eac");
|
||||
refused.Signal.Should().Be("EasyAntiCheat_EOS.dll");
|
||||
h.Guard.Scanned.Should().ContainSingle().Which.Should().Be(@"C:\Games\Title");
|
||||
GameConsentRecord record = await h.Consent.FindAsync(_exe, Ct).ConfigureAwait(true);
|
||||
record.HookEnabled.Should().BeFalse();
|
||||
record.BlockedReason.Should().NotBeNullOrEmpty("the block is on the row for FR-2.2's disabled toggle");
|
||||
record.ConsentedAt.Should().BeNull("nothing was stamped");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetHookEnabledTrueWithACleanScanStampsNothingWhileTheDisclosureDoesNotExist()
|
||||
{
|
||||
Harness h = await BuildAsync(consented: false).ConfigureAwait(true);
|
||||
long gameId = h.Games.Rows[_exe].Id;
|
||||
|
||||
IpcEnvelope ack = await AskAsync(h.Handler, IpcMessageType.SetHookEnabled, new SetHookEnabledRequest(gameId, Enabled: true, "client-claims-a-version")).ConfigureAwait(true);
|
||||
|
||||
ack.Type.Should().Be(IpcMessageType.Error);
|
||||
ErrorAck error = IpcCodec.Payload<ErrorAck>(ack)!;
|
||||
error.Code.Should().Be(IpcErrorCode.DisclosureUnavailable);
|
||||
error.Message.Should().Contain("PR-4").And.Contain("consent grant");
|
||||
h.Guard.Scanned.Should().ContainSingle("the pre-scan ran first");
|
||||
GameConsentRecord record = await h.Consent.FindAsync(_exe, Ct).ConfigureAwait(true);
|
||||
record.HookEnabled.Should().BeFalse();
|
||||
record.ConsentedAt.Should().BeNull("a client's version string is not a disclosure shown; nothing is stamped");
|
||||
record.Provenance.Should().Be(ConsentProvenance.NotRecorded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetHookEnabledForAnUnknownGameOrAnUnreadableExecutableIsAnError()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
IpcEnvelope unknown = await AskAsync(h.Handler, IpcMessageType.SetHookEnabled, new SetHookEnabledRequest(999, Enabled: true, null)).ConfigureAwait(true);
|
||||
IpcCodec.Payload<ErrorAck>(unknown)!.Code.Should().Be(IpcErrorCode.UnknownGame);
|
||||
|
||||
h.Identity.Unreadable.Add(_exe);
|
||||
IpcEnvelope unreadable = await AskAsync(h.Handler, IpcMessageType.SetHookEnabled, new SetHookEnabledRequest(h.Games.Rows[_exe].Id, Enabled: true, null)).ConfigureAwait(true);
|
||||
IpcCodec.Payload<ErrorAck>(unreadable)!.Code.Should().Be(IpcErrorCode.ExecutableUnreadable);
|
||||
h.Guard.Scanned.Should().BeEmpty("nothing is scanned for a file that cannot be read");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PauseAndResumeFlipTheOneGlobalFlagTheStatusReports()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
h.Handler.IsPaused.Should().BeFalse();
|
||||
|
||||
IpcEnvelope paused = await AskAsync(h.Handler, IpcMessageType.PauseCapture).ConfigureAwait(true);
|
||||
paused.Type.Should().Be(IpcMessageType.PauseAck);
|
||||
IpcCodec.Payload<PauseAck>(paused)!.Paused.Should().BeTrue();
|
||||
h.Pause.IsPaused.Should().BeTrue();
|
||||
h.Handler.IsPaused.Should().BeTrue();
|
||||
|
||||
IpcEnvelope resumed = await AskAsync(h.Handler, IpcMessageType.ResumeCapture).ConfigureAwait(true);
|
||||
IpcCodec.Payload<PauseAck>(resumed)!.Paused.Should().BeFalse();
|
||||
h.Pause.IsPaused.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopSessionForAGuidNobodyRunsIsNotAccepted()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
var guid = Guid.NewGuid();
|
||||
|
||||
IpcEnvelope ack = await AskAsync(h.Handler, IpcMessageType.StopSession, new StopSessionRequest(guid)).ConfigureAwait(true);
|
||||
|
||||
ack.Type.Should().Be(IpcMessageType.StopAck);
|
||||
StopAck payload = IpcCodec.Payload<StopAck>(ack)!;
|
||||
payload.SessionGuid.Should().Be(guid);
|
||||
payload.Accepted.Should().BeFalse();
|
||||
payload.Reason.Should().NotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LaunchGameIsTheOrchestratorsAnswer()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
|
||||
IpcEnvelope ack = await AskAsync(h.Handler, IpcMessageType.LaunchGame, new LaunchGameRequest(h.Games.Rows[_exe].Id, null)).ConfigureAwait(true);
|
||||
|
||||
ack.Type.Should().Be(IpcMessageType.LaunchAck);
|
||||
LaunchAck payload = IpcCodec.Payload<LaunchAck>(ack)!;
|
||||
payload.Accepted.Should().BeFalse("this orchestrator was composed without launch mode");
|
||||
payload.Outcome.Should().Be(nameof(LaunchOutcome.Unavailable));
|
||||
payload.SessionGuid.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRulesIsATriggerWithNoSourceAndShutdownAsksTheLifetime()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
|
||||
IpcEnvelope rules = await AskAsync(h.Handler, IpcMessageType.UpdateRules).ConfigureAwait(true);
|
||||
rules.Type.Should().Be(IpcMessageType.UpdateRulesAck);
|
||||
IpcCodec.Payload<UpdateRulesAck>(rules)!.Outcome.Should().Be("AlreadyCurrent");
|
||||
h.RulesUpdates.Should().Be(1);
|
||||
|
||||
// A payload naming a path is ignored: the rules SOURCE is not a parameter (07_IPC §The pipe is not a trust boundary).
|
||||
byte[] withPath = IpcCodec.Encode(new IpcEnvelope { Type = IpcMessageType.UpdateRules, Id = "2", Payload = System.Text.Json.JsonDocument.Parse("{\"path\":\"C:\\\\evil\\\\rules.json\"}").RootElement });
|
||||
(await h.Handler.HandleAsync(IpcCodec.Decode(withPath), Ct).ConfigureAwait(true)).Should().NotBeNull();
|
||||
h.RulesUpdates.Should().Be(2, "answered as the same bare trigger");
|
||||
|
||||
IpcEnvelope shutdown = await AskAsync(h.Handler, IpcMessageType.Shutdown).ConfigureAwait(true);
|
||||
shutdown.Type.Should().Be(IpcMessageType.ShutdownAck);
|
||||
h.Lifetime.Requests.Should().Be(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ACommandWithoutItsPayloadIsMalformedNotAGuess()
|
||||
{
|
||||
Harness h = await BuildAsync().ConfigureAwait(true);
|
||||
foreach (string type in new[] { IpcMessageType.SetWatchlist, IpcMessageType.LaunchGame, IpcMessageType.SetHookEnabled, IpcMessageType.StopSession })
|
||||
{
|
||||
IpcEnvelope ack = await AskAsync(h.Handler, type).ConfigureAwait(true);
|
||||
ack.Type.Should().Be(IpcMessageType.Error, type);
|
||||
IpcCodec.Payload<ErrorAck>(ack)!.Code.Should().Be(IpcErrorCode.Malformed, type);
|
||||
}
|
||||
|
||||
Encoding.UTF8.GetString(IpcCodec.Encode(IpcMessageType.Ping, "9")).Should().NotContain("payload");
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ public sealed class RecordedSessionEventsTests
|
||||
[InlineData(SessionEndReason.RefusedHookNotEnabled, RecordedSessionEvents.Kind.None)]
|
||||
[InlineData(SessionEndReason.RefusedConsentMissing, RecordedSessionEvents.Kind.None)]
|
||||
[InlineData(SessionEndReason.Running, RecordedSessionEvents.Kind.None)]
|
||||
[InlineData(SessionEndReason.StoppedByUser, RecordedSessionEvents.Kind.None)]
|
||||
public void EveryReasonHasOneKind(SessionEndReason reason, RecordedSessionEvents.Kind expected) =>
|
||||
RecordedSessionEvents.Classify(reason).Should().Be(expected);
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ public sealed class ExitStatusMapperTests
|
||||
[InlineData(SessionEndReason.WriterStoppedBlocklisted, null, false, ExitStatus.Degraded)]
|
||||
[InlineData(SessionEndReason.WriterNeverInstalledHooks, null, false, ExitStatus.Degraded)]
|
||||
[InlineData(SessionEndReason.RefusedByGuard, null, false, ExitStatus.Normal)]
|
||||
[InlineData(SessionEndReason.StoppedByUser, null, false, ExitStatus.Normal)]
|
||||
[InlineData(SessionEndReason.KillSwitchEngaged, null, false, ExitStatus.Normal)]
|
||||
public void MapsTheReasonTheExitCodeAndTheWitness(SessionEndReason reason, int? exitCode, bool witness, ExitStatus expected)
|
||||
{
|
||||
ExitStatusMapper.Map(reason, exitCode, witness).Should().Be(expected);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Recording;
|
||||
using FrameLedger.Application.Tests.Recording;
|
||||
using FrameLedger.Application.Watch;
|
||||
@@ -38,6 +39,8 @@ public sealed class CaptureOrchestratorTests
|
||||
private sealed class FakeIdentity : IExecutableIdentitySource
|
||||
{
|
||||
public ExecutableFingerprint? Read(string normalisedExePath) => new() { ExePath = normalisedExePath, SizeBytes = 5, MtimeUnixMs = 5 };
|
||||
|
||||
public string Normalise(string exePath) => exePath;
|
||||
}
|
||||
|
||||
private const string _game = @"C:\Games\Title\game.exe";
|
||||
@@ -121,6 +124,91 @@ public sealed class CaptureOrchestratorTests
|
||||
o.RunningSessions.Should().Be(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopSessionCancelsTheRequestsOwnStopTokenAndNothingElse()
|
||||
{
|
||||
(CaptureOrchestrator o, FakeRecorder recorder, FakeSnapshots processes, List<string> log) = await BuildAsync().ConfigureAwait(true);
|
||||
CancellationToken ct = TestContext.Current.CancellationToken;
|
||||
processes.Processes.Add(new ProcessSnapshot(4242, 1, "game.exe", _game, DateTimeOffset.UnixEpoch));
|
||||
await o.PollOnceAsync(ct).ConfigureAwait(true);
|
||||
await WaitForRequestsAsync(recorder, 1).ConfigureAwait(true);
|
||||
RecordRequest request = recorder.Requests.Single();
|
||||
request.SessionGuid.Should().NotBeNull("the orchestrator names the session so a stop can address it");
|
||||
request.StopToken.IsCancellationRequested.Should().BeFalse();
|
||||
|
||||
o.StopSession(Guid.NewGuid()).Should().BeFalse("no session carries a guid nobody started");
|
||||
o.StopSession(request.SessionGuid!.Value).Should().BeTrue();
|
||||
|
||||
request.StopToken.IsCancellationRequested.Should().BeTrue("the stop is the session's own token");
|
||||
ct.IsCancellationRequested.Should().BeFalse("the host's token is untouched");
|
||||
log.Should().Contain(l => l.Contains("stop requested", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private sealed class FakeLaunches(FakeRecorder recorder) : ILaunchRecorderFactory, IDisposable
|
||||
{
|
||||
private Launch? _current;
|
||||
|
||||
public void Dispose() => _current?.Dispose();
|
||||
|
||||
public int Prepared { get; private set; }
|
||||
|
||||
public int Disposed { get; private set; }
|
||||
|
||||
public ValueTask<ILaunchRecording> PrepareAsync(string normalisedExePath, CancellationToken ct = default)
|
||||
{
|
||||
Prepared++;
|
||||
_current = new Launch(recorder, this);
|
||||
return ValueTask.FromResult<ILaunchRecording>(_current);
|
||||
}
|
||||
|
||||
private sealed class Launch(FakeRecorder recorder, FakeLaunches owner) : ILaunchRecording
|
||||
{
|
||||
public ISessionRecorder Recorder => recorder;
|
||||
|
||||
public string Description => "vulkan layer: test";
|
||||
|
||||
public void Dispose() => owner.Disposed++;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LaunchStartsALaunchModeSessionOncePerGameAndRefusesWhatItCannotName()
|
||||
{
|
||||
var games = new FakeGameRepository();
|
||||
GameRow game = await games.EnsureAsync(new ExecutableFingerprint { ExePath = _game, SizeBytes = 1, MtimeUnixMs = 1 }, "Title", TestContext.Current.CancellationToken).ConfigureAwait(true);
|
||||
var attach = new FakeRecorder();
|
||||
var launchRecorder = new FakeRecorder();
|
||||
using var launches = new FakeLaunches(launchRecorder);
|
||||
List<string> log = [];
|
||||
var o = new CaptureOrchestrator(attach, games, new FakeSnapshots(), new FakeIdentity(),
|
||||
new OrchestratorOptions { PayloadPath = @"C:\FL\FrameLedger.Overlay.dll" }, log.Add, launches);
|
||||
CancellationToken ct = TestContext.Current.CancellationToken;
|
||||
|
||||
(await o.LaunchAsync(999, "", ct).ConfigureAwait(true)).Outcome.Should().Be(LaunchOutcome.UnknownGame);
|
||||
|
||||
LaunchResult first = await o.LaunchAsync(game.Id, "-benchmark", ct).ConfigureAwait(true);
|
||||
first.Outcome.Should().Be(LaunchOutcome.Accepted);
|
||||
first.SessionGuid.Should().NotBeNull();
|
||||
await WaitForRequestsAsync(launchRecorder, 1).ConfigureAwait(true);
|
||||
RecordRequest request = launchRecorder.Requests.Single();
|
||||
request.Mode.Should().Be(CaptureMode.Launch);
|
||||
request.Arguments.Should().Be("-benchmark");
|
||||
request.SessionGuid.Should().Be(first.SessionGuid);
|
||||
request.GameName.Should().Be("Title");
|
||||
attach.Requests.Should().BeEmpty("launch mode uses the launch recorder, not the watcher's");
|
||||
|
||||
(await o.LaunchAsync(game.Id, "", ct).ConfigureAwait(true)).Outcome.Should().Be(LaunchOutcome.SessionRunning, "one session per game at a time");
|
||||
o.StopSession(first.SessionGuid!.Value).Should().BeTrue("a launched session is addressable like a watched one");
|
||||
|
||||
launchRecorder.Pending[0].SetException(new OperationCanceledException());
|
||||
await WaitUntilAsync(() => launches.Disposed == 1).ConfigureAwait(true);
|
||||
launches.Disposed.Should().Be(1, "the launch environment is released with the session");
|
||||
|
||||
var noLaunch = new CaptureOrchestrator(attach, games, new FakeSnapshots(), new FakeIdentity(),
|
||||
new OrchestratorOptions { PayloadPath = @"C:\FL\FrameLedger.Overlay.dll" }, log.Add);
|
||||
(await noLaunch.LaunchAsync(game.Id, "", ct).ConfigureAwait(true)).Outcome.Should().Be(LaunchOutcome.Unavailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunAsyncPollsUntilCancelledAndThenReportsWhatWasRunning()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user