Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.1 5f3dbcca81 feat(detection): the rules engine wired into the Agent -- DetectionSweep under --serve, ApplyDetectionAsync under the provenance rule, schema 0004, the Supports row (P4 PR-1)
The engine, schema, validator and fixture corpus existed since P0 with
no production caller and no writer. DetectionSweep runs
StaticGameDetector over the real GameFileProbe for every library game
whose DetectionCacheKey is stale and persists through the new
IGameRepository.ApplyDetectionAsync; DetectionHostedService hosts it
under --serve on its own task (the probe blocks on file I/O), every
15 s and at once when UpdateRules re-seeds the rules file.

Schema 0004 gives the key's exe half its own columns: exe_size_bytes /
exe_mtime_ms are the consent fingerprint the gate reads and a background
scan must never refresh them. The repository applies 05_DETECTION
§Caching's provenance rule per field -- a user field is never touched,
a detected one is refreshed, an empty field with no entry is filled and
badged (without that a fresh game could never receive an engine), a
null detected value erases nothing -- and writes capability_flags whole
as the rule ids.

App: Tools > Update detection rules is a real command; the Supports row
shows what the sweep wrote. Tests across Application, Infrastructure and
App. Docs: 05_DETECTION, 06_DATA_MODEL, 04_CAPTURE, 08_UI, HANDOFF,
15_ROADMAP, CHANGELOG.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 19:21:26 +07:00
29 changed files with 865 additions and 20 deletions

No files matched your search

+25
View File
@@ -17,6 +17,31 @@ GitHub release body, so a missing section will mean an empty release note.
## [Unreleased]
### Added
- **P4 PR-1 — the detection rules engine wired into the Agent, and the Supports row (2026-09-14).** The engine,
schema, validator and fixture corpus existed since P0 with no production caller and no writer. Now:
`Application.Detection.DetectionSweep` runs `StaticGameDetector` over the real `GameFileProbe` for every game in
the library whose `DetectionCacheKey` is stale — never scanned, the exe changed, the rules moved on — and
persists through the new `IGameRepository.ApplyDetectionAsync`; `Agent.Hosting.DetectionHostedService` hosts it
under `--serve` on its own task (the probe blocks on file I/O; the 1 Hz poll never waits on it), every 15 s and
at once when `UpdateRules` re-seeds the rules file. **Schema 0004** `games.detection_exe_size_bytes` /
`detection_exe_mtime_ms`: the key's exe half apart from `exe_size_bytes` / `exe_mtime_ms`, which are the consent
fingerprint the gate reads and which a background scan must never refresh. The repository applies
`05_DETECTION` §Caching's provenance rule per field — a `user` field is never touched, a `detected` one is
refreshed, an empty field with no entry is filled and badged (without that clause a fresh game could never
receive an engine), a null detected value erases nothing — and writes `capability_flags` whole as a JSON array of
the rule ids (`dlss`, `dlss_g`, `dlss_rr`, `streamline`, `fsr`, `xess`, `xefg`; the App's `CapabilityNames` reads
both spellings). App: Tools ▸ Update detection rules is a real command (`UpdateRules` over the pipe, the seeder's
outcome in a snackbar); the game page's Supports row shows what the sweep wrote and says "not scanned yet" only
until the Agent's next tick. Tests: `DetectionSweepTests` (5: scanned once then current, exe change and rules
change re-scan, unreadable exe and unusable rules, the wake, the key field by field),
`SqliteGameRepositoryTests` (the provenance rule end to end, the consent fingerprint untouched),
`LedgerDatabaseTests` (0004), `GameDetailViewModelTests` (the Supports row from a detection write, the rule
ids). 4 App strings en/vi/ja + the Supports empty-state reworded. Docs: `05_DETECTION` §Caching built note,
`06_DATA_MODEL` §Writer ownership / §games / §Migrations, `04_CAPTURE` §Threading model, `08_UI` §Games,
HANDOFF §P4 and `15_ROADMAP` §P4 struck.
### Fixed
- **A DXGI present counter that went backwards read as four billion unseen presents (2026-09-14).** The Present
+5 -1
View File
@@ -120,7 +120,11 @@ which makes the notification more important than it was, not less.
> at a time through `ISessionRecorder`, attach mode only; it decides nothing about hooking, the recorder's loop
> reaches the gate exactly as a console verb does. `WatcherHostedService` runs `PartialRecovery` first, every
> start, then the orchestrator. There is no `Channel` and no second consumer: `PollOnceAsync` is the only writer
> of the running-session table, and the sessions run on their own tasks.
> of the running-session table, and the sessions run on their own tasks. **Since P4 PR-1 (2026-09-14) a second
> hosted service runs beside it under `--serve`: `DetectionHostedService`, the static detection sweep
> (`05_DETECTION` §Caching) on its own task, because `GameFileProbe` blocks on file I/O and the 1 Hz poll must
> not wait on it. It reads game files and writes the detected columns of `games`; it never touches a process,
> a hook, or a consent column.**
## Launch mode vs attach mode
+16
View File
@@ -190,6 +190,22 @@ Three things this section previously implied that are not true, and are worth st
- Detection results cached per game; refreshed when exe timestamp/size changes or `rulesVersion` changes. Implemented as `DetectionCacheKey` (path + size + mtime + `rulesVersion`).
- **A re-run never overwrites a field the user supplied.** `games.field_provenance` records where each value came from; anything not marked `detected` is left alone, and an absent or unrecognised provenance reads as *user*. Without this rule the re-run triggered by every rules update silently clobbers every correction the user has ever made — a data-loss bug that surfaces weeks later on somebody else's machine. Stated here because no document said it before, and the safe default is the one that costs a badge rather than a value.
> **Built 2026-09-14 (P4 PR-1), and two things this section did not say.** *When it runs:* the Agent's
> `DetectionHostedService` (`--serve` only) sweeps the library on its own task — every 15 s, and at once
> when `UpdateRules` re-seeds the rules file — through `Application.Detection.DetectionSweep`, which runs
> `StaticGameDetector` over the real `GameFileProbe` for every game whose key is stale and persists through
> `IGameRepository.ApplyDetectionAsync`. A game the App adds is scanned on the next tick (the App writes the
> row, the Agent reads the table); no Agent running means no scan, and the game page says "not scanned yet".
> *The key's exe half is NOT `exe_size_bytes` / `exe_mtime_ms`:* those are the consent fingerprint the gate
> reads (`SqliteGameConsentStore` refuses a mismatch while a block stands), so schema 0004 gave the key its own
> `detection_exe_size_bytes` / `detection_exe_mtime_ms` beside `detection_rules_version`. *And the provenance
> rule, applied per field in the repository:* a `user` entry, an unrecognised entry, or a value with no entry is
> the user's and stays; a `detected` entry is refreshed; **an empty field with no entry has nothing to protect
> and is filled and badged `detected`** — without that clause a freshly added game could never receive an
> engine at all, since `EnsureAsync` writes no provenance. A null detected value erases nothing.
> `capability_flags` is written whole every run (a JSON array of the rule ids — `dlss`, `dlss_g`, `dlss_rr`,
> `streamline`, `fsr`, `xess`, `xefg`) because the Supports row has no user-edit surface and a stale "Supports
> DLSS-G" after the DLL left is the confusion §Capability hints exists to prevent.
- Strings scans bounded to 8 MB, local only.
- Module enumeration uses read-only handles (`PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ`); never a handle with write access outside the injection call itself.
- No game memory is read for detection purposes — all runtime facts come from arguments to APIs we hooked (CLAUDE.md rule 4).
+10 -2
View File
@@ -2,7 +2,7 @@
`%LOCALAPPDATA%\FrameLedger\ledger.db`. Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, `busy_timeout=5000`. `Microsoft.Data.Sqlite` + Dapper; all writes in explicit transactions.
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, and the hook-state columns on `games`. UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; never a `hook_*` column), `session_annotations` (tags, notes, and since schema 0002 the FR-8.3 overrides — which is WHY they are on this table and not on `sessions`), `settings`, `legal_acceptance`. Both read everything. The ports say the same in their names: `IGameRepository.UpdateMetadataAsync` / `SetTriStateDefaultAsync` / `RemoveAsync`, `ISessionAnnotationRepository`, `RegisteredSettings`, `ILegalAcceptanceStore.RecordAsync` (all P3 PR-3).
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms` — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; never a `hook_*` column), `session_annotations` (tags, notes, and since schema 0002 the FR-8.3 overrides — which is WHY they are on this table and not on `sessions`), `settings`, `legal_acceptance`. Both read everything. The ports say the same in their names: `IGameRepository.UpdateMetadataAsync` / `SetTriStateDefaultAsync` / `RemoveAsync`, `ISessionAnnotationRepository`, `RegisteredSettings`, `ILegalAcceptanceStore.RecordAsync` (all P3 PR-3).
## Schema (v2 — hook architecture)
@@ -56,7 +56,10 @@ CREATE TABLE games (
hook_blocked_reason TEXT, -- set by the static AC pre-scan; non-null = toggle disabled in UI
hook_autodisabled_reason TEXT, -- set after repeated crashes
hook_crash_count INTEGER NOT NULL DEFAULT 0,
capability_flags TEXT, -- JSON: what the game SHIPS (dlss/dlssg/dlssd/fsr/xess) — never a measurement
capability_flags TEXT, -- JSON: what the game SHIPS — never a measurement. Since P4 PR-1 (2026-09-14) a JSON
-- array of the rule ids of rules/detection-rules.json (dlss, dlss_g, dlss_rr, streamline,
-- fsr, xess, xefg), written whole by the Agent's detection sweep; this line used to spell
-- the App's tokens (dlssg/dlssd), which the App still reads for older rows
-- tri-state defaults inherited by new sessions
rt_default TEXT NOT NULL DEFAULT 'na',
@@ -401,6 +404,11 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
> `ALTER TABLE ADD COLUMN`, written by the Agent (`SessionAggregator.ApplyFg`), read by the UI for the "factor not
> counted" tooltip (`08_UI` §FPS display rule). `LatestVersion` is 3; `LedgerDatabaseTests` asserts the column.
> **`0004_detection_cache.sql` (P4 PR-1, 2026-09-14) — `games.detection_exe_size_bytes` / `detection_exe_mtime_ms`.**
> The detection cache key's exe half (`05_DETECTION` §Caching), apart from `exe_size_bytes` / `exe_mtime_ms`,
> which are the consent fingerprint the gate reads and which a background scan must never refresh.
> `LatestVersion` is 4; `LedgerDatabaseTests` asserts the columns.
> **Built 2026-09-09 (P2 PR-B):** `Infrastructure.Persistence.MigrationRunner` over scripts embedded in
> the assembly (so the schema a build applies is the one it was tested against), one transaction per
> script, under `Local\FrameLedger.Ledger.Migrate` — session-local rather than `Global\`, because the
+1 -1
View File
@@ -139,7 +139,7 @@ All screens are `Page`s registered with the navigation page provider and navigat
> FIRST when it was on. Detail: header (name, publisher · version · store · engine, last session's date and
> API, the last hooked session's `FpsReadout`, the three chips resolved with the annotation and the game
> default — `Application.TriState.TriStateResolution`), Edit… (FR-1.3, a `ContentDialog` badging detected
> fields), **Supports** (from `capability_flags`; empty until P4's scan writes it, and the card says so) beside
> fields), **Supports** (from `capability_flags`; ~~empty until P4's scan writes it, and the card says so~~ **written by the Agent's detection sweep since P4 PR-1, 2026-09-14** — the rule ids as product names via `CapabilityNames`, "not scanned yet" only until the Agent's next tick) beside
> **Last session measured** (upscaler · resolution, frame generation, the non-N/A chips — accent pills, from the
> hooks). Hooking: the toggle is `OneWay` from the row and its command runs `HookingConsent`; a refusal, a
> mismatch or a failure is a persistent `InfoBar` on the page (never a toast); a blocked row disables the
+1 -1
View File
@@ -317,7 +317,7 @@ Agent: watcher, tier selection, injection orchestration, shm drain, telemetry po
WPF UI shell (`16_WPFUI_SYNTAX`), library, per-game hooking consent flow, Dashboard live card showing *measured* settings, session summary, ScottPlot charts, game detail tabs, Compare with tier guarding, segment ribbon, tri-state chips with override, refusal/degradation/unhook notices as first-class UI. **Plus, moved here from P4 on 2026-09-13 (owner):** the command pipe (`07_IPC` §C — P2's decision D10 put it here), i18n en/vi/ja with `tools/resx-audit` (the consent dialog is the first thing that needs a reviewed `.resx`, so it cannot wait), the Legal Gate (FR-11), Settings (FR-10, the kill switch first), the Logs page, tray + toasts. The owner chose the whole of `08_UI` over a shell-first cut; HANDOFF §P3 carries the slice order and the decisions (D11–D17). *Not started as of 2026-09-13: `FrameLedger.App` is the scaffold, `FrameLedger.Shared` has no IPC type, and no `.resx` exists in the tree.*
## P4 — Detection & product polish (1 week)
Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures; store auto-import; capability-vs-measured UI separation; ~~i18n en/vi/ja; Legal Gate;~~ Velopack + updater (with the hooked-session deferral); bug bundle incl. overlay logs; ~~tray + toasts; Settings;~~ DB maintenance; accessibility pass; the scheduled task (`--install-task`) and the Velopack install hooks. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
~~Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures~~ **landed 2026-09-14 (P4 PR-1: the engine existed since P0; the Agent's `DetectionSweep` is its first caller, `ApplyDetectionAsync` its first writer — HANDOFF §P4)**; store auto-import; ~~capability-vs-measured UI separation~~ **(PR-1: the Supports row reads the sweep's flags)**; ~~i18n en/vi/ja; Legal Gate;~~ Velopack + updater (with the hooked-session deferral); bug bundle incl. overlay logs; ~~tray + toasts; Settings;~~ DB maintenance; accessibility pass; the scheduled task (`--install-task`) and the Velopack install hooks. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
## P5 — Ship (3–4 days)
CI/CD with the native build; CodeQL (C# + C++); Dependabot; CHANGELOG; README with the P0 accuracy comparison — **which is not a percentage, and this line used to send its author looking for one**. The decision is recorded under item 3 and in `spike-notes.md` §8: the baseline can answer **none** of item 4's four runtime questions, so the defensible claim is *"the baseline cannot answer four of these five questions at all"*, not *"N% more accurate"*. Overhead + tier cross-validation measurements; release smoke on clean VMs; `v0.1.0-beta.1`.
+8 -4
View File
@@ -1220,10 +1220,14 @@ P3's slices are all struck below. What is left of P3 is not code: the owner merg
The owner-only measurements of §P2 (`spike-notes` §14) are still open and still owner-only.
**P4 is `15_ROADMAP` §P4**, in this order, each a PR that fails on unpatched `main` for a stated reason:
detection rules engine + `detection-rules.json` validator and fixtures (the anticheat blocklist is already
consumed by the guard; the engine/platform/capability halves are not), store auto-import (Steam / GOG / Epic /
itch.io — the first-run flow's step 4 and File ▸ Import library both say "later build"), the
capability-vs-measured separation in the UI (the game page's Supports row is empty until this), Velopack +
~~detection rules engine + `detection-rules.json` validator and fixtures (the anticheat blocklist is already
consumed by the guard; the engine/platform/capability halves are not)~~ **LANDED 2026-09-14 (P4 PR-1)** — the
engine, validator and corpus already existed; what was missing was a caller and a writer: `DetectionSweep` +
`DetectionHostedService` under `--serve`, `IGameRepository.ApplyDetectionAsync` under the provenance rule,
schema 0004 for the key's exe half (NOT the consent fingerprint), Tools ▸ Update rules wired, the Supports row
filled — status in `CHANGELOG.md`, the decisions in `05_DETECTION` §Caching's built note; store auto-import (Steam / GOG / Epic /
itch.io — the first-run flow's step 4 and File ▸ Import library both say "later build"), ~~the
capability-vs-measured separation in the UI (the game page's Supports row is empty until this)~~ **(PR-1)**, Velopack +
the updater (`11_UPDATER`; the Settings channel row is stored and unused), the bug-report flow's steps 3–5
(`10_LOGGING`: the preview dialog, the GitHub issue link — step 2's bundle exists), the "is Vulkan" fact the
layer's register/unregister-on-consent automation needs (`17_HOOK_ENGINE` §Vulkan built note), the Help menu's
@@ -2,6 +2,7 @@ using FrameLedger.Agent.Hosting;
using FrameLedger.Application.AntiCheat;
using FrameLedger.Application.Capture;
using FrameLedger.Application.Consent;
using FrameLedger.Application.Detection;
using FrameLedger.Application.Ipc;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
@@ -11,6 +12,7 @@ using FrameLedger.Application.Watch;
using FrameLedger.Infrastructure.AntiCheat;
using FrameLedger.Infrastructure.Blobs;
using FrameLedger.Infrastructure.Capture;
using FrameLedger.Infrastructure.Detection;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Infrastructure.Recording;
@@ -91,6 +93,8 @@ internal static class AgentServices
// The watcher (this PR): snapshots, identity, and the orchestrator over an unbounded recorder.
services.AddSingleton<IProcessSnapshotSource, ToolhelpProcessSnapshotSource>();
services.AddSingleton<IExecutableIdentitySource, ExecutableIdentitySource>();
AddDetection(services);
services.AddSingleton<ISessionRecorder>(static sp => sp.GetRequiredService<AgentRecording>().Recorder(seconds: 0, launcher: null));
AddPipe(services, pipeName);
@@ -98,6 +102,22 @@ internal static class AgentServices
return services;
}
/// <summary>The static detection sweep (P4 PR-1, <c>05_DETECTION</c> §Caching): hosted under <c>--serve</c> only, composed and inert under <c>--console</c>.</summary>
private static void AddDetection(IServiceCollection services)
{
// The static detection sweep (P4 PR-1, 05_DETECTION §Caching): the rules file RulesSeeder seeds (the two
// paths agree, RulesPathAgreementTests), the real probe, and the sweep over the games table. Hosted under
// --serve only (DetectionHostedService); composed and inert under --console.
services.AddSingleton<IDetectionRulesSource>(static _ => new DetectionRulesFile());
services.AddSingleton<IGameFileProbe, GameFileProbe>();
services.AddSingleton(static sp => new DetectionSweep(
sp.GetRequiredService<IGameRepository>(),
sp.GetRequiredService<IDetectionRulesSource>(),
sp.GetRequiredService<IGameFileProbe>(),
sp.GetRequiredService<IExecutableIdentitySource>(),
static line => Serilog.Log.Information("{Line}", line)));
}
/// <summary>
/// The pipe, read half (P3 PR-1, <c>07_IPC</c> §C, HANDOFF §P3 D11–D13). Events leave through <c>SessionEventPublisher</c>,
/// the recorder's observer; requests are answered by <c>AgentRequestHandler</c>; the server itself is started by
@@ -120,7 +140,14 @@ internal static class AgentServices
sp.GetRequiredService<CaptureOrchestrator>(),
sp.GetRequiredService<CapturePause>(),
sp.GetRequiredService<IAgentLifetime>(),
static async ct => (await new RulesSeeder(new FileSystemRulesStore()).EnsureSeededAsync(ct).ConfigureAwait(false)).ToString(),
// UpdateRules: re-seed the rules file, then wake the detection sweep (P4 PR-1) — a rules change is the
// re-run trigger 05_DETECTION §Caching names, so the games table follows within the same second.
async ct =>
{
RulesSeedOutcome outcome = await new RulesSeeder(new FileSystemRulesStore()).EnsureSeededAsync(ct).ConfigureAwait(false);
sp.GetRequiredService<DetectionSweep>().RequestNow();
return outcome.ToString();
},
// P3 PR-4 (D14): the reviewed disclosure this Agent stamps against, and its own clock for the stamp.
SafetyDisclosure.Version,
TimeProvider.System));
@@ -0,0 +1,59 @@
using FrameLedger.Application.Detection;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace FrameLedger.Agent.Hosting;
/// <summary>
/// <c>--serve</c> (P4 PR-1): the static detection sweep on its own background task. One pass at start, then one
/// every <see cref="Interval"/>, and one as soon as <c>UpdateRules</c> re-seeds the rules file
/// (<see cref="DetectionSweep.RequestNow"/>). It reads game files and writes the detected columns of <c>games</c>;
/// it never touches a process, a hook, or a consent column (<c>05_DETECTION</c> §Caching, CLAUDE.md rule 4).
/// </summary>
/// <remarks>
/// Its own task because <c>GameFileProbe</c> blocks on file I/O (a bounded directory walk, an 8 MB strings pass):
/// the orchestrator's 1 Hz poll must not wait on it, and a session's drain must never share a thread with it.
/// A sweep that throws is logged and retried on the next tick rather than ending the service — a game's
/// directory going away mid-walk is ordinary, and one bad game must not stop the scan of the rest.
/// </remarks>
internal sealed class DetectionHostedService(DetectionSweep sweep) : BackgroundService
{
/// <summary>The idle cadence. A game the App just added is seen within this; a rules update wakes the loop at once.</summary>
public static readonly TimeSpan Interval = TimeSpan.FromSeconds(15);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Log.Information("detect: sweeping the library every {Seconds} s, and on every rules update", Interval.TotalSeconds);
while (!stoppingToken.IsCancellationRequested)
{
try
{
DetectionSweepReport r = await sweep.SweepOnceAsync(stoppingToken).ConfigureAwait(false);
if (r.Scanned > 0 || r.Unreadable > 0 || r.RulesUnusable)
{
Log.Information("detect: sweep scanned {Scanned}, current {Current}, unreadable {Unreadable}{Rules}",
r.Scanned, r.Current, r.Unreadable, r.RulesUnusable ? ", rules unusable" : string.Empty);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
{
Log.Warning(ex, "detect: sweep did not complete; retrying on the next tick");
}
try
{
await sweep.WaitAsync(Interval, stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
}
Log.Information("detect: stopped");
}
}
+2
View File
@@ -97,6 +97,8 @@ internal static class Program
builder.Services.AddSingleton<IAgentLifetime, HostAgentLifetime>();
builder.Services.AddFrameLedgerAgent(db, paths);
builder.Services.AddHostedService<WatcherHostedService>();
// The static detection sweep (P4 PR-1, 05_DETECTION §Caching): its own task, because the probe blocks on file I/O.
builder.Services.AddHostedService<DetectionHostedService>();
// The pipe (07_IPC §C), the product's UI channel: --serve only, never under --console (P3 PR-1).
builder.Services.AddHostedService<PipeServerHostedService>();
// Finalize's grace on shutdown (04_CAPTURE §Threading model): a session that does not make it leaves
+1 -1
View File
@@ -44,7 +44,7 @@
</MenuItem>
<MenuItem Header="{x:Static res:Strings.Menu_Tools}">
<MenuItem Header="{x:Static res:Strings.Menu_Tools_AgentStatus}" Command="{Binding ViewModel.AgentStatusCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_UpdateRules}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_UpdateRules}" Command="{Binding ViewModel.UpdateRulesCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_VulkanLayer}" Command="{Binding ViewModel.VulkanLayerCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_OpenDataFolder}" Command="{Binding ViewModel.OpenDataFolderCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_Tools_DbMaintenance}" Command="{Binding ViewModel.NotYetCommand}" />
+12
View File
@@ -309,6 +309,10 @@ public static class Strings
nameof(RemoveGame_Keep),
nameof(RemoveGame_Removed_Format),
nameof(RemoveGame_Title_Format),
nameof(Rules_Update_Done_Format),
nameof(Rules_Update_Failed),
nameof(Rules_Update_NoAgent),
nameof(Rules_Update_Title),
nameof(Sensors_Axis_Mb),
nameof(Sensors_Empty),
nameof(Sensors_Series_GpuHotspot),
@@ -1044,6 +1048,14 @@ public static class Strings
public static string RemoveGame_Title_Format => ResourceManager.GetString(nameof(RemoveGame_Title_Format), Culture) ?? nameof(RemoveGame_Title_Format);
public static string Rules_Update_Done_Format => ResourceManager.GetString(nameof(Rules_Update_Done_Format), Culture) ?? nameof(Rules_Update_Done_Format);
public static string Rules_Update_Failed => ResourceManager.GetString(nameof(Rules_Update_Failed), Culture) ?? nameof(Rules_Update_Failed);
public static string Rules_Update_NoAgent => ResourceManager.GetString(nameof(Rules_Update_NoAgent), Culture) ?? nameof(Rules_Update_NoAgent);
public static string Rules_Update_Title => ResourceManager.GetString(nameof(Rules_Update_Title), Culture) ?? nameof(Rules_Update_Title);
public static string Sensors_Axis_Mb => ResourceManager.GetString(nameof(Sensors_Axis_Mb), Culture) ?? nameof(Sensors_Axis_Mb);
public static string Sensors_Empty => ResourceManager.GetString(nameof(Sensors_Empty), Culture) ?? nameof(Sensors_Empty);
+17 -1
View File
@@ -245,6 +245,22 @@
<value>未実装</value>
<comment>review</comment>
</data>
<data name="Rules_Update_Title" xml:space="preserve">
<value>検出ルール</value>
<comment>review</comment>
</data>
<data name="Rules_Update_Done_Format" xml:space="preserve">
<value>ルールを確認しました ({0})。エージェントがライブラリのゲームを再スキャンしています。</value>
<comment>review</comment>
</data>
<data name="Rules_Update_NoAgent" xml:space="preserve">
<value>キャプチャエージェントが接続されていないため、ルールを更新できません。</value>
<comment>review</comment>
</data>
<data name="Rules_Update_Failed" xml:space="preserve">
<value>エージェントがルール更新に応答しませんでした。</value>
<comment>review</comment>
</data>
<data name="Settings_Appearance_Header" xml:space="preserve">
<value>外観</value>
<comment>review</comment>
@@ -662,7 +678,7 @@
<comment>review</comment>
</data>
<data name="GameDetail_Supports_Empty" xml:space="preserve">
<value>未スキャン — 機能スキャンは後のビルドで追加されます。</value>
<value>未スキャン — キャプチャエージェントは起動後数秒でゲームのファイルをスキャンします。</value>
<comment>review</comment>
</data>
<data name="GameDetail_Supports_Format" xml:space="preserve">
+13 -1
View File
@@ -189,6 +189,18 @@
<data name="NotYet_Title" xml:space="preserve">
<value>Not built yet</value>
</data>
<data name="Rules_Update_Title" xml:space="preserve">
<value>Detection rules</value>
</data>
<data name="Rules_Update_Done_Format" xml:space="preserve">
<value>Rules checked ({0}); the agent is re-scanning the library's games.</value>
</data>
<data name="Rules_Update_NoAgent" xml:space="preserve">
<value>The capture agent is not connected, so the rules cannot be updated.</value>
</data>
<data name="Rules_Update_Failed" xml:space="preserve">
<value>The agent did not answer the rules update.</value>
</data>
<data name="Settings_Appearance_Header" xml:space="preserve">
<value>Appearance</value>
</data>
@@ -502,7 +514,7 @@
<value>No sessions yet — launch the game and FrameLedger will do the rest.</value>
</data>
<data name="GameDetail_Supports_Empty" xml:space="preserve">
<value>Not scanned yet — the capability scan arrives with a later build.</value>
<value>Not scanned yet — the capture agent scans a game's files within seconds of running.</value>
</data>
<data name="GameDetail_Supports_Format" xml:space="preserve">
<value>Supports {0}</value>
+13 -1
View File
@@ -184,6 +184,18 @@
<data name="NotYet_Title" xml:space="preserve">
<value>Chưa xây dựng</value>
</data>
<data name="Rules_Update_Title" xml:space="preserve">
<value>Quy tắc nhận diện</value>
</data>
<data name="Rules_Update_Done_Format" xml:space="preserve">
<value>Đã kiểm tra quy tắc ({0}); agent đang quét lại các game trong thư viện.</value>
</data>
<data name="Rules_Update_NoAgent" xml:space="preserve">
<value>Agent ghi chưa kết nối nên không thể cập nhật quy tắc.</value>
</data>
<data name="Rules_Update_Failed" xml:space="preserve">
<value>Agent không phản hồi yêu cầu cập nhật quy tắc.</value>
</data>
<data name="Settings_Appearance_Header" xml:space="preserve">
<value>Giao diện</value>
</data>
@@ -497,7 +509,7 @@
<value>Chưa có phiên nào — hãy chạy game, FrameLedger lo phần còn lại.</value>
</data>
<data name="GameDetail_Supports_Empty" xml:space="preserve">
<value>Chưa quét — tính năng quét khả năng sẽ có ở bản sau.</value>
<value>Chưa quét — agent ghi sẽ quét file của game trong vài giây sau khi chạy.</value>
</data>
<data name="GameDetail_Supports_Format" xml:space="preserve">
<value>Hỗ trợ {0}</value>
@@ -535,7 +535,11 @@ public sealed partial class GameDetailViewModel : ObservableObject
_ => row.RrDefault,
};
/// <summary><c>capability_flags</c> (<c>05_DETECTION</c> §Capability hints): an object of flags or an array of tokens → product names. Nothing writes it before P4; an unreadable value is no chips.</summary>
/// <summary>
/// <c>capability_flags</c> (<c>05_DETECTION</c> §Capability hints): an array of the rule ids the Agent's detection sweep
/// writes (P4 PR-1 — <c>dlss</c>, <c>dlss_g</c>, <c>dlss_rr</c>, <c>streamline</c>, <c>fsr</c>, <c>xess</c>, <c>xefg</c>), or
/// an object of flags in the older spelling, → product names. An unreadable value is no chips.
/// </summary>
internal static IReadOnlyList<string> CapabilityNames(string? json)
{
if (string.IsNullOrWhiteSpace(json))
@@ -559,8 +563,9 @@ public sealed partial class GameDetailViewModel : ObservableObject
private static string CapabilityName(string token) => token switch
{
"dlss" => "DLSS",
"dlssg" => "DLSS-G",
"dlssd" => "DLSS Ray Reconstruction",
"dlssg" or "dlss_g" => "DLSS-G",
"dlssd" or "dlss_rr" => "DLSS Ray Reconstruction",
"streamline" => "Streamline",
"fsr" => "FSR",
"fsrfg" => "FSR Frame Generation",
"xess" => "XeSS",
@@ -6,6 +6,8 @@ using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FrameLedger.App.Pages;
using FrameLedger.App.Services;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Shared.Ipc;
using Wpf.Ui;
using Wpf.Ui.Controls;
@@ -114,6 +116,35 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
await box.ShowDialogAsync().ConfigureAwait(true);
}
/// <summary>
/// Tools ▸ Update detection rules (P4 PR-1): the Agent re-seeds the rules file and wakes its detection sweep, so every
/// game's engine / platform / Supports row follows within the second (<c>05_DETECTION</c> §Caching). The ack's
/// outcome is the seeder's word — <c>AlreadyCurrent</c>, <c>Updated</c>, … — shown as is; there is no fetch yet.
/// </summary>
[RelayCommand]
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format string is a resource that follows the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")]
private async Task UpdateRulesAsync()
{
if (!_agent.IsConnected)
{
_snackbar.Show(Strings.Rules_Update_Title, Strings.Rules_Update_NoAgent, ControlAppearance.Caution, new SymbolIcon(SymbolRegular.Warning24), TimeSpan.FromSeconds(4));
return;
}
try
{
IpcEnvelope ack = await _agent.RequestAsync(IpcMessageType.UpdateRules, new UpdateRulesRequest()).ConfigureAwait(true);
string outcome = IpcCodec.Payload<UpdateRulesAck>(ack)?.Outcome ?? string.Empty;
_snackbar.Show(Strings.Rules_Update_Title, string.Format(CultureInfo.CurrentCulture, Strings.Rules_Update_Done_Format, outcome),
ControlAppearance.Secondary, new SymbolIcon(SymbolRegular.Info24), TimeSpan.FromSeconds(4));
}
catch (Exception ex) when (ex is IpcRequestException or TimeoutException or System.IO.IOException or InvalidOperationException)
{
Serilog.Log.Warning(ex, "ui: update rules did not complete");
_snackbar.Show(Strings.Rules_Update_Title, Strings.Rules_Update_Failed, ControlAppearance.Caution, new SymbolIcon(SymbolRegular.Warning24), TimeSpan.FromSeconds(4));
}
}
/// <summary>Every menu item of <c>08_UI</c> §Menu bar that a later slice builds says so, in a 4 s snackbar, rather than doing nothing.</summary>
[RelayCommand]
private void NotYet() =>
@@ -0,0 +1,133 @@
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Watch;
using FrameLedger.Domain.Consent;
using FrameLedger.Domain.Detection;
namespace FrameLedger.Application.Detection;
/// <summary>
/// The static detection engine's first production caller (P4 PR-1): once per sweep, every game in the library
/// whose <c>DetectionCacheKey</c> is stale — never scanned, the exe changed, or the rules moved on — is run through
/// <see cref="StaticGameDetector"/> and the result persisted through <see cref="IGameRepository.ApplyDetectionAsync"/>.
/// </summary>
/// <remarks>
/// <para>
/// <b>What "stale" is</b> (<c>05_DETECTION</c> §Caching): the stored <c>detection_rules_version</c> differs from the
/// rules file's, or the stored exe size / mtime (schema 0004 — the detection key's own columns, never the consent
/// fingerprint) differ from the file on disk right now. An unreadable exe is skipped and named once per sweep; an
/// unreadable rules file ends the sweep with nothing written.
/// </para>
/// <para>
/// <b>Where it runs.</b> <c>GameFileProbe</c> does blocking file I/O (a bounded directory walk and an 8 MB strings
/// pass), so the sweep belongs on its own background task — the Agent's <c>DetectionHostedService</c> — and never
/// on the orchestrator's poll or a UI thread. It writes only the detected columns of <c>games</c>, under the
/// repository's provenance rule; it is not a third writer of <c>ledger.db</c> (HANDOFF §P4).
/// </para>
/// <para>
/// <b>When it wakes.</b> On an interval, and immediately after <c>UpdateRules</c> re-seeds the rules file
/// (<see cref="RequestNow"/>): a rules update is the trigger §Caching names, and a game the App just added is
/// picked up on the next tick because the App writes the row and the Agent reads the same table.
/// </para>
/// </remarks>
public sealed class DetectionSweep : IDisposable
{
private readonly IGameRepository _games;
private readonly IDetectionRulesSource _rules;
private readonly StaticGameDetector _detector;
private readonly IExecutableIdentitySource _identity;
private readonly Action<string> _log;
private readonly SemaphoreSlim _wake = new(0, 1);
public DetectionSweep(IGameRepository games, IDetectionRulesSource rules, IGameFileProbe probe, IExecutableIdentitySource identity, Action<string> log)
{
_games = games ?? throw new ArgumentNullException(nameof(games));
_rules = rules ?? throw new ArgumentNullException(nameof(rules));
ArgumentNullException.ThrowIfNull(probe);
_identity = identity ?? throw new ArgumentNullException(nameof(identity));
_log = log ?? throw new ArgumentNullException(nameof(log));
_detector = new StaticGameDetector(rules, probe);
}
/// <summary>Wake the hosted loop before its interval elapses (the <c>UpdateRules</c> trigger). Idempotent.</summary>
public void RequestNow()
{
try
{
_wake.Release();
}
catch (SemaphoreFullException)
{
// Already requested and not yet consumed: one wake is one wake.
}
}
/// <summary>Wait for <see cref="RequestNow"/> or <paramref name="interval"/>, whichever first. True when woken early.</summary>
public Task<bool> WaitAsync(TimeSpan interval, CancellationToken ct) => _wake.WaitAsync(interval, ct);
public void Dispose() => _wake.Dispose();
/// <summary>One pass over the library. Returns what it scanned and what it skipped.</summary>
public async ValueTask<DetectionSweepReport> SweepOnceAsync(CancellationToken ct = default)
{
DetectionRuleSet rules;
try
{
rules = await _rules.LoadAsync(ct).ConfigureAwait(false);
}
catch (InvalidOperationException ex)
{
_log($"detect: rules unusable, nothing scanned — {ex.Message}");
return new DetectionSweepReport { RulesUnusable = true };
}
int scanned = 0;
int current = 0;
int unreadable = 0;
foreach (GameRow game in await _games.ListAsync(ct).ConfigureAwait(false))
{
ct.ThrowIfCancellationRequested();
if (_identity.Read(game.Fingerprint.ExePath) is not { } onDisk)
{
unreadable++;
_log($"detect: {game.Name} — executable unreadable, skipped ({game.Fingerprint.ExePath})");
continue;
}
if (!IsStale(game, onDisk, rules.RulesVersion))
{
current++;
continue;
}
StaticDetectionResult r = await _detector.DetectAsync(game.Fingerprint.ExePath, ct).ConfigureAwait(false);
var write = new DetectionWrite
{
EngineId = r.EngineId,
EngineVersion = r.EngineVersion,
PlatformId = r.PlatformId,
CapabilityIds = r.CapabilityIds,
RulesVersion = r.RulesVersion,
ExeSizeBytes = onDisk.SizeBytes,
ExeMtimeMs = onDisk.MtimeUnixMs,
};
if (await _games.ApplyDetectionAsync(game.Id, write, ct).ConfigureAwait(false))
{
scanned++;
_log($"detect: {game.Name} — engine={r.EngineId ?? (r.EngineUndetermined ? "undetermined" : "none")}"
+ $"{(r.EngineVersion is null ? string.Empty : " " + r.EngineVersion)} platform={r.PlatformId ?? (r.PlatformUndetermined ? "undetermined" : "none")}"
+ $" capabilities=[{string.Join(",", r.CapabilityIds)}] rules={r.RulesVersion}");
}
}
return new DetectionSweepReport { Scanned = scanned, Current = current, Unreadable = unreadable };
}
/// <summary><c>DetectionCacheKey</c> compared field by field against the row: any difference is a re-run.</summary>
public static bool IsStale(GameRow game, ExecutableFingerprint onDisk, string rulesVersion)
{
ArgumentNullException.ThrowIfNull(game);
return !string.Equals(game.DetectionRulesVersion, rulesVersion, StringComparison.Ordinal)
|| game.DetectionExeSizeBytes != onDisk.SizeBytes
|| game.DetectionExeMtimeMs != onDisk.MtimeUnixMs;
}
}
@@ -0,0 +1,17 @@
namespace FrameLedger.Application.Detection;
/// <summary>What one <see cref="DetectionSweep.SweepOnceAsync"/> did.</summary>
public sealed record DetectionSweepReport
{
/// <summary>Games detected and written this pass.</summary>
public int Scanned { get; init; }
/// <summary>Games whose cache key matched, left alone.</summary>
public int Current { get; init; }
/// <summary>Games whose executable could not be read, skipped.</summary>
public int Unreadable { get; init; }
/// <summary>The rules file could not be loaded; nothing was scanned.</summary>
public bool RulesUnusable { get; init; }
}
@@ -0,0 +1,37 @@
namespace FrameLedger.Application.Persistence;
/// <summary>
/// What one static detection run wants to persist on a <c>games</c> row (P4 PR-1): the engine, its version, the
/// platform, the capability ids, and the cache key it ran under (<c>05_DETECTION</c> §Caching). The repository — not
/// the caller — applies the provenance rule: a field the user supplied is never overwritten, a field detection
/// wrote before is refreshed, and an empty field with no provenance is filled and badged <c>detected</c>.
/// </summary>
/// <remarks>
/// A null <see cref="EngineId"/> / <see cref="EngineVersion"/> / <see cref="PlatformId"/> means "not established"
/// (<c>StaticDetectionResult</c>): the existing value is left as it is, whatever its provenance — detection never
/// erases. <see cref="CapabilityIds"/> is always written in full (an empty list clears the row's flags), because the
/// Supports row has no user-edit surface and a stale "Supports DLSS-G" after the DLL was removed is the confusion
/// <c>05_DETECTION</c> §Capability hints exists to prevent.
/// </remarks>
public sealed record DetectionWrite
{
/// <summary>The engine rule id, or null when no engine rule matched or the walk stopped on <c>Unknown</c>.</summary>
public string? EngineId { get; init; }
public string? EngineVersion { get; init; }
/// <summary>The platform rule id (<c>steam</c>, <c>gog</c>, <c>epic</c>, <c>itch</c>), or null.</summary>
public string? PlatformId { get; init; }
/// <summary>The capability rule ids that matched, in rule order; stored verbatim as a JSON array.</summary>
public required IReadOnlyList<string> CapabilityIds { get; init; }
/// <summary>The <c>rulesVersion</c> the run evaluated under.</summary>
public required string RulesVersion { get; init; }
/// <summary>The exe size the run saw (the cache key's exe half — never the consent fingerprint).</summary>
public required long ExeSizeBytes { get; init; }
/// <summary>The exe mtime, unix ms, the run saw.</summary>
public required long ExeMtimeMs { get; init; }
}
@@ -50,9 +50,18 @@ public sealed record GameRow
/// <summary><c>field_provenance</c> as stored (JSON object field → <c>detected|user</c>); null or absent reads as <c>user</c> for every field.</summary>
public string? FieldProvenanceJson { get; init; }
/// <summary><c>capability_flags</c> as stored — what the game SHIPS, never a measurement (FR-1.5).</summary>
/// <summary><c>capability_flags</c> as stored — what the game SHIPS, never a measurement (FR-1.5). Since P4 PR-1 a JSON array of the rule ids of <c>rules/detection-rules.json</c>.</summary>
public string? CapabilityFlagsJson { get; init; }
/// <summary>The <c>rulesVersion</c> the last static detection ran under (<c>DetectionCacheKey</c>'s rules half); null = never scanned.</summary>
public string? DetectionRulesVersion { get; init; }
/// <summary>The exe size the last static detection saw (schema 0004) — the key's exe half, NOT the consent fingerprint.</summary>
public long? DetectionExeSizeBytes { get; init; }
/// <summary>The exe mtime (unix ms) the last static detection saw (schema 0004).</summary>
public long? DetectionExeMtimeMs { get; init; }
// FR-8.3 game defaults, inherited by sessions that measured nothing.
public Tri RtDefault { get; init; } = Tri.NotApplicable;
@@ -40,4 +40,12 @@ public interface IGameRepository
/// Touches no hook-state column: revoking consent is the pipe's <c>SetHookEnabled false</c>, sent first.
/// </summary>
ValueTask<bool> RemoveAsync(long gameId, bool keepSessions, CancellationToken ct = default);
/// <summary>
/// The Agent's detection sweep (P4 PR-1): persist one static detection run under the provenance rule of
/// <c>05_DETECTION</c> §Caching — a <c>user</c> field is never overwritten, a <c>detected</c> one is refreshed, an
/// empty field with no provenance is filled and badged <c>detected</c>; <c>capability_flags</c> and the cache key
/// are always written. False when the game does not exist.
/// </summary>
ValueTask<bool> ApplyDetectionAsync(long gameId, DetectionWrite detection, CancellationToken ct = default);
}
@@ -0,0 +1,17 @@
-- 0004 (P4 PR-1, 2026-09-14): the detection cache key's exe half, as its own columns.
--
-- 05_DETECTION §Caching keys a game's static detection on path + size + mtime + rulesVersion
-- (DetectionCacheKey). 0001 gave the rules half a column (detection_rules_version) and it looked
-- as if games.exe_size_bytes / exe_mtime_ms were the other half -- but those two are the
-- CONSENT fingerprint (SqliteGameConsentStore refuses a mismatching fingerprint while a block
-- stands, 19_SAFETY), written when the user consents and never by a background scan. A sweep
-- that refreshed them after a game patch would silently re-point a consent at a binary nobody
-- consented to. So the detection key gets its own two columns and touches nothing the gate reads.
--
-- NULL = never scanned by this build's sweep. The Agent writes both beside detection_rules_version
-- (06_DATA_MODEL §Writer ownership, the detected columns); the UI reads them only to say "scanned".
--
-- ALTER TABLE ADD COLUMN only: 0001..0003 are applied on real machines and are never edited.
ALTER TABLE games ADD COLUMN detection_exe_size_bytes INTEGER;
ALTER TABLE games ADD COLUMN detection_exe_mtime_ms INTEGER;
@@ -22,7 +22,8 @@ public sealed class SqliteGameRepository : IGameRepository
"id, name, exe_path, exe_size_bytes, exe_mtime_ms, hook_enabled, hook_blocked_reason, hook_autodisabled_reason, "
+ "hook_crash_count, hook_last_injected_at, added_at, updated_at, "
+ "platform, store_id, engine, engine_version, publisher, game_version, cover_path, notes, field_provenance, capability_flags, "
+ "rt_default, pt_default, rr_default, hook_consent_at, hook_prescan_state, removed_at";
+ "rt_default, pt_default, rr_default, hook_consent_at, hook_prescan_state, removed_at, "
+ "detection_rules_version, detection_exe_size_bytes, detection_exe_mtime_ms";
private const string _selectByPath = $"SELECT {_columns} FROM games WHERE exe_path = @path";
@@ -53,6 +54,11 @@ public sealed class SqliteGameRepository : IGameRepository
private const string _delete = "DELETE FROM games WHERE id = @id";
private const string _applyDetection =
"UPDATE games SET engine = @engine, engine_version = @engineVersion, platform = @platform, capability_flags = @flags, "
+ "field_provenance = @provenance, detection_rules_version = @rules, detection_exe_size_bytes = @size, detection_exe_mtime_ms = @mtime, "
+ "updated_at = @now WHERE id = @id";
private readonly LedgerDatabase _db;
public SqliteGameRepository(LedgerDatabase db) => _db = db ?? throw new ArgumentNullException(nameof(db));
@@ -171,6 +177,42 @@ public sealed class SqliteGameRepository : IGameRepository
return n == 1;
}, ct);
public ValueTask<bool> ApplyDetectionAsync(long gameId, DetectionWrite detection, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(detection);
ArgumentException.ThrowIfNullOrWhiteSpace(detection.RulesVersion, nameof(detection));
return _db.WriteAsync(async (c, tx, token) =>
{
GameRow? before = await SqliteReaders.ReadOneAsync(c, new CommandDefinition(_selectById, new { id = gameId }, tx, cancellationToken: token), Read).ConfigureAwait(false);
if (before is null)
{
return false;
}
// The provenance rule (05_DETECTION §Caching), applied per field: a user's value is never overwritten, a
// detected one is refreshed, and an empty field with no provenance is filled and badged. A null detected
// value leaves the field as it is — detection never erases.
Dictionary<string, string> map = FieldProvenance.Parse(before.FieldProvenanceJson);
string? engine = FieldProvenance.Resolve(map, "engine", before.Engine, detection.EngineId);
string? engineVersion = FieldProvenance.Resolve(map, "engine_version", before.EngineVersion, detection.EngineVersion);
string platform = FieldProvenance.Resolve(map, "platform", string.Equals(before.Platform, "none", StringComparison.Ordinal) ? null : before.Platform, detection.PlatformId) ?? "none";
var p = new
{
id = gameId,
engine,
engineVersion,
platform,
flags = JsonSerializer.Serialize(detection.CapabilityIds.ToArray(), LedgerJsonContext.Default.StringArray),
provenance = map.Count == 0 ? before.FieldProvenanceJson : JsonSerializer.Serialize(map, LedgerJsonContext.Default.DictionaryStringString),
rules = detection.RulesVersion,
size = detection.ExeSizeBytes,
mtime = detection.ExeMtimeMs,
now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
};
return await c.ExecuteAsync(new CommandDefinition(_applyDetection, p, tx, cancellationToken: token)).ConfigureAwait(false) == 1;
}, ct);
}
private static Task<GameRow?> ReadByPathAsync(SqliteConnection c, SqliteTransaction? tx, string path, CancellationToken ct) =>
SqliteReaders.ReadOneAsync(c, new CommandDefinition(_selectByPath, new { path }, tx, cancellationToken: ct), Read);
@@ -211,6 +253,9 @@ public sealed class SqliteGameRepository : IGameRepository
HookConsentAt = At(SqliteReaders.Int64(r, 25)),
HookPrescanState = SqliteReaders.String(r, 26) ?? "not_run",
RemovedAt = At(SqliteReaders.Int64(r, 27)),
DetectionRulesVersion = SqliteReaders.String(r, 28),
DetectionExeSizeBytes = SqliteReaders.Int64(r, 29),
DetectionExeMtimeMs = SqliteReaders.Int64(r, 30),
};
private static DateTimeOffset? At(long? unixMs) => unixMs is { } ms ? DateTimeOffset.FromUnixTimeMilliseconds(ms) : null;
@@ -220,6 +265,34 @@ public sealed class SqliteGameRepository : IGameRepository
{
public const string User = "user";
public const string Detected = "detected";
/// <summary>
/// The value a detection run leaves in <paramref name="field"/>, and the map updated to match (P4 PR-1). Null
/// <paramref name="detected"/> = not established: the current value stays and the map is untouched. A field
/// badged <c>detected</c> is refreshed. A field with no entry and no value has nothing to protect: it is filled
/// and badged. Anything else — a <c>user</c> entry, an unrecognised entry, or a value with no entry — reads as
/// the user's (<c>05_DETECTION</c> §Caching, <c>06_DATA_MODEL</c> §games) and is left alone.
/// </summary>
public static string? Resolve(Dictionary<string, string> map, string field, string? current, string? detected)
{
if (detected is null)
{
return current;
}
bool writable = map.TryGetValue(field, out string? badge)
? string.Equals(badge, Detected, StringComparison.Ordinal)
: string.IsNullOrEmpty(current);
if (!writable)
{
return current;
}
map[field] = Detected;
return detected;
}
/// <summary>The stored JSON after a user edit: every field whose value changed is now <c>user</c>; the rest keep what they had.</summary>
public static string? AfterUserEdit(string? storedJson, GameMetadata before, GameMetadata after)
{
@@ -138,6 +138,39 @@ public sealed class GameDetailViewModelTests
}
}
/// <summary>The Supports row (P4 PR-1): what the Agent's detection sweep wrote, as product names, and nothing measured.</summary>
[Fact]
public async Task TheSupportsRowReadsWhatTheDetectionSweepWrote()
{
CultureInfo? previous = Strings.Culture;
Strings.Culture = CultureInfo.GetCultureInfo("en");
try
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
GameRow game = await s.GameAsync("Scanned");
(await s.Games.ApplyDetectionAsync(game.Id, new DetectionWrite
{
EngineId = "unreal",
EngineVersion = "5.4",
PlatformId = "steam",
CapabilityIds = ["dlss", "dlss_g", "streamline"],
RulesVersion = "2026.09.1",
ExeSizeBytes = 1,
ExeMtimeMs = 1,
}, Ct)).Should().BeTrue();
(GameDetailViewModel vm, _, _, _, _) = await BuildAsync(s, game.Id);
vm.SupportsEmpty.Should().BeFalse();
vm.Supports.Should().Equal("Supports DLSS", "Supports DLSS-G", "Supports Streamline");
vm.Subtitle.Should().Contain("Steam", "the detected platform reaches the header");
}
finally
{
Strings.Culture = previous;
}
}
[Fact]
public async Task TheHeaderTheTwoRowsAndTheSessionsTabReadFromTheLedger()
{
@@ -158,7 +191,7 @@ public sealed class GameDetailViewModelTests
vm.Name.Should().Be("Alpha");
vm.Subtitle.Should().Be("Pub · 1.2 · Steam");
vm.Lifetime.Kind.Should().Be(FpsReadoutKind.Generated, "the last HOOKED session, not the last session");
vm.SupportsEmpty.Should().BeTrue("nothing wrote capability_flags before P4");
vm.SupportsEmpty.Should().BeTrue("the Agent's sweep has not written capability_flags for this game yet");
vm.Measured.Should().Contain(static m => m.StartsWith("DLSS", StringComparison.Ordinal)).And.Contain(static m => m.StartsWith("DLSS-G", StringComparison.Ordinal));
vm.Chips.Should().HaveCount(3);
vm.Chips[0].IsYes.Should().BeTrue("rt_flag = yes on the last hooked session");
@@ -323,6 +356,8 @@ public sealed class GameDetailViewModelTests
{
GameDetailViewModel.CapabilityNames("{\"dlss\":true,\"dlssg\":true,\"fsr\":false,\"weird\":true}").Should().Equal("DLSS", "DLSS-G");
GameDetailViewModel.CapabilityNames("[\"xess\",\"xefg\"]").Should().Equal("XeSS", "XeFG");
GameDetailViewModel.CapabilityNames("[\"dlss\",\"dlss_g\",\"dlss_rr\",\"streamline\",\"fsr\"]")
.Should().Equal("DLSS", "DLSS-G", "DLSS Ray Reconstruction", "Streamline", "FSR"); // the rule ids of rules/detection-rules.json, as the Agent's sweep writes them (P4 PR-1)
GameDetailViewModel.CapabilityNames("not json").Should().BeEmpty();
GameDetailViewModel.CapabilityNames(null).Should().BeEmpty();
}
@@ -0,0 +1,172 @@
using FluentAssertions;
using FrameLedger.Application.Detection;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Tests.Recording;
using FrameLedger.Application.Watch;
using FrameLedger.Domain.Consent;
using FrameLedger.Domain.Detection;
namespace FrameLedger.Application.Tests.Detection;
/// <summary>
/// The sweep (P4 PR-1): a game is scanned when its cache key is stale — never scanned, the exe changed, the rules
/// moved on — and left alone when it is current (<c>05_DETECTION</c> §Caching). An unreadable exe is skipped, an
/// unusable rules file scans nothing, and <c>RequestNow</c> wakes the loop before its interval.
/// </summary>
public sealed class DetectionSweepTests
{
private const string _exe = @"C:\Games\Title\game.exe";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private sealed class ScriptedRules(string version) : IDetectionRulesSource
{
public string Version { get; set; } = version;
public bool Unusable { get; set; }
public ValueTask<DetectionRuleSet> LoadAsync(CancellationToken ct = default) => Unusable
? throw new InvalidOperationException("rules unusable")
: ValueTask.FromResult(new DetectionRuleSet
{
SchemaVersion = 2,
RulesVersion = Version,
Engines = [new EngineRule { Id = "unity", Name = "Unity", Signals = new SignalGroup { Combinator = SignalCombinator.All, Signals = [new DetectionSignal { Type = DetectionSignalType.SiblingGlob, Value = "UnityPlayer.dll" }] } }],
Platforms = [new PlatformRule { Id = "steam", Name = "Steam", Signals = new SignalGroup { Combinator = SignalCombinator.Any, Signals = [new DetectionSignal { Type = DetectionSignalType.SiblingGlob, Value = "steam_api64.dll" }] } }],
Capabilities = [new CapabilityRule { Id = "dlss", Name = "DLSS", Signals = new SignalGroup { Combinator = SignalCombinator.Any, Signals = [new DetectionSignal { Type = DetectionSignalType.SiblingGlob, Value = "nvngx_dlss.dll" }] } }],
});
}
private sealed class ScriptedProbe : IGameFileProbe
{
public int Calls { get; private set; }
public ValueTask<GameFileSnapshot> SnapshotAsync(string exePath, DetectionRuleSet rules, CancellationToken ct = default)
{
Calls++;
return ValueTask.FromResult(new GameFileSnapshot
{
ExePath = exePath,
ExeNameWithoutExtension = "game",
GameDirectory = "C:/Games/Title",
RelativeFiles = ["game.exe", "UnityPlayer.dll", "steam_api64.dll", "nvngx_dlss.dll"],
RelativeDirectories = [],
FileListingComplete = true,
SiblingFileVersions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase),
MatchedStringNeedles = new HashSet<string>(StringComparer.Ordinal),
StringsRegexCaptures = new Dictionary<string, string>(StringComparer.Ordinal),
ManifestFields = new Dictionary<string, string>(StringComparer.Ordinal),
UncollectedFacts = new HashSet<DetectionSignalType>(),
});
}
}
private sealed class FakeIdentity : IExecutableIdentitySource
{
public ExecutableFingerprint? OnDisk { get; set; } = new() { ExePath = _exe, SizeBytes = 5, MtimeUnixMs = 5 };
public ExecutableFingerprint? Read(string normalisedExePath) => OnDisk;
public string Normalise(string exePath) => exePath;
}
private static async Task<(DetectionSweep Sweep, FakeGameRepository Games, ScriptedRules Rules, ScriptedProbe Probe, FakeIdentity Identity, List<string> Log)> BuildAsync()
{
var games = new FakeGameRepository();
await games.EnsureAsync(new ExecutableFingerprint { ExePath = _exe, SizeBytes = 1, MtimeUnixMs = 1 }, "Title", Ct).ConfigureAwait(false);
var rules = new ScriptedRules("2026.09.1");
var probe = new ScriptedProbe();
var identity = new FakeIdentity();
List<string> log = [];
return (new DetectionSweep(games, rules, probe, identity, log.Add), games, rules, probe, identity, log);
}
[Fact]
public async Task AGameNeverScannedIsScannedOnceAndThenLeftAloneWhileItsKeyHolds()
{
(DetectionSweep sweep, FakeGameRepository games, _, ScriptedProbe probe, _, List<string> log) = await BuildAsync();
DetectionSweepReport first = await sweep.SweepOnceAsync(Ct);
first.Scanned.Should().Be(1);
first.Current.Should().Be(0);
probe.Calls.Should().Be(1);
(long GameId, DetectionWrite Write) w = games.Detections.Single();
w.Write.EngineId.Should().Be("unity");
w.Write.PlatformId.Should().Be("steam");
w.Write.CapabilityIds.Should().Equal("dlss");
w.Write.RulesVersion.Should().Be("2026.09.1");
w.Write.ExeSizeBytes.Should().Be(5, "the key's exe half is what is on disk NOW, not the consent fingerprint the row was added with");
w.Write.ExeMtimeMs.Should().Be(5);
log.Should().ContainSingle(static l => l.Contains("engine=unity", StringComparison.Ordinal) && l.Contains("capabilities=[dlss]", StringComparison.Ordinal));
DetectionSweepReport second = await sweep.SweepOnceAsync(Ct);
second.Scanned.Should().Be(0);
second.Current.Should().Be(1, "the stored key matches the file and the rules");
probe.Calls.Should().Be(1, "a current game is not walked again");
}
[Fact]
public async Task AChangedExeOrANewRulesVersionRescans()
{
(DetectionSweep sweep, FakeGameRepository games, ScriptedRules rules, ScriptedProbe probe, FakeIdentity identity, _) = await BuildAsync();
await sweep.SweepOnceAsync(Ct);
identity.OnDisk = new ExecutableFingerprint { ExePath = _exe, SizeBytes = 6, MtimeUnixMs = 9 };
(await sweep.SweepOnceAsync(Ct)).Scanned.Should().Be(1, "the exe on disk changed (a patch)");
games.Detections[^1].Write.ExeSizeBytes.Should().Be(6);
rules.Version = "2026.10.1";
(await sweep.SweepOnceAsync(Ct)).Scanned.Should().Be(1, "the rules moved on — the trigger 05_DETECTION §Caching names");
games.Detections[^1].Write.RulesVersion.Should().Be("2026.10.1");
probe.Calls.Should().Be(3);
(await sweep.SweepOnceAsync(Ct)).Scanned.Should().Be(0);
}
[Fact]
public async Task AnUnreadableExeIsSkippedAndNamedAndAnUnusableRulesFileScansNothing()
{
(DetectionSweep sweep, FakeGameRepository games, ScriptedRules rules, ScriptedProbe probe, FakeIdentity identity, List<string> log) = await BuildAsync();
identity.OnDisk = null;
DetectionSweepReport r = await sweep.SweepOnceAsync(Ct);
r.Unreadable.Should().Be(1);
r.Scanned.Should().Be(0);
probe.Calls.Should().Be(0, "nothing is walked for a file that cannot be read");
log.Should().ContainSingle(static l => l.Contains("unreadable", StringComparison.Ordinal));
identity.OnDisk = new ExecutableFingerprint { ExePath = _exe, SizeBytes = 5, MtimeUnixMs = 5 };
rules.Unusable = true;
DetectionSweepReport bad = await sweep.SweepOnceAsync(Ct);
bad.RulesUnusable.Should().BeTrue();
bad.Scanned.Should().Be(0);
games.Detections.Should().BeEmpty("an unusable rules file writes nothing rather than a wrong answer");
}
[Fact]
public async Task RequestNowWakesTheWaitBeforeTheIntervalAndIsIdempotent()
{
(DetectionSweep sweep, _, _, _, _, _) = await BuildAsync();
sweep.RequestNow();
sweep.RequestNow();
(await sweep.WaitAsync(TimeSpan.FromSeconds(30), Ct)).Should().BeTrue("woken at once — the request was queued before the wait");
(await sweep.WaitAsync(TimeSpan.FromMilliseconds(50), Ct)).Should().BeFalse("two requests while nobody waited are one wake; the second wait times out");
Task<bool> waiting = sweep.WaitAsync(TimeSpan.FromSeconds(30), Ct);
sweep.RequestNow();
(await waiting).Should().BeTrue("a waiter is woken early");
}
[Fact]
public void StalenessIsTheCacheKeyFieldByField()
{
var onDisk = new ExecutableFingerprint { ExePath = _exe, SizeBytes = 5, MtimeUnixMs = 7 };
GameRow current = new() { Id = 1, Name = "T", Fingerprint = onDisk, HookEnabled = false, HookCrashCount = 0, AddedAt = DateTimeOffset.UnixEpoch, UpdatedAt = DateTimeOffset.UnixEpoch, DetectionRulesVersion = "v", DetectionExeSizeBytes = 5, DetectionExeMtimeMs = 7 };
DetectionSweep.IsStale(current, onDisk, "v").Should().BeFalse();
DetectionSweep.IsStale(current with { DetectionRulesVersion = null }, onDisk, "v").Should().BeTrue("never scanned");
DetectionSweep.IsStale(current, onDisk, "w").Should().BeTrue("rules moved");
DetectionSweep.IsStale(current with { DetectionExeSizeBytes = 4 }, onDisk, "v").Should().BeTrue("size changed");
DetectionSweep.IsStale(current with { DetectionExeMtimeMs = 8 }, onDisk, "v").Should().BeTrue("mtime changed");
}
}
@@ -66,4 +66,33 @@ internal sealed class FakeGameRepository : IGameRepository
public ValueTask<bool> SetTriStateDefaultAsync(long gameId, TriStateKind kind, Tri value, CancellationToken ct = default) => throw new NotSupportedException();
public ValueTask<bool> RemoveAsync(long gameId, bool keepSessions, CancellationToken ct = default) => throw new NotSupportedException();
/// <summary>Every detection write, in order (P4 PR-1); the row gains the cache key and the flags so a second sweep sees it as current.</summary>
public List<(long GameId, DetectionWrite Write)> Detections { get; } = [];
public ValueTask<bool> ApplyDetectionAsync(long gameId, DetectionWrite detection, CancellationToken ct = default)
{
Detections.Add((gameId, detection));
foreach ((string key, GameRow row) in Rows)
{
if (row.Id != gameId)
{
continue;
}
Rows[key] = row with
{
Engine = detection.EngineId ?? row.Engine,
EngineVersion = detection.EngineVersion ?? row.EngineVersion,
Platform = detection.PlatformId ?? row.Platform,
CapabilityFlagsJson = "[" + string.Join(",", detection.CapabilityIds.Select(static c => "\"" + c + "\"")) + "]",
DetectionRulesVersion = detection.RulesVersion,
DetectionExeSizeBytes = detection.ExeSizeBytes,
DetectionExeMtimeMs = detection.ExeMtimeMs,
};
return ValueTask.FromResult(true);
}
return ValueTask.FromResult(false);
}
}
@@ -44,6 +44,20 @@ public sealed class LedgerDatabaseTests
columns.Should().Contain("fg_refusal").And.Contain("fg_none_withheld_reason", "0003 appends beside 0001's columns, it edits nothing");
}
/// <summary>Schema 0004 (P4 PR-1): the detection cache key's exe half on <c>games</c>, apart from the consent fingerprint.</summary>
[Fact]
public async Task ScriptFourAddsTheDetectionCacheColumns()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(4);
IReadOnlyList<string> columns = await f.Db.ReadAsync(async (c, ct) =>
(IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('games')", cancellationToken: ct)).ConfigureAwait(false)], Ct);
columns.Should().Contain("detection_exe_size_bytes").And.Contain("detection_exe_mtime_ms")
.And.Contain("exe_size_bytes", "the consent fingerprint keeps its own columns; the sweep never writes them");
}
[Fact]
public async Task ReopeningIsANoOp()
{
@@ -20,6 +20,74 @@ public sealed class SqliteGameRepositoryTests
private static readonly ExecutableFingerprint _exe = new() { ExePath = @"C:\Games\T\t.exe", SizeBytes = 10, MtimeUnixMs = 20 };
/// <summary>
/// The Agent's detection write (P4 PR-1) under the provenance rule of <c>05_DETECTION</c> §Caching: an empty field
/// is filled and badged <c>detected</c>; a <c>detected</c> field is refreshed; a <c>user</c> field is never touched;
/// a null detected value erases nothing; the flags and the cache key are always written — and the consent
/// fingerprint (<c>exe_size_bytes</c> / <c>exe_mtime_ms</c>) is not, because the gate reads it.
/// </summary>
[Fact]
public async Task ADetectionWriteFillsEmptyFieldsRefreshesDetectedOnesAndNeverTouchesTheUsers()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var repo = new SqliteGameRepository(f.Db);
GameRow row = await repo.EnsureAsync(_exe, "Title", Ct);
(await repo.ApplyDetectionAsync(row.Id, new DetectionWrite
{
EngineId = "unity",
EngineVersion = "2022.3.1",
PlatformId = "steam",
CapabilityIds = ["dlss", "dlss_g", "streamline"],
RulesVersion = "2026.09.1",
ExeSizeBytes = 777,
ExeMtimeMs = 888,
}, Ct)).Should().BeTrue();
GameRow first = (await repo.FindByIdAsync(row.Id, Ct))!;
first.Engine.Should().Be("unity");
first.EngineVersion.Should().Be("2022.3.1");
first.Platform.Should().Be("steam", "the default 'none' is an empty field with nothing to protect");
first.CapabilityFlagsJson.Should().Be("[\"dlss\",\"dlss_g\",\"streamline\"]");
first.DetectionRulesVersion.Should().Be("2026.09.1");
first.DetectionExeSizeBytes.Should().Be(777);
first.DetectionExeMtimeMs.Should().Be(888);
first.Fingerprint.SizeBytes.Should().Be(10, "the consent fingerprint is the gate's, never the sweep's");
first.Fingerprint.MtimeUnixMs.Should().Be(20);
JsonSerializer.Deserialize<Dictionary<string, string>>(first.FieldProvenanceJson!).Should().BeEquivalentTo(new Dictionary<string, string>(StringComparer.Ordinal)
{
["engine"] = "detected",
["engine_version"] = "detected",
["platform"] = "detected",
});
// The user corrects the engine; the platform stays detected.
(await repo.UpdateMetadataAsync(row.Id, new GameMetadata { Name = "Title", Platform = "steam", Engine = "Unreal Engine", EngineVersion = "2022.3.1" }, Ct)).Should().BeTrue();
// A re-run with a newer answer refreshes what detection owns and leaves the user's correction alone;
// a null engine version erases nothing; an empty capability list clears the flags.
(await repo.ApplyDetectionAsync(row.Id, new DetectionWrite
{
EngineId = "godot",
EngineVersion = null,
PlatformId = "gog",
CapabilityIds = [],
RulesVersion = "2026.10.1",
ExeSizeBytes = 777,
ExeMtimeMs = 888,
}, Ct)).Should().BeTrue();
GameRow second = (await repo.FindByIdAsync(row.Id, Ct))!;
second.Engine.Should().Be("Unreal Engine", "a user field is never overwritten — the rule 05_DETECTION §Caching exists for");
second.EngineVersion.Should().Be("2022.3.1", "null detected = not established = left alone");
second.Platform.Should().Be("gog", "a detected field is refreshed");
second.CapabilityFlagsJson.Should().Be("[]");
second.DetectionRulesVersion.Should().Be("2026.10.1");
JsonSerializer.Deserialize<Dictionary<string, string>>(second.FieldProvenanceJson!)!["engine"].Should().Be("user");
(await repo.ApplyDetectionAsync(row.Id + 99, new DetectionWrite { CapabilityIds = [], RulesVersion = "v", ExeSizeBytes = 0, ExeMtimeMs = 0 }, Ct)).Should().BeFalse();
}
private static async Task<long> AddSessionAsync(LedgerFixture f, long gameId)
{
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "G" }, DateTimeOffset.UnixEpoch, Ct).ConfigureAwait(false);