Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa42d2d155 | ||
|
|
7584259aab |
No files matched your search
@@ -27,6 +27,42 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
_Nothing yet — entries continue here after `0.1.0-beta.6`._
|
||||
|
||||
## [0.1.0-beta.6] - 2026-09-23
|
||||
|
||||
**The sixth pre-release: a game is recorded under its own entry, one entry per game after a drive changes its
|
||||
letter, a game that is not measured is shown while it runs, and RE Engine and FromSoftware games are detected.** The
|
||||
same unsigned installer: verify its hash against `SHA256SUMS.txt`, then *More info → Run anyway*. What changed for a
|
||||
user:
|
||||
|
||||
- **Another game's `Game.exe` is no longer recorded under your entry.** A process that matches an entry by file name
|
||||
only starts nothing — unless it is that entry's own executable on a drive that changed its letter — so an RPG Maker
|
||||
game can no longer be recorded under another RPG Maker game's name, twice, as *HELLO, HELLO WORLD!* was under
|
||||
*Flower in Us*.
|
||||
- **A game that is not measured is shown while it runs.** Hooking off, refused by the guard, or a process Windows
|
||||
would not open: the Dashboard shows the game, the time and the temperatures, says why nothing is measured, and the
|
||||
tray turns to recording-only — until now it said "Nothing is being captured." for as long as the game ran.
|
||||
- **One entry per game when a drive changes its letter.** Two entries for the same executable under two letters
|
||||
merge on their own (the older one stays, with both histories); a game updated while its drive had another letter is
|
||||
followed with hooking off; the library import no longer adds a game again under the new letter.
|
||||
- **A game removed while it runs keeps its session** (under the entry that holds its executable), and a session file
|
||||
left behind can no longer stop the Agent at every start.
|
||||
- **RE Engine and FromSoftware games are detected**, engines are shown by name, and a game added by hand whose
|
||||
executable is `Game.exe` is named after the game.
|
||||
|
||||
**Updating from `0.1.0-beta.5`:**
|
||||
|
||||
- Quit the App (tray icon → Exit) and end `FrameLedger.Agent.exe` before running the installer.
|
||||
- No schema change; the database opens in place. Every game is re-detected once (rules `2026.09.2`).
|
||||
- Session files in `%LOCALAPPDATA%\FrameLedger\tmp` that beta.5 could not store are stored at the Agent's first start —
|
||||
under the entry that holds their executable — or dropped with a line in `agent-*.log`; the Agent keeps running either
|
||||
way.
|
||||
- An entry that a beta.5 file-name match created for another game keeps its wrong name until you rename it (*Edit…*)
|
||||
or remove it; its executable path says which game it is.
|
||||
- A game whose **folder** moved — not only its drive letter — now records nothing until *Change executable* points its
|
||||
entry at the new file.
|
||||
|
||||
### Added
|
||||
|
||||
- **RE Engine and FromSoftware games are detected.** Capcom's RE Engine titles (RESIDENT EVIL 2/3/4/7/Village, Devil
|
||||
@@ -53,6 +89,16 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
|
||||
*Change executable* points its entry at the new file. The "Flower in Us" entry the old match created stays until you
|
||||
rename it (it points at HHW's `swiftshader\Game.exe`, the file to measure HHW by) or remove it.
|
||||
|
||||
- **One entry per game after a drive letter changes — the two side by side become one.** When the owner's USB drive
|
||||
came back as `H:` for a morning, a second entry was made for each game played from it, and once the letter was back
|
||||
neither entry could move onto the other's path: two of each game, and "could not be moved" in the log every 15 s.
|
||||
Now the Agent merges two entries for the same executable (same path on two letters, same size and modification
|
||||
time): the entry made first stays, the other's sessions join it, a block on either is kept, and no consent moves
|
||||
between them — it waits while either game runs. A game whose executable changed on the new letter (it was updated
|
||||
meanwhile) is followed with hooking off, as *Change executable* does; turn hooking on again to measure it. The
|
||||
library import no longer adds a game again when it is already in the library under another drive letter. And a
|
||||
database error during the Agent's 15 s library pass no longer stops the Agent.
|
||||
|
||||
- **A game removed from the library while it runs no longer loses its session — or stops the Agent at the next
|
||||
start.** On 2026-09-22 23:26 and 2026-09-23 00:25 a GIRLS' FRONTLINE 2 session ended `FAULTED` on the database's
|
||||
foreign key: its entry had been removed (and re-imported) while the game ran, and the session was written under the
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
> No telemetry. No accounts. All data stays on your machine.
|
||||
|
||||
<!-- accuracy-block:begin -->
|
||||
> ⚠ **What FrameLedger actually measures today — 2026-09-22.** The software is a beta; its latest
|
||||
> **pre-release is `0.1.0-beta.5`** (2026-09-22), an unsigned installer built from that tag with its
|
||||
> ⚠ **What FrameLedger actually measures today — 2026-09-23.** The software is a beta; its latest
|
||||
> **pre-release is `0.1.0-beta.6`** (2026-09-23), an unsigned installer built from that tag with its
|
||||
> checksums published beside it. The source holds the desktop app
|
||||
> (library, store import, charts, settings) and the background Agent, which records a session when a
|
||||
> game in the library runs, injects only into games you enabled and only past the safety guard, and
|
||||
@@ -22,8 +22,8 @@
|
||||
> NVIDIA Streamline (with Ray Reconstruction Yes/No), and FSR through AMD's shipped FidelityFX DLLs:
|
||||
> named FSR 3 from the older DLLs, and FSR without a version from the newer ones, which host both
|
||||
> FSR 3.1 and FSR 4. FSR 2, and FSR shipped any other way, is not identified. For DLSS titles that
|
||||
> bypass Streamline, the NVIDIA driver's own per-process record is stored with the session, labelled
|
||||
> *driver-reported*; the app does not display it yet. Intel XeSS is **not** read (its SDK licence
|
||||
> bypass Streamline, the NVIDIA driver's own per-process record is stored with the session and shown
|
||||
> as *DLSS (driver-reported)*. Intel XeSS is **not** read (its SDK licence
|
||||
> forbids it), and neither is an upscaler compiled into the game: those read `N/A`, or "Unknown
|
||||
> upscaler" when another vendor's hook ran in the game. Vulkan and OpenGL titles read `N/A`.
|
||||
> - **Quality preset:** not reported on any title measured. The one route this software may use — the
|
||||
@@ -136,7 +136,7 @@ Elevation is **optional — for everything.** Hooked capture is the normal path
|
||||
|
||||
## Install
|
||||
|
||||
> **The latest pre-release is `v0.1.0-beta.5` (2026-09-22); before it `v0.1.0-beta.4` (2026-09-21), `v0.1.0-beta.3` (2026-09-21), `v0.1.0-beta.2` (2026-09-17) and `v0.1.0-beta.1` (2026-09-16).** They are pre-releases: read `CHANGELOG.md`'s section for the one you install — what it measures, what it does not yet, and how to update — before installing. A source build is `docs/12_BUILD.md`.
|
||||
> **The latest pre-release is `v0.1.0-beta.6` (2026-09-23); before it `v0.1.0-beta.5` (2026-09-22), `v0.1.0-beta.4` (2026-09-21), `v0.1.0-beta.3` (2026-09-21), `v0.1.0-beta.2` (2026-09-17) and `v0.1.0-beta.1` (2026-09-16).** They are pre-releases: read `CHANGELOG.md`'s section for the one you install — what it measures, what it does not yet, and how to update — before installing. A source build is `docs/12_BUILD.md`.
|
||||
|
||||
1. Download the latest `FrameLedger.App-win-Setup.exe` from [Releases](https://github.com/poli0981/frameledger/releases). It installs into `%LOCALAPPDATA%\FrameLedger.App`; your data stays in `%LOCALAPPDATA%\FrameLedger`, and uninstalling asks before touching it.
|
||||
2. SmartScreen may warn — releases are not code-signed (free, open-source project). Verify the SHA-256 checksum published with each release, then **More info → Run anyway**.
|
||||
@@ -164,4 +164,4 @@ If you find a game with anti-cheat that FrameLedger fails to detect, please open
|
||||
|
||||
---
|
||||
|
||||
**Status:** pre-release (beta). Five tagged pre-releases so far; see `CHANGELOG.md` for what each one changed and the accuracy block at the top of this file for what is and is not measured. It is not feature-complete, it certainly still has bugs, and `legal/DISCLAIMER.md` §0 says what that means for you.
|
||||
**Status:** pre-release (beta). Six tagged pre-releases so far; see `CHANGELOG.md` for what each one changed and the accuracy block at the top of this file for what is and is not measured. It is not feature-complete, it certainly still has bugs, and `legal/DISCLAIMER.md` §0 says what that means for you.
|
||||
@@ -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`, 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). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. **Maintenance (P4 PR-7) adds no writer:** the retention sweep on demand is the Agent's, asked over the pipe; the UI's `VACUUM` rewrites pages with the same contents and changes no row (§Retention built note). 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). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. **And since 2026-09-23 the Agent's relocator merges two entries for one executable under two drive letters** (`IGameMerge`, HANDOFF D26, `19_SAFETY` §A moved drive is the same executable): in one transaction it re-parents the dropped entry's `sessions` to the survivor (before the delete — `sessions.game_id` cascades), carries a block or a crash auto-disable still in force to the survivor (`hook_enabled` only ever to 0; `hook_blocked_reason` is copied, never originated or cleared), adds the crash counts, deletes the dropped `games` row, and then moves the survivor to the file's path (after the delete — `exe_path` is UNIQUE). It is the one Agent write that deletes a `games` row; it never touches a consent column. **Maintenance (P4 PR-7) adds no writer:** the retention sweep on demand is the Agent's, asked over the pipe; the UI's `VACUUM` rewrites pages with the same contents and changes no row (§Retention built note). 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)
|
||||
|
||||
|
||||
@@ -740,6 +740,27 @@ detection. The conditions are the safety of it:
|
||||
*Change executable* is the other operation and stays what it was: a different binary, so hooking off, consent gone,
|
||||
pre-scan not run — it is the user saying "that file", not "that file moved".
|
||||
|
||||
**Two more answers, 2026-09-23 (owner decisions D26, D27).** Both are downgrades or neutral by construction; neither
|
||||
can move a consent onto a binary it was not given for.
|
||||
|
||||
- **D27 — the file moved and changed.** When the row's file is gone and the only file at its path under another
|
||||
letter has OTHER bytes (the game updated while the drive had another letter), the row follows it through *Change
|
||||
executable*'s write (`ChangeExecutableAsync`): the new size and mtime, hooking off, consent cleared, the pre-scan
|
||||
back to not run, the block kept. The user turns hooking on again for the new binary, through the disclosure, as
|
||||
for any changed executable. Two such files (two drives) is an ambiguity and refuses. The same rule holds for the
|
||||
watcher's adopt, whose session is then Tier 2 until the user does.
|
||||
- **D26 — two entries for one file.** When the move is refused because another entry already holds the target path
|
||||
— a twin made while the letter was different, as the owner's `H:` entries were — and the file there has the bytes
|
||||
the stale entry recorded, the two become one (`IGameMerge`, one transaction): the entry made first stays (its name,
|
||||
notes, consent and history), the other's sessions are re-parented to it, a block either carried is kept (hooking
|
||||
off; nothing clears a block, and a merge must not be how one disappears), a crash auto-disable still in force is
|
||||
kept, the crash counts add, and the dropped row is deleted. **Nothing about consent moves between the rows:** the
|
||||
survivor keeps its own record — which, when it is the entry that moves, is about these same bytes — and the dropped
|
||||
row's goes with it. A merge waits while a session of either entry runs or waits in a `.partial` to be recovered (a
|
||||
session finalized under a deleted entry would be dropped), and it is never done with an entry removed from the
|
||||
library. Other bytes under the twin are not merged: they do not prove the other entry is this game, so the log says
|
||||
so once and the user removes the entry they do not want.
|
||||
|
||||
### A game already enabled can become blocked later
|
||||
|
||||
FR-2.2 disables the toggle for titles that ship anti-cheat, and FR-2.3 refuses at
|
||||
|
||||
+20
-3
@@ -1448,9 +1448,10 @@ executable to another drive-letter root when the file is gone from the row's pat
|
||||
file with the same size and mtime — with consent, block and detection kept (`19_SAFETY` §A moved drive is the same
|
||||
executable). Three callers: the 15 s sweep, the watcher's file-name match, the enable-hooking command. The owner's
|
||||
log of the same morning is the case: 46 rows unreadable on `D:` while the drive sat on `H:`, GF2 and ELDEN RING
|
||||
running from `H:` "BY FILE NAME ONLY". **Not done, on purpose:** re-import does not merge a duplicate row an earlier
|
||||
running from `H:` "BY FILE NAME ONLY". ~~**Not done, on purpose:** re-import does not merge a duplicate row an earlier
|
||||
re-scan created at the new path (`LibraryImporter` still dedupes on path); the relocator refuses to move onto a path
|
||||
another row owns and says so in the log.
|
||||
another row owns and says so in the log.~~ **Done 2026-09-23 (D26/D27, the beta.6 section below):** twins with the
|
||||
same bytes merge, a changed file is followed with hooking off, and the import no longer adds a twin.
|
||||
|
||||
**Trap.** `FakeIdentity` in three test classes answers the same fingerprint for ANY path; a relocation test needs one
|
||||
that answers per path, or the "exactly one candidate" rule reads every root as a match.
|
||||
@@ -1472,7 +1473,7 @@ fact stands.
|
||||
|
||||
## 2026-09-23 — the beta.6 train: a file name is not an identity, one entry per executable, Tier 2 shown live
|
||||
|
||||
*Status is `CHANGELOG.md` `[Unreleased]` until the tag; this is what no other file carries. The owner's list and the
|
||||
*Status is `CHANGELOG.md` `[0.1.0-beta.6]`; this is what no other file carries. The owner's list and the
|
||||
evidence behind each item are in the approved plan the PRs cite; the decisions it took are D25–D28.*
|
||||
|
||||
**Decision (D25, owner: "HELLO, HELLO WORLD! was recorded as Flower in Us, twice").** A file name is not an identity:
|
||||
@@ -1484,7 +1485,23 @@ nothing until *Change executable* — accepted, because the alternative is exact
|
||||
in Us. **D28 (owner, same day):** HHW itself is measured by pointing an entry at `swiftshader\Game.exe` (the NW.js
|
||||
runtime its .NET launcher starts); no launcher-following in beta.6.
|
||||
|
||||
**Decision (D26, owner: "the library still shows two entries side by side after the drive letter changed, with the
|
||||
data unchanged").** The Agent merges two entries for one executable under two drive letters by itself: the stale
|
||||
entry's file is gone, the other entry holds the same path on another letter, and the file there has the bytes the
|
||||
stale entry recorded. The entry made first stays; the other's sessions join it; a block or a crash auto-disable in
|
||||
force is kept; no consent moves between them; it waits while a session of either runs or waits to be recovered
|
||||
(`CaptureOrchestrator.IsRecording`, `IPartialSessionStore.PendingGameIds`). `19_SAFETY` §A moved drive has the rules,
|
||||
`06_DATA_MODEL` the writer. The import no longer adds a twin: a store's executable that is a library entry's path on
|
||||
another letter, with that entry's file gone, is shown "in the library under another drive letter" and skipped.
|
||||
**D27 (owner, same day):** when the only file at the entry's path on another letter has other bytes, the entry follows
|
||||
it with hooking off (`ChangeExecutableAsync`, the *Change executable* write). Other bytes under a twin are NOT merged
|
||||
— the log says once which entry to remove.
|
||||
|
||||
**Traps.**
|
||||
- **`IGameMerge` is a second writer that can delete a `games` row.** Only the relocator calls it; a test that removes
|
||||
rows under a running session must expect the merge to wait (busy), not to race it.
|
||||
- **Python patch scripts: `\"` inside a normal triple-quoted string is an escaped quote**, so `@"C:\"` silently loses
|
||||
its backslash and the replace finds nothing (or worse, writes the wrong text). Use raw strings (`r"""…"""`) for C#.
|
||||
- **`FakeIdentity` in `CaptureOrchestratorTests` answers every path with the same bytes — which is exactly the hazard
|
||||
D25 closed**, so it is the right fake for "identical bytes in another folder are another game" and the wrong one for
|
||||
any test that needs a relocation to succeed (use `ExecutableRelocatorTests.DiskByPath`).
|
||||
|
||||
+4
-4
@@ -11,8 +11,8 @@
|
||||
that changes what FrameLedger.Overlay or the capture host does; date the change.
|
||||
HTML comments are not part of the block.
|
||||
-->
|
||||
> ⚠ **What FrameLedger actually measures today — 2026-09-22.** The software is a beta; its latest
|
||||
> **pre-release is `0.1.0-beta.5`** (2026-09-22), an unsigned installer built from that tag with its
|
||||
> ⚠ **What FrameLedger actually measures today — 2026-09-23.** The software is a beta; its latest
|
||||
> **pre-release is `0.1.0-beta.6`** (2026-09-23), an unsigned installer built from that tag with its
|
||||
> checksums published beside it. The source holds the desktop app
|
||||
> (library, store import, charts, settings) and the background Agent, which records a session when a
|
||||
> game in the library runs, injects only into games you enabled and only past the safety guard, and
|
||||
@@ -28,8 +28,8 @@
|
||||
> NVIDIA Streamline (with Ray Reconstruction Yes/No), and FSR through AMD's shipped FidelityFX DLLs:
|
||||
> named FSR 3 from the older DLLs, and FSR without a version from the newer ones, which host both
|
||||
> FSR 3.1 and FSR 4. FSR 2, and FSR shipped any other way, is not identified. For DLSS titles that
|
||||
> bypass Streamline, the NVIDIA driver's own per-process record is stored with the session, labelled
|
||||
> *driver-reported*; the app does not display it yet. Intel XeSS is **not** read (its SDK licence
|
||||
> bypass Streamline, the NVIDIA driver's own per-process record is stored with the session and shown
|
||||
> as *DLSS (driver-reported)*. Intel XeSS is **not** read (its SDK licence
|
||||
> forbids it), and neither is an upscaler compiled into the game: those read `N/A`, or "Unknown
|
||||
> upscaler" when another vendor's hook ran in the game. Vulkan and OpenGL titles read `N/A`.
|
||||
> - **Quality preset:** not reported on any title measured. The one route this software may use — the
|
||||
|
||||
+4
-4
@@ -97,8 +97,8 @@ Software running inside another process can, in principle, destabilize it. Frame
|
||||
Frame timing is derived from high-resolution timestamps taken at the moment the game presents each frame; upscaling, frame-generation and ray-tracing state are read from the parameters the game passes to those APIs. This is substantially more accurate than inferring settings from files on disk, but **no measurement is guaranteed to be exact**:
|
||||
|
||||
<!-- accuracy-block:begin -->
|
||||
> ⚠ **What FrameLedger actually measures today — 2026-09-22.** The software is a beta; its latest
|
||||
> **pre-release is `0.1.0-beta.5`** (2026-09-22), an unsigned installer built from that tag with its
|
||||
> ⚠ **What FrameLedger actually measures today — 2026-09-23.** The software is a beta; its latest
|
||||
> **pre-release is `0.1.0-beta.6`** (2026-09-23), an unsigned installer built from that tag with its
|
||||
> checksums published beside it. The source holds the desktop app
|
||||
> (library, store import, charts, settings) and the background Agent, which records a session when a
|
||||
> game in the library runs, injects only into games you enabled and only past the safety guard, and
|
||||
@@ -114,8 +114,8 @@ Frame timing is derived from high-resolution timestamps taken at the moment the
|
||||
> NVIDIA Streamline (with Ray Reconstruction Yes/No), and FSR through AMD's shipped FidelityFX DLLs:
|
||||
> named FSR 3 from the older DLLs, and FSR without a version from the newer ones, which host both
|
||||
> FSR 3.1 and FSR 4. FSR 2, and FSR shipped any other way, is not identified. For DLSS titles that
|
||||
> bypass Streamline, the NVIDIA driver's own per-process record is stored with the session, labelled
|
||||
> *driver-reported*; the app does not display it yet. Intel XeSS is **not** read (its SDK licence
|
||||
> bypass Streamline, the NVIDIA driver's own per-process record is stored with the session and shown
|
||||
> as *DLSS (driver-reported)*. Intel XeSS is **not** read (its SDK licence
|
||||
> forbids it), and neither is an upscaler compiled into the game: those read `N/A`, or "Unknown
|
||||
> upscaler" when another vendor's hook ran in the game. Vulkan and OpenGL titles read `N/A`.
|
||||
> - **Quality preset:** not reported on any title measured. The one route this software may use — the
|
||||
|
||||
@@ -121,12 +121,18 @@ internal static class AgentServices
|
||||
services.AddSingleton<IDetectionRulesSource>(static _ => new DetectionRulesFile());
|
||||
services.AddSingleton<IGameFileProbe, GameFileProbe>();
|
||||
// A drive that changed its letter (2026-09-22): one relocator, asked by the sweep, the watcher and the enable-hooking
|
||||
// command, over the BCL's drive list.
|
||||
// command, over the BCL's drive list. Since 2026-09-23 it also merges two entries for one executable (D26), and waits
|
||||
// while a session of either runs — the orchestrator's table, read when asked (it holds the relocator itself) — or
|
||||
// waits in a .partial to be recovered.
|
||||
services.AddSingleton<IGameMerge>(static sp => new SqliteGameMerge(sp.GetRequiredService<LedgerDatabase>()));
|
||||
services.AddSingleton(static sp => new ExecutableRelocator(
|
||||
sp.GetRequiredService<IGameRepository>(),
|
||||
sp.GetRequiredService<IExecutableIdentitySource>(),
|
||||
VolumeRoots.Ready,
|
||||
static line => Serilog.Log.Information("{Line}", line)));
|
||||
static line => Serilog.Log.Information("{Line}", line),
|
||||
merge: sp.GetRequiredService<IGameMerge>(),
|
||||
busy: id => sp.GetRequiredService<CaptureOrchestrator>().IsRecording(id)
|
||||
|| sp.GetRequiredService<IPartialSessionStore>().PendingGameIds().Contains(id)));
|
||||
services.AddSingleton(static sp => new DetectionSweep(
|
||||
sp.GetRequiredService<IGameRepository>(),
|
||||
sp.GetRequiredService<IDetectionRulesSource>(),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Data.Common;
|
||||
using FrameLedger.Application.Detection;
|
||||
using FrameLedger.Application.Vulkan;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
@@ -15,7 +16,9 @@ namespace FrameLedger.Agent.Hosting;
|
||||
/// 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.
|
||||
/// directory going away mid-walk is ordinary, and one bad game must not stop the scan of the rest. A database error
|
||||
/// is one of those since 2026-09-23: the sweep writes rows (a relocation, a merge), a service that throws stops the
|
||||
/// Agent's host (the Generic Host's default), and a busy or locked ledger is a retry, not a reason to stop capturing.
|
||||
/// </remarks>
|
||||
internal sealed class DetectionHostedService(DetectionSweep sweep, VkLayerReconciler layer) : BackgroundService
|
||||
{
|
||||
@@ -49,7 +52,7 @@ internal sealed class DetectionHostedService(DetectionSweep sweep, VkLayerReconc
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or DbException)
|
||||
{
|
||||
Log.Warning(ex, "detect: sweep did not complete; retrying on the next tick");
|
||||
}
|
||||
|
||||
Generated
+3
@@ -299,6 +299,7 @@ public static class Strings
|
||||
nameof(Import_Intro),
|
||||
nameof(Import_Note_Already),
|
||||
nameof(Import_Note_Guessed),
|
||||
nameof(Import_Note_Moved),
|
||||
nameof(Import_Note_NoExe),
|
||||
nameof(Import_NothingFound),
|
||||
nameof(Import_SelectAll),
|
||||
@@ -1182,6 +1183,8 @@ public static class Strings
|
||||
|
||||
public static string Import_Note_Guessed => ResourceManager.GetString(nameof(Import_Note_Guessed), Culture) ?? nameof(Import_Note_Guessed);
|
||||
|
||||
public static string Import_Note_Moved => ResourceManager.GetString(nameof(Import_Note_Moved), Culture) ?? nameof(Import_Note_Moved);
|
||||
|
||||
public static string Import_Note_NoExe => ResourceManager.GetString(nameof(Import_Note_NoExe), Culture) ?? nameof(Import_Note_NoExe);
|
||||
|
||||
public static string Import_NothingFound => ResourceManager.GetString(nameof(Import_NothingFound), Culture) ?? nameof(Import_NothingFound);
|
||||
|
||||
@@ -261,6 +261,10 @@
|
||||
<value>推定 — 確認してください</value>
|
||||
<comment>review</comment>
|
||||
</data>
|
||||
<data name="Import_Note_Moved" xml:space="preserve">
|
||||
<value>別のドライブ文字でライブラリに登録済み — そのエントリがこのファイルに追従します</value>
|
||||
<comment>review</comment>
|
||||
</data>
|
||||
<data name="Import_Selected_Format" xml:space="preserve">
|
||||
<value>{1} 件中 {0} 件を選択</value>
|
||||
<comment>review</comment>
|
||||
|
||||
@@ -201,6 +201,9 @@
|
||||
<data name="Import_Note_Guessed" xml:space="preserve">
|
||||
<value>Guessed — check it</value>
|
||||
</data>
|
||||
<data name="Import_Note_Moved" xml:space="preserve">
|
||||
<value>In the library under another drive letter — that entry follows this file</value>
|
||||
</data>
|
||||
<data name="Import_Selected_Format" xml:space="preserve">
|
||||
<value>{0} of {1} selected</value>
|
||||
</data>
|
||||
|
||||
@@ -196,6 +196,9 @@
|
||||
<data name="Import_Note_Guessed" xml:space="preserve">
|
||||
<value>Đoán — hãy kiểm tra</value>
|
||||
</data>
|
||||
<data name="Import_Note_Moved" xml:space="preserve">
|
||||
<value>Đã có trong thư viện dưới ký tự ổ đĩa khác — mục đó sẽ đi theo tệp này</value>
|
||||
</data>
|
||||
<data name="Import_Selected_Format" xml:space="preserve">
|
||||
<value>Đã chọn {0}/{1}</value>
|
||||
</data>
|
||||
|
||||
@@ -15,6 +15,7 @@ public sealed partial class ImportCandidateViewModel : ObservableObject
|
||||
Candidate = candidate ?? throw new ArgumentNullException(nameof(candidate));
|
||||
_isSelected = candidate.CanImport;
|
||||
Note = candidate.AlreadyInLibrary ? Strings.Import_Note_Already
|
||||
: candidate.MovedFrom is not null ? Strings.Import_Note_Moved
|
||||
: candidate.ExePath is null || candidate.ExecutableMissing ? Strings.Import_Note_NoExe
|
||||
: candidate.ExecutableGuessed ? Strings.Import_Note_Guessed
|
||||
: string.Empty;
|
||||
@@ -30,6 +31,6 @@ public sealed partial class ImportCandidateViewModel : ObservableObject
|
||||
|
||||
public string ExeText => Candidate.ExePath ?? Strings.Common_Dash;
|
||||
|
||||
/// <summary>Already in the library, no executable found, or a guessed executable the user should check.</summary>
|
||||
/// <summary>Already in the library (under this drive letter or, since 2026-09-23, another), no executable found, or a guessed executable the user should check.</summary>
|
||||
public string Note { get; }
|
||||
}
|
||||
@@ -101,12 +101,19 @@ public sealed class DetectionSweep : IDisposable
|
||||
foreach (GameRow listed in await _games.ListAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
(GameRow game, ExecutableFingerprint? read, bool moved) = await ReadOrRelocateAsync(listed, ct).ConfigureAwait(false);
|
||||
(GameRow game, ExecutableFingerprint? read, bool moved, bool gone) = await ReadOrRelocateAsync(listed, ct).ConfigureAwait(false);
|
||||
if (moved)
|
||||
{
|
||||
relocated++;
|
||||
}
|
||||
|
||||
if (gone)
|
||||
{
|
||||
// Merged into its twin this pass (2026-09-23): not an entry any more, so not an unreadable one.
|
||||
_unreadableSaid.Remove(game.Id);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (read is not { } onDisk)
|
||||
{
|
||||
unreadable++;
|
||||
@@ -169,17 +176,24 @@ public sealed class DetectionSweep : IDisposable
|
||||
/// <summary>
|
||||
/// The row's executable as read from disk — and, when it is missing, one more question before the row is skipped
|
||||
/// (2026-09-22): is the same file under another drive letter? When it is, the row follows it and this very pass
|
||||
/// scans it there.
|
||||
/// scans it there. Since 2026-09-23 the relocator can also merge the row into the entry that already holds that
|
||||
/// file; the row is then gone, which this says rather than calling it unreadable.
|
||||
/// </summary>
|
||||
private async ValueTask<(GameRow Game, ExecutableFingerprint? Read, bool Moved)> ReadOrRelocateAsync(GameRow game, CancellationToken ct)
|
||||
private async ValueTask<(GameRow Game, ExecutableFingerprint? Read, bool Moved, bool Gone)> ReadOrRelocateAsync(GameRow game, CancellationToken ct)
|
||||
{
|
||||
ExecutableFingerprint? read = _identity.Read(game.Fingerprint.ExePath);
|
||||
if (read is not null || _relocator is null || await _relocator.TryRelocateAsync(game, ct).ConfigureAwait(false) is not { } moved)
|
||||
if (read is not null || _relocator is null)
|
||||
{
|
||||
return (game, read, false);
|
||||
return (game, read, false, false);
|
||||
}
|
||||
|
||||
return (game with { Fingerprint = moved }, _identity.Read(moved.ExePath), true);
|
||||
if (await _relocator.TryRelocateAsync(game, ct).ConfigureAwait(false) is { } moved)
|
||||
{
|
||||
return (game with { Fingerprint = moved }, _identity.Read(moved.ExePath), true, false);
|
||||
}
|
||||
|
||||
bool gone = await _games.FindByIdAsync(game.Id, ct).ConfigureAwait(false) is null;
|
||||
return (game, null, gone, gone);
|
||||
}
|
||||
|
||||
/// <summary><c>DetectionCacheKey</c> compared field by field against the row: any difference is a re-run.</summary>
|
||||
|
||||
@@ -5,8 +5,14 @@ namespace FrameLedger.Application.Import;
|
||||
/// own when it names one, else the locator's guess — whether the ledger already has it, and whether the file is
|
||||
/// there to be read at all. A candidate with no executable cannot be imported and the list says so.
|
||||
/// </summary>
|
||||
public sealed record ImportCandidate(StoreGame Game, string? ExePath, bool AlreadyInLibrary, bool ExecutableGuessed, bool ExecutableMissing = false)
|
||||
/// <remarks>
|
||||
/// <see cref="MovedFrom"/> (2026-09-23) is the path of the library entry this executable already is, on a drive whose
|
||||
/// letter changed: that entry follows the file (the Agent's relocator), so importing it again would make the second,
|
||||
/// side-by-side entry the owner's library showed for every game on the re-lettered drive.
|
||||
/// </remarks>
|
||||
public sealed record ImportCandidate(StoreGame Game, string? ExePath, bool AlreadyInLibrary, bool ExecutableGuessed, bool ExecutableMissing = false,
|
||||
string? MovedFrom = null)
|
||||
{
|
||||
/// <summary>An executable is known, it is on disk, and the ledger does not have it yet.</summary>
|
||||
public bool CanImport => ExePath is not null && !ExecutableMissing && !AlreadyInLibrary;
|
||||
/// <summary>An executable is known, it is on disk, and the ledger does not have it yet — under this letter or another.</summary>
|
||||
public bool CanImport => ExePath is not null && !ExecutableMissing && !AlreadyInLibrary && MovedFrom is null;
|
||||
}
|
||||
@@ -36,6 +36,7 @@ public sealed class LibraryImporter
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
List<ImportCandidate> candidates = [];
|
||||
IReadOnlyList<GameRow> library = await _games.ListAsync(ct).ConfigureAwait(false);
|
||||
foreach (IStoreLibrarySource source in _sources)
|
||||
{
|
||||
IReadOnlyList<StoreGame> games;
|
||||
@@ -67,7 +68,8 @@ public sealed class LibraryImporter
|
||||
// rather than the import failing later.
|
||||
bool missing = exe is not null && _identity.Read(exe) is null;
|
||||
bool already = exe is not null && await _games.FindAsync(exe, ct).ConfigureAwait(false) is { InLibrary: true };
|
||||
candidates.Add(new ImportCandidate(game, exe, already, guessed, missing));
|
||||
string? movedFrom = exe is null || already ? null : StaleTwinOf(exe, library)?.Fingerprint.ExePath;
|
||||
candidates.Add(new ImportCandidate(game, exe, already, guessed, missing, movedFrom));
|
||||
}
|
||||
|
||||
_log($"import: {source.Platform} — {games.Count} title(s)");
|
||||
@@ -82,6 +84,7 @@ public sealed class LibraryImporter
|
||||
ArgumentNullException.ThrowIfNull(selected);
|
||||
int added = 0;
|
||||
int skipped = 0;
|
||||
IReadOnlyList<GameRow> library = await _games.ListAsync(ct).ConfigureAwait(false);
|
||||
foreach (ImportCandidate c in selected)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
@@ -93,6 +96,13 @@ public sealed class LibraryImporter
|
||||
}
|
||||
|
||||
GameRow? before = await _games.FindAsync(c.ExePath, ct).ConfigureAwait(false);
|
||||
if (before is null && StaleTwinOf(c.ExePath, library) is { } twin)
|
||||
{
|
||||
skipped++;
|
||||
_log($"import: {c.Game.Name} not added — it is the library's '{twin.Name}' ({twin.Fingerprint.ExePath}) on a drive whose letter changed; that entry follows it");
|
||||
continue;
|
||||
}
|
||||
|
||||
GameRow row = await _games.EnsureAsync(fingerprint, c.Game.Name, ct).ConfigureAwait(false);
|
||||
_ = await _games.ApplyStoreMetadataAsync(row.Id, new StoreMetadata { Platform = c.Game.Platform, StoreId = c.Game.StoreId, GameVersion = c.Game.Version }, ct).ConfigureAwait(false);
|
||||
if (before is { InLibrary: true })
|
||||
@@ -108,4 +118,13 @@ public sealed class LibraryImporter
|
||||
|
||||
return new ImportReport(added, skipped);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The library entry <paramref name="exe"/> already is on a drive that changed its letter (2026-09-23): its path with
|
||||
/// only the letter different, and its own file gone — the relocator's rule (<see cref="ExecutableRelocator.IsDriveLetterTwin"/>).
|
||||
/// The Agent's sweep moves that entry within one interval; a new entry beside it is how the owner's library came to
|
||||
/// show two of every game on the re-lettered drive.
|
||||
/// </summary>
|
||||
private GameRow? StaleTwinOf(string exe, IReadOnlyList<GameRow> library) =>
|
||||
library.FirstOrDefault(r => ExecutableRelocator.IsDriveLetterTwin(r.Fingerprint.ExePath, exe) && _identity.Read(r.Fingerprint.ExePath) is null);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using FrameLedger.Domain.Consent;
|
||||
|
||||
namespace FrameLedger.Application.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Two library entries for one executable under two drive letters, and which one stays (2026-09-23, HANDOFF D26). The
|
||||
/// owner's library showed <c>H:</c> twins beside their <c>D:</c> entries for a day: a drive that changed its letter made
|
||||
/// a second entry for the same file, and once the letter changed back neither could move onto the other's path.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>The entry made first stays</b> (a tie keeps the lower id): its name, notes, consent and history are the user's
|
||||
/// oldest, and the other entry's sessions join it. Nothing about consent moves from the dropped entry to the survivor —
|
||||
/// a merge can only ever carry a block or an auto-disable, which turn hooking off.
|
||||
/// </remarks>
|
||||
public sealed record GameMergePlan
|
||||
{
|
||||
public required long SurvivorId { get; init; }
|
||||
|
||||
/// <summary>Where the survivor's row says its executable is, as the plan saw it.</summary>
|
||||
public required string SurvivorPath { get; init; }
|
||||
|
||||
public required long DroppedId { get; init; }
|
||||
|
||||
/// <summary>Where the dropped row says its executable is, as the plan saw it.</summary>
|
||||
public required string DroppedPath { get; init; }
|
||||
|
||||
/// <summary>The one file both entries name: where the survivor lives after the merge, with the bytes it was found with.</summary>
|
||||
public required ExecutableFingerprint Target { get; init; }
|
||||
|
||||
/// <summary>The survivor is the entry whose file is gone, so it takes the target's path once the other row is deleted.</summary>
|
||||
public bool SurvivorMoves => !string.Equals(SurvivorPath, Target.ExePath, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The plan for <paramref name="stale"/> — the entry whose file is gone — and <paramref name="owner"/>, the entry at
|
||||
/// <paramref name="target"/>'s path.
|
||||
/// </summary>
|
||||
public static GameMergePlan For(GameRow stale, GameRow owner, ExecutableFingerprint target)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(stale);
|
||||
ArgumentNullException.ThrowIfNull(owner);
|
||||
if (stale.Id == owner.Id)
|
||||
{
|
||||
throw new ArgumentException("an entry is not its own twin", nameof(owner));
|
||||
}
|
||||
|
||||
if (!string.Equals(owner.Fingerprint.ExePath, target.ExePath, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new ArgumentException("the owner is the entry at the target's path", nameof(owner));
|
||||
}
|
||||
|
||||
bool staleStays = stale.AddedAt < owner.AddedAt || (stale.AddedAt == owner.AddedAt && stale.Id < owner.Id);
|
||||
GameRow keep = staleStays ? stale : owner;
|
||||
GameRow drop = staleStays ? owner : stale;
|
||||
return new GameMergePlan
|
||||
{
|
||||
SurvivorId = keep.Id,
|
||||
SurvivorPath = keep.Fingerprint.ExePath,
|
||||
DroppedId = drop.Id,
|
||||
DroppedPath = drop.Fingerprint.ExePath,
|
||||
Target = target,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace FrameLedger.Application.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// The one write that folds two library entries into one (2026-09-23, HANDOFF D26). The Agent's — its relocator is the
|
||||
/// only caller — because it moves sessions, which are the Agent's rows (<c>06_DATA_MODEL</c> §Writer ownership).
|
||||
/// </summary>
|
||||
public interface IGameMerge
|
||||
{
|
||||
/// <summary>
|
||||
/// Folds <see cref="GameMergePlan.DroppedId"/> into <see cref="GameMergePlan.SurvivorId"/> in one transaction: the
|
||||
/// dropped entry's sessions re-parented, any block or auto-disable it carried kept (hooking off), its crash count
|
||||
/// added, the row deleted, and the survivor at the target path. Null — nothing written — when either row is not what
|
||||
/// the plan saw: gone, removed from the library, at another path, or (for a survivor that moves) no longer holding the
|
||||
/// target's bytes. Otherwise the number of sessions that moved.
|
||||
/// </summary>
|
||||
ValueTask<int?> MergeAsync(GameMergePlan plan, CancellationToken ct = default);
|
||||
}
|
||||
@@ -20,6 +20,13 @@ public interface IPartialSessionStore
|
||||
/// <summary>Removes the file; a missing file is not an error.</summary>
|
||||
void Delete(Guid sessionGuid);
|
||||
|
||||
/// <summary>
|
||||
/// The entries every pending file's header names (2026-09-23) — the sessions still running and those waiting to be
|
||||
/// recovered. What a merge of two entries waits for: a session re-keyed under a deleted entry would be dropped. Read
|
||||
/// beside a running session's writer; a file whose header cannot be read names nothing.
|
||||
/// </summary>
|
||||
IReadOnlySet<long> PendingGameIds();
|
||||
|
||||
/// <summary>
|
||||
/// Sets the file aside as <c><guid>.partial.failed</c> (2026-09-23): out of <see cref="ListPending"/>, never
|
||||
/// retried, kept for a bug report. What recovery does with a file it could not finalize, so that one bad file cannot
|
||||
|
||||
@@ -25,6 +25,15 @@ namespace FrameLedger.Application.Watch;
|
||||
/// (<see cref="IsDriveLetterTwin"/>), and exactly one such file with the row's bytes.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Two more answers since the same day (HANDOFF D26, D27).</b> When the only file at the row's path under another
|
||||
/// letter has OTHER bytes — the game was updated while the drive had another letter — the row follows it the way
|
||||
/// <i>Change executable</i> does: hooking off, consent cleared, the block kept (D27). And when the file the row
|
||||
/// would move to already has an entry of its own — a twin made while the letter was different — and it is the same
|
||||
/// bytes the row recorded, the two entries become one (<see cref="IGameMerge"/>, D26): the entry made first stays,
|
||||
/// the other's sessions join it, a block or auto-disable either carried is kept, and no consent moves between them.
|
||||
/// A merge waits while a session of either entry runs or waits to be recovered (<c>busy</c>).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Three callers, one rule.</b> The 15 s sweep (a missing executable), the watcher (a process running from a path
|
||||
/// that is not the row's while the row's is gone) and the enable-hooking command (the same, when the user clicks). No
|
||||
/// caller opens a process; this reads files. A refusal is logged once per row until it changes — the owner's log
|
||||
@@ -38,6 +47,8 @@ public sealed class ExecutableRelocator
|
||||
private readonly Func<IReadOnlyList<string>> _roots;
|
||||
private readonly Action<string> _log;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly IGameMerge? _merge;
|
||||
private readonly Func<long, bool> _busy;
|
||||
private readonly Lock _logged = new();
|
||||
private readonly Dictionary<long, string> _lastLine = [];
|
||||
|
||||
@@ -47,13 +58,18 @@ public sealed class ExecutableRelocator
|
||||
/// <param name="roots">The mounted volumes' roots (<c>C:\</c>, <c>H:\</c>, …); an adapter's, so a test can name its own.</param>
|
||||
/// <param name="log">The Agent's log line.</param>
|
||||
/// <param name="clock">The row's <c>updated_at</c>.</param>
|
||||
public ExecutableRelocator(IGameRepository games, IExecutableIdentitySource identity, Func<IReadOnlyList<string>> roots, Action<string> log, TimeProvider? clock = null)
|
||||
/// <param name="merge">Folds a twin entry into its other half (D26); null never merges.</param>
|
||||
/// <param name="busy">Whether a session of the entry runs or waits to be recovered; a merge waits for it. Null is never busy.</param>
|
||||
public ExecutableRelocator(IGameRepository games, IExecutableIdentitySource identity, Func<IReadOnlyList<string>> roots, Action<string> log, TimeProvider? clock = null,
|
||||
IGameMerge? merge = null, Func<long, bool>? busy = null)
|
||||
{
|
||||
_games = games ?? throw new ArgumentNullException(nameof(games));
|
||||
_identity = identity ?? throw new ArgumentNullException(nameof(identity));
|
||||
_roots = roots ?? throw new ArgumentNullException(nameof(roots));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
_merge = merge;
|
||||
_busy = busy ?? (static _ => false);
|
||||
}
|
||||
|
||||
/// <summary>The same path under each other drive-letter root; empty for a path that is not a drive-letter path (UNC).</summary>
|
||||
@@ -96,8 +112,10 @@ public sealed class ExecutableRelocator
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The row's executable is gone from its path: find it under another root and move the row. Null when the file is
|
||||
/// still where the row says, when no other root has it, or when more than one does.
|
||||
/// The row's executable is gone from its path: find it under another root and move the row — or follow it with
|
||||
/// hooking off when its bytes changed (D27), or merge the row into the entry that already holds that path (D26).
|
||||
/// The row's executable as it now is, when the row still exists and moved; null when the file is still where the row
|
||||
/// says, when no other root has it, when more than one does, and when the row was merged into the other entry.
|
||||
/// </summary>
|
||||
public async ValueTask<ExecutableFingerprint?> TryRelocateAsync(GameRow row, CancellationToken ct = default)
|
||||
{
|
||||
@@ -108,21 +126,28 @@ public sealed class ExecutableRelocator
|
||||
return null;
|
||||
}
|
||||
|
||||
List<ExecutableFingerprint> found = SameBytesUnder(row, Candidates(row.Fingerprint.ExePath, _roots()), ct);
|
||||
if (found.Count > 1)
|
||||
List<ExecutableFingerprint> onDisk = Existing(Candidates(row.Fingerprint.ExePath, _roots()), ct);
|
||||
List<ExecutableFingerprint> same = [.. onDisk.Where(f => SameBytes(row.Fingerprint, f))];
|
||||
if (same.Count == 1)
|
||||
{
|
||||
LogOnce(row.Id, $"relocate: {row.Name} — {found.Count} drives hold {row.Fingerprint.ExePath[2..]} with the same size and mtime; not guessing which");
|
||||
return await MoveAsync(row, same[0], ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (same.Count > 1 || onDisk.Count > 1)
|
||||
{
|
||||
LogAmbiguous(row, onDisk.Count, sameBytes: same.Count > 1);
|
||||
return null;
|
||||
}
|
||||
|
||||
return found.Count == 1 ? await MoveAsync(row, found[0], ct).ConfigureAwait(false) : null;
|
||||
return onDisk.Count == 1 ? await FollowChangedAsync(row, onDisk[0], ct).ConfigureAwait(false) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The watcher saw the game run from <paramref name="observedPath"/>, not the row's path (a file-name match). When the
|
||||
/// row's file is gone, the running one is the row's path with only its drive letter changed, and it is the only file
|
||||
/// there with the row's size and mtime, it is the row's executable on a drive that changed its letter: move the row, so
|
||||
/// the session is the row's and its consent applies. False otherwise — including when both files exist, which is two
|
||||
/// row's file is gone and the running one is the row's path with only its drive letter changed, it is the row's
|
||||
/// executable on a drive that changed its letter: the row moves to it — with everything kept when it is the only file
|
||||
/// there with the row's size and mtime, or with hooking off when it is the only file there at all and its bytes
|
||||
/// changed (D27) — so the session is the row's. False otherwise — including when both files exist, which is two
|
||||
/// copies, not a move, and when the running file is in another folder, which is another game (2026-09-23).
|
||||
/// </summary>
|
||||
public async ValueTask<bool> TryAdoptAsync(GameRow row, string observedPath, CancellationToken ct = default)
|
||||
@@ -131,22 +156,33 @@ public sealed class ExecutableRelocator
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(observedPath);
|
||||
if (!IsDriveLetterTwin(row.Fingerprint.ExePath, observedPath)
|
||||
|| _identity.Read(row.Fingerprint.ExePath) is not null
|
||||
|| _identity.Read(observedPath) is not { } onDisk
|
||||
|| !SameBytes(row.Fingerprint, onDisk))
|
||||
|| _identity.Read(observedPath) is not { } running)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// The running file's own drive is mounted by definition; the rest of the list may not know it yet.
|
||||
List<string> roots = [.. _roots(), observedPath[..3]];
|
||||
List<ExecutableFingerprint> found = SameBytesUnder(row, Candidates(row.Fingerprint.ExePath, roots), ct);
|
||||
if (found.Count != 1)
|
||||
List<ExecutableFingerprint> onDisk = Existing(Candidates(row.Fingerprint.ExePath, roots), ct);
|
||||
int same = onDisk.Count(f => SameBytes(row.Fingerprint, f));
|
||||
if (SameBytes(row.Fingerprint, running))
|
||||
{
|
||||
LogOnce(row.Id, $"relocate: {row.Name} — {found.Count} drives hold {row.Fingerprint.ExePath[2..]} with the same size and mtime; not guessing which");
|
||||
if (same != 1)
|
||||
{
|
||||
LogAmbiguous(row, onDisk.Count, sameBytes: true);
|
||||
return false;
|
||||
}
|
||||
|
||||
return await MoveAsync(row, running, ct).ConfigureAwait(false) is not null;
|
||||
}
|
||||
|
||||
if (same > 0 || onDisk.Count != 1)
|
||||
{
|
||||
LogAmbiguous(row, onDisk.Count, sameBytes: same > 1);
|
||||
return false;
|
||||
}
|
||||
|
||||
return await MoveAsync(row, onDisk, ct).ConfigureAwait(false) is not null;
|
||||
return await FollowChangedAsync(row, running, ct).ConfigureAwait(false) is not null;
|
||||
}
|
||||
|
||||
private static bool IsDriveLetterPath(string path) =>
|
||||
@@ -155,13 +191,13 @@ public sealed class ExecutableRelocator
|
||||
private static bool SameBytes(ExecutableFingerprint stored, ExecutableFingerprint onDisk) =>
|
||||
stored.SizeBytes == onDisk.SizeBytes && stored.MtimeUnixMs == onDisk.MtimeUnixMs;
|
||||
|
||||
private List<ExecutableFingerprint> SameBytesUnder(GameRow row, IReadOnlyList<string> candidates, CancellationToken ct)
|
||||
private List<ExecutableFingerprint> Existing(IReadOnlyList<string> candidates, CancellationToken ct)
|
||||
{
|
||||
List<ExecutableFingerprint> found = [];
|
||||
foreach (string candidate in candidates)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (_identity.Read(_identity.Normalise(candidate)) is { } onDisk && SameBytes(row.Fingerprint, onDisk))
|
||||
if (_identity.Read(_identity.Normalise(candidate)) is { } onDisk)
|
||||
{
|
||||
found.Add(onDisk);
|
||||
}
|
||||
@@ -170,6 +206,9 @@ public sealed class ExecutableRelocator
|
||||
return found;
|
||||
}
|
||||
|
||||
private void LogAmbiguous(GameRow row, int drives, bool sameBytes) =>
|
||||
LogOnce(row.Id, $"relocate: {row.Name} — {drives} drives hold {row.Fingerprint.ExePath[2..]}{(sameBytes ? " with the same size and mtime" : string.Empty)}; not guessing which");
|
||||
|
||||
private async ValueTask<ExecutableFingerprint?> MoveAsync(GameRow row, ExecutableFingerprint moved, CancellationToken ct)
|
||||
{
|
||||
bool done = await _games.RelocateExecutableAsync(row.Id, moved, _clock.GetUtcNow(), ct).ConfigureAwait(false);
|
||||
@@ -180,10 +219,71 @@ public sealed class ExecutableRelocator
|
||||
return moved;
|
||||
}
|
||||
|
||||
// Refused: another row owns that path, or this one changed underneath. The first, when that row is in the library,
|
||||
// is a twin made while the letter was different (D26).
|
||||
if (_merge is not null && await _games.FindAsync(moved.ExePath, ct).ConfigureAwait(false) is { InLibrary: true } owner && owner.Id != row.Id)
|
||||
{
|
||||
return await MergeAsync(row, owner, moved, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
LogOnce(row.Id, $"relocate: {row.Name} — {moved.ExePath} has the row's size and mtime but the row could not be moved (another row owns that path, or the row changed underneath)");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// D27 (owner, 2026-09-23): the row's file is gone and the only file at its path under another letter has other bytes
|
||||
/// — the game was updated while the drive had another letter. The row follows it as <i>Change executable</i> does
|
||||
/// (<see cref="IGameRepository.ChangeExecutableAsync"/>): hooking off, consent cleared, the block kept — a downgrade by
|
||||
/// construction, never a grant.
|
||||
/// </summary>
|
||||
private async ValueTask<ExecutableFingerprint?> FollowChangedAsync(GameRow row, ExecutableFingerprint changed, CancellationToken ct)
|
||||
{
|
||||
if (await _games.ChangeExecutableAsync(row.Id, changed, _clock.GetUtcNow(), ct).ConfigureAwait(false))
|
||||
{
|
||||
Forget(row.Id);
|
||||
_log($"relocate: {row.Name} — executable moved {row.Fingerprint.ExePath} → {changed.ExePath} and changed since the entry recorded it "
|
||||
+ "(other size or mtime); the entry follows it with hooking OFF, consent cleared, any block kept — turn hooking on again to measure it");
|
||||
return changed;
|
||||
}
|
||||
|
||||
// Not merged: other bytes are not proof that the entry holding that path is this one's game (D26 merges the same bytes only).
|
||||
LogOnce(row.Id, await _games.FindAsync(changed.ExePath, ct).ConfigureAwait(false) is { } owner && owner.Id != row.Id
|
||||
? $"relocate: {row.Name} — its executable is now {changed.ExePath}, which the entry '{owner.Name}' already holds, and the file there is not "
|
||||
+ "the one this entry recorded, so the two are not merged; remove the entry you do not want"
|
||||
: $"relocate: {row.Name} — {changed.ExePath} could not be followed (the row changed underneath)");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// D26 (owner, 2026-09-23): <paramref name="stale"/>'s file is gone and <paramref name="owner"/> is the entry at the
|
||||
/// same file under another letter, with the bytes <paramref name="stale"/> recorded: one executable, two entries. They
|
||||
/// become one unless a session of either is running or waiting to be recovered.
|
||||
/// </summary>
|
||||
private async ValueTask<ExecutableFingerprint?> MergeAsync(GameRow stale, GameRow owner, ExecutableFingerprint target, CancellationToken ct)
|
||||
{
|
||||
if (_busy(stale.Id) || _busy(owner.Id))
|
||||
{
|
||||
LogOnce(stale.Id, $"relocate: {stale.Name} and {owner.Name} are one executable ({target.ExePath}) under two drive letters; "
|
||||
+ "they are merged once no session of either is running or waiting to be recovered");
|
||||
return null;
|
||||
}
|
||||
|
||||
GameMergePlan plan = GameMergePlan.For(stale, owner, target);
|
||||
if (await _merge!.MergeAsync(plan, ct).ConfigureAwait(false) is not { } sessions)
|
||||
{
|
||||
LogOnce(stale.Id, $"relocate: {stale.Name} — not merged with {owner.Name} (one of the two entries changed underneath); the next pass looks again");
|
||||
return null;
|
||||
}
|
||||
|
||||
Forget(stale.Id);
|
||||
Forget(owner.Id);
|
||||
(GameRow keep, GameRow drop) = plan.SurvivorId == stale.Id ? (stale, owner) : (owner, stale);
|
||||
_log($"relocate: merged — '{drop.Name}' ({drop.Fingerprint.ExePath}) and '{keep.Name}' ({keep.Fingerprint.ExePath}) are one executable under two "
|
||||
+ $"drive letters; '{keep.Name}' stays, at {target.ExePath}, with {sessions} session(s) moved to it"
|
||||
+ (drop.HookBlockedReason is not null && keep.HookBlockedReason is null ? ", and the other entry's block" : string.Empty));
|
||||
return plan.SurvivorMoves ? target : null;
|
||||
}
|
||||
|
||||
/// <summary>The same refusal about the same row is said once, until something about it changes.</summary>
|
||||
private void LogOnce(long rowId, string line)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.Data.Common;
|
||||
using Dapper;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IGameMerge"/> over the ledger (2026-09-23, HANDOFF D26): two entries for one executable under two drive
|
||||
/// letters become one, in one transaction, or nothing is written.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>The order is the schema's.</b> <c>sessions.game_id</c> is the only reference to <c>games</c> (0001–0008) and it
|
||||
/// cascades on delete, so the sessions are re-parented BEFORE the dropped row is deleted; <c>exe_path</c> is UNIQUE, so a
|
||||
/// survivor that moves takes the path AFTER the row that held it is gone.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Only ever toward hooking off.</b> A block the dropped entry carried is kept (it is never cleared anywhere, and a
|
||||
/// merge must not be the way one disappears); a crash auto-disable it is still under turns the survivor's hooking off
|
||||
/// too; its crash count is added. Nothing about consent is read from the dropped entry or written to the survivor —
|
||||
/// <c>hook_enabled</c> only ever goes to 0 here, and the survivor's own consent is untouched: a survivor that moves has
|
||||
/// the target's bytes (the plan's condition, checked again below), which is the move <see cref="IGameRepository.RelocateExecutableAsync"/>
|
||||
/// makes with consent kept. This class is therefore a writer of <c>hook_blocked_reason</c> that can only copy a block,
|
||||
/// never set one from nothing or clear one (<c>06_DATA_MODEL</c> §Writer ownership).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class SqliteGameMerge : IGameMerge
|
||||
{
|
||||
private const string _read =
|
||||
"SELECT id, exe_path, exe_size_bytes, exe_mtime_ms, removed_at, hook_enabled, hook_blocked_reason, hook_autodisabled_reason, "
|
||||
+ "hook_autodisabled_at, hook_crash_count, hook_last_injected_at FROM games WHERE id = @id";
|
||||
|
||||
private const string _reparent = "UPDATE sessions SET game_id = @keep WHERE game_id = @drop";
|
||||
|
||||
private const string _carry =
|
||||
"UPDATE games SET hook_blocked_reason = @blocked, hook_autodisabled_reason = @autoReason, hook_autodisabled_at = @autoAt, "
|
||||
+ "hook_crash_count = @crashes, hook_last_injected_at = @injected, "
|
||||
+ "hook_enabled = CASE WHEN @hookOff THEN 0 ELSE hook_enabled END, "
|
||||
+ "hook_prescan_state = CASE WHEN @blockCarried THEN 'blocked' ELSE hook_prescan_state END, "
|
||||
+ "updated_at = @now WHERE id = @keep";
|
||||
|
||||
private const string _delete = "DELETE FROM games WHERE id = @drop";
|
||||
|
||||
private const string _move = "UPDATE games SET exe_path = @path, updated_at = @now WHERE id = @keep";
|
||||
|
||||
private readonly LedgerDatabase _db;
|
||||
|
||||
public SqliteGameMerge(LedgerDatabase db) => _db = db ?? throw new ArgumentNullException(nameof(db));
|
||||
|
||||
public ValueTask<int?> MergeAsync(GameMergePlan plan, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
return _db.WriteAsync(async (c, tx, token) =>
|
||||
{
|
||||
Twin? keep = await ReadAsync(c, tx, plan.SurvivorId, token).ConfigureAwait(false);
|
||||
Twin? drop = await ReadAsync(c, tx, plan.DroppedId, token).ConfigureAwait(false);
|
||||
if (!AsPlanned(plan, keep, drop))
|
||||
{
|
||||
return (int?)null;
|
||||
}
|
||||
|
||||
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
int sessions = await c.ExecuteAsync(new CommandDefinition(_reparent, new { keep = plan.SurvivorId, drop = plan.DroppedId }, tx, cancellationToken: token))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// A crash auto-disable the dropped entry is still under (hooking off because of it) turns the survivor's hooking off
|
||||
// too; one it was re-enabled after is history, and the survivor keeps its own.
|
||||
bool autoCarried = keep!.AutoDisabledReason is null && drop!.AutoDisabledReason is not null && !drop.HookEnabled;
|
||||
bool blockCarried = keep.BlockedReason is null && drop!.BlockedReason is not null;
|
||||
var carry = new
|
||||
{
|
||||
keep = plan.SurvivorId,
|
||||
blocked = keep.BlockedReason ?? drop!.BlockedReason,
|
||||
autoReason = autoCarried ? drop!.AutoDisabledReason : keep.AutoDisabledReason,
|
||||
autoAt = autoCarried ? drop!.AutoDisabledAt : keep.AutoDisabledAt,
|
||||
crashes = keep.CrashCount + drop!.CrashCount,
|
||||
injected = Later(keep.LastInjectedAt, drop.LastInjectedAt),
|
||||
hookOff = blockCarried || autoCarried,
|
||||
blockCarried,
|
||||
now,
|
||||
};
|
||||
await c.ExecuteAsync(new CommandDefinition(_carry, carry, tx, cancellationToken: token)).ConfigureAwait(false);
|
||||
await c.ExecuteAsync(new CommandDefinition(_delete, new { drop = plan.DroppedId }, tx, cancellationToken: token)).ConfigureAwait(false);
|
||||
if (plan.SurvivorMoves)
|
||||
{
|
||||
await c.ExecuteAsync(new CommandDefinition(_move, new { keep = plan.SurvivorId, path = plan.Target.ExePath, now }, tx, cancellationToken: token))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return (int?)sessions;
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Both rows are still what the plan saw: there, in the library, at the paths it read — and a survivor that moves still
|
||||
/// holds the target's bytes, so the move keeps its consent for the file it was given for.
|
||||
/// </summary>
|
||||
private static bool AsPlanned(GameMergePlan plan, Twin? keep, Twin? drop) =>
|
||||
keep is { RemovedAt: null } && drop is { RemovedAt: null }
|
||||
&& string.Equals(keep.ExePath, plan.SurvivorPath, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(drop.ExePath, plan.DroppedPath, StringComparison.OrdinalIgnoreCase)
|
||||
&& (plan.SurvivorMoves
|
||||
? string.Equals(drop.ExePath, plan.Target.ExePath, StringComparison.OrdinalIgnoreCase)
|
||||
&& keep.SizeBytes == plan.Target.SizeBytes && keep.MtimeMs == plan.Target.MtimeUnixMs
|
||||
: string.Equals(keep.ExePath, plan.Target.ExePath, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static long? Later(long? a, long? b) => a is null ? b : b is null ? a : Math.Max(a.Value, b.Value);
|
||||
|
||||
private static Task<Twin?> ReadAsync(SqliteConnection c, SqliteTransaction tx, long id, CancellationToken ct) =>
|
||||
SqliteReaders.ReadOneAsync(c, new CommandDefinition(_read, new { id }, tx, cancellationToken: ct), Read);
|
||||
|
||||
private static Twin Read(DbDataReader r) => new(
|
||||
r.GetInt64(0),
|
||||
r.GetString(1),
|
||||
SqliteReaders.Int64(r, 2),
|
||||
SqliteReaders.Int64(r, 3),
|
||||
SqliteReaders.Int64(r, 4),
|
||||
r.GetInt64(5) != 0,
|
||||
SqliteReaders.String(r, 6),
|
||||
SqliteReaders.String(r, 7),
|
||||
SqliteReaders.Int64(r, 8),
|
||||
r.GetInt32(9),
|
||||
SqliteReaders.Int64(r, 10));
|
||||
|
||||
private sealed record Twin(
|
||||
long Id,
|
||||
string ExePath,
|
||||
long? SizeBytes,
|
||||
long? MtimeMs,
|
||||
long? RemovedAt,
|
||||
bool HookEnabled,
|
||||
string? BlockedReason,
|
||||
string? AutoDisabledReason,
|
||||
long? AutoDisabledAt,
|
||||
int CrashCount,
|
||||
long? LastInjectedAt);
|
||||
}
|
||||
@@ -19,6 +19,9 @@ public static class PartialSessionFile
|
||||
private const int _chunkOverhead = 12;
|
||||
private const int _recordBytes = 64;
|
||||
|
||||
// A header is a few hundred bytes of JSON; a length past this is a damaged file, not a header to allocate for.
|
||||
private const int _maxHeaderBytes = 1024 * 1024;
|
||||
|
||||
/// <summary>Opens a new file and writes the header chunk. Never overwrites: a guid is one session.</summary>
|
||||
public static IPartialSessionWriter Create(string path, PartialHeader header)
|
||||
{
|
||||
@@ -45,6 +48,43 @@ public static class PartialSessionFile
|
||||
return Parse(bytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The header alone (2026-09-23), read beside the running session's writer — which holds the file for writing and
|
||||
/// shares it for reading only, so this opens it sharing read, write and delete. Null when the file is gone, cannot
|
||||
/// be opened, or its first chunk is not a whole header.
|
||||
/// </summary>
|
||||
public static PartialHeader? ReadHeader(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
Span<byte> head = stackalloc byte[8];
|
||||
if (stream.ReadAtLeast(head, head.Length, throwOnEndOfStream: false) < head.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int length = (int)BinaryPrimitives.ReadUInt32LittleEndian(head[4..]);
|
||||
if (length < 0 || length > _maxHeaderBytes)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] chunk = new byte[_chunkOverhead + length];
|
||||
head.CopyTo(chunk);
|
||||
if (stream.ReadAtLeast(chunk.AsSpan(head.Length), chunk.Length - head.Length, throwOnEndOfStream: false) < chunk.Length - head.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Parse(chunk)?.Header;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The valid prefix of <paramref name="bytes"/>; null when the header itself is missing or unreadable.</summary>
|
||||
public static PartialSession? Parse(ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
|
||||
@@ -51,6 +51,21 @@ public sealed class PartialSessionStore : IPartialSessionStore
|
||||
|
||||
public void Delete(Guid sessionGuid) => File.Delete(PathOf(sessionGuid));
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlySet<long> PendingGameIds()
|
||||
{
|
||||
HashSet<long> ids = [];
|
||||
foreach (Guid guid in ListPending())
|
||||
{
|
||||
if (PartialSessionFile.ReadHeader(PathOf(guid)) is { } header)
|
||||
{
|
||||
ids.Add(header.GameId);
|
||||
}
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Quarantine(Guid sessionGuid)
|
||||
{
|
||||
|
||||
@@ -131,13 +131,17 @@ public sealed class ImportLibraryFlowTests : IDisposable
|
||||
var can = new ImportCandidate(new StoreGame("steam", "1", "A", @"C:\a", @"C:\a\a.exe", null), @"C:\a\a.exe", AlreadyInLibrary: false, ExecutableGuessed: true);
|
||||
var already = new ImportCandidate(new StoreGame("steam", "2", "B", @"C:\b", @"C:\b\b.exe", null), @"C:\b\b.exe", AlreadyInLibrary: true, ExecutableGuessed: false);
|
||||
var none = new ImportCandidate(new StoreGame("steam", "3", "C", @"C:\c", null, null), null, AlreadyInLibrary: false, ExecutableGuessed: true);
|
||||
var vm = new ImportReviewViewModel([can, already, none]);
|
||||
var moved = new ImportCandidate(new StoreGame("steam", "4", "D", @"D:\d", @"D:\d\d.exe", null), @"D:\d\d.exe", AlreadyInLibrary: false, ExecutableGuessed: false,
|
||||
MovedFrom: @"H:\d\d.exe");
|
||||
var vm = new ImportReviewViewModel([can, already, none, moved]);
|
||||
|
||||
vm.SelectedCount.Should().Be(1, "only the importable row is ticked by default");
|
||||
vm.CanImport.Should().BeTrue();
|
||||
vm.Rows[1].Note.Should().Be(Strings.Import_Note_Already);
|
||||
vm.Rows[2].Note.Should().Be(Strings.Import_Note_NoExe);
|
||||
vm.Rows[0].Note.Should().Be(Strings.Import_Note_Guessed);
|
||||
vm.Rows[3].Note.Should().Be(Strings.Import_Note_Moved, "in the library under another drive letter (2026-09-23): that entry follows the file");
|
||||
vm.Rows[3].CanImport.Should().BeFalse();
|
||||
|
||||
vm.SelectNoneCommand.Execute(null);
|
||||
vm.SelectedCount.Should().Be(0);
|
||||
|
||||
@@ -2,6 +2,7 @@ using FluentAssertions;
|
||||
using FrameLedger.Application.Detection;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Tests.Recording;
|
||||
using FrameLedger.Application.Tests.Watch;
|
||||
using FrameLedger.Application.Watch;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Domain.Detection;
|
||||
@@ -254,4 +255,35 @@ public sealed class DetectionSweepTests
|
||||
gone.Unreadable.Should().Be(1);
|
||||
gone.Relocated.Should().Be(0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A twin merged away in the pass (2026-09-23, D26) is not an entry any more, so it is not reported unreadable: the
|
||||
/// owner's log would otherwise say the entry it just merged could not be read.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task AnEntryMergedIntoItsTwinIsNotUnreadable()
|
||||
{
|
||||
var games = new FakeGameRepository();
|
||||
const string live = @"H:\SteamLibrary\steamapps\common\Title\game.exe";
|
||||
GameRow owner = await games.EnsureAsync(new ExecutableFingerprint { ExePath = live, SizeBytes = 5, MtimeUnixMs = 5 }, "Title", Ct);
|
||||
GameRow stale = await games.EnsureAsync(new ExecutableFingerprint { ExePath = @"D:\SteamLibrary\steamapps\common\Title\game.exe", SizeBytes = 5, MtimeUnixMs = 5 }, "Title (D:)", Ct);
|
||||
var identity = new FakeIdentity
|
||||
{
|
||||
ByPath = new Dictionary<string, ExecutableFingerprint>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[live] = new ExecutableFingerprint { ExePath = live, SizeBytes = 5, MtimeUnixMs = 5 },
|
||||
},
|
||||
};
|
||||
List<string> log = [];
|
||||
using var sweep = new DetectionSweep(games, new ScriptedRules("2026.09.1"), new ScriptedProbe(), identity, log.Add,
|
||||
new ExecutableRelocator(games, identity, () => [@"C:\", @"D:\", @"H:\"], log.Add, merge: new FakeGameMerge(games)));
|
||||
|
||||
DetectionSweepReport report = await sweep.SweepOnceAsync(Ct);
|
||||
|
||||
report.Unreadable.Should().Be(0);
|
||||
report.Relocated.Should().Be(1);
|
||||
games.Rows.Should().ContainSingle().Which.Value.Id.Should().Be(owner.Id, "made first (a tie keeps the lower id), so it stays");
|
||||
log.Should().Contain(l => l.Contains("merged", StringComparison.Ordinal))
|
||||
.And.NotContain(l => l.Contains("unreadable", StringComparison.Ordinal) && l.Contains(stale.Name, StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,40 @@ public sealed class LibraryImporterTests
|
||||
public string? PickPrimary(string installDirectory) => Guesses.GetValueOrDefault(installDirectory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A game whose entry was made while its drive had another letter (2026-09-23): the entry's file is gone and this is the
|
||||
/// same path on the new letter. Importing it again made the second, side-by-side entry the owner's library showed for
|
||||
/// every game on the re-lettered drive; the review says where it is, and the import adds nothing — the Agent's
|
||||
/// relocator moves the entry to the file within one sweep.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task AGameInTheLibraryUnderAnotherDriveLetterIsNotImportedAgain()
|
||||
{
|
||||
var games = new FakeGameRepository();
|
||||
var identity = new FakeIdentity();
|
||||
List<string> log = [];
|
||||
const string stale = @"H:\STEAM\STEAMAPPS\COMMON\TITLE\TITLE.EXE";
|
||||
await games.EnsureAsync(new ExecutableFingerprint { ExePath = stale, SizeBytes = 7, MtimeUnixMs = 7 }, "Title", Ct);
|
||||
identity.Existing.Add(@"D:\STEAM\STEAMAPPS\COMMON\TITLE\TITLE.EXE");
|
||||
var steam = new ScriptedStore("steam", new StoreGame("steam", "1", "Title", @"D:\Steam\steamapps\common\Title", @"D:\Steam\steamapps\common\Title\Title.exe", null));
|
||||
var importer = new LibraryImporter([steam], games, identity, new FakeLocator(), log.Add);
|
||||
|
||||
ImportCandidate found = (await importer.DiscoverAsync(Ct)).Should().ContainSingle().Subject;
|
||||
found.MovedFrom.Should().Be(stale);
|
||||
found.AlreadyInLibrary.Should().BeFalse("not at this path");
|
||||
found.CanImport.Should().BeFalse("the entry follows the file; a second entry is the bug");
|
||||
|
||||
ImportReport report = await importer.ImportAsync([found], Ct);
|
||||
report.Added.Should().Be(0);
|
||||
report.Skipped.Should().Be(1);
|
||||
games.Rows.Should().ContainSingle().Which.Key.Should().Be(stale, "nothing was added beside it");
|
||||
log.Should().Contain(static l => l.Contains("drive whose letter changed", StringComparison.Ordinal));
|
||||
|
||||
// Both files there: two copies, not a move — the second is a game of its own.
|
||||
identity.Existing.Add(stale);
|
||||
(await importer.DiscoverAsync(Ct)).Single().MovedFrom.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DiscoveryJoinsTheStoresToTheLedgerAndImportAddsOnlyWhatWasTicked()
|
||||
{
|
||||
|
||||
@@ -49,8 +49,35 @@ internal sealed class FakeGameRepository : IGameRepository
|
||||
return ValueTask.FromResult(true);
|
||||
}
|
||||
|
||||
public ValueTask<bool> ChangeExecutableAsync(long gameId, ExecutableFingerprint fingerprint, DateTimeOffset at, CancellationToken ct = default) =>
|
||||
ValueTask.FromResult(true);
|
||||
public List<(long GameId, ExecutableFingerprint Changed)> Changes { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// The adapter's rule (2026-09-23, kept here so the relocator's D27 tests see it): a downgrade by construction — the new
|
||||
/// bytes, hooking off, consent cleared, the pre-scan not run, the block kept — refused for a removed row and for a
|
||||
/// path another row holds.
|
||||
/// </summary>
|
||||
public ValueTask<bool> ChangeExecutableAsync(long gameId, ExecutableFingerprint fingerprint, DateTimeOffset at, CancellationToken ct = default)
|
||||
{
|
||||
foreach ((string key, GameRow row) in Rows)
|
||||
{
|
||||
if (row.Id != gameId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!row.InLibrary || (Rows.TryGetValue(fingerprint.ExePath, out GameRow? holder) && holder.Id != gameId))
|
||||
{
|
||||
return ValueTask.FromResult(false);
|
||||
}
|
||||
|
||||
Rows.Remove(key);
|
||||
Rows[fingerprint.ExePath] = row with { Fingerprint = fingerprint, HookEnabled = false, HookConsentAt = null, HookPrescanState = "not_run", UpdatedAt = at };
|
||||
Changes.Add((gameId, fingerprint));
|
||||
return ValueTask.FromResult(true);
|
||||
}
|
||||
|
||||
return ValueTask.FromResult(false);
|
||||
}
|
||||
|
||||
public List<(long GameId, ExecutableFingerprint Moved)> Relocations { get; } = [];
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ internal sealed class FakePartialSessionStore : IPartialSessionStore
|
||||
Files.Remove(sessionGuid);
|
||||
}
|
||||
|
||||
public IReadOnlySet<long> PendingGameIds() => Files.Values.Select(static e => e.Header.GameId).ToHashSet();
|
||||
|
||||
/// <summary>Files set aside by recovery, out of <see cref="ListPending"/> but not deleted.</summary>
|
||||
public List<Guid> Quarantined { get; } = [];
|
||||
|
||||
|
||||
@@ -38,6 +38,27 @@ public sealed class ExecutableRelocatorTests
|
||||
return (new ExecutableRelocator(games, disk, () => roots, log.Add), games, disk, log, row);
|
||||
}
|
||||
|
||||
/// <summary>The relocator with a merge (2026-09-23): the stale entry at <c>D:</c>, added first, and its twin at <c>H:</c>, added later.</summary>
|
||||
private sealed record Twins(ExecutableRelocator Relocator, FakeGameRepository Games, FakeGameMerge Merge, DiskByPath Disk, List<string> Log, GameRow Stale, GameRow Owner);
|
||||
|
||||
private const string _twin = @"H:\SteamLibrary\steamapps\common\Title\game.exe";
|
||||
|
||||
private static async Task<Twins> TwinsAsync(bool staleFirst = true, Func<long, bool>? busy = null, long ownerSize = 500)
|
||||
{
|
||||
var games = new FakeGameRepository();
|
||||
GameRow stale = await games.EnsureAsync(new ExecutableFingerprint { ExePath = _stored, SizeBytes = 500, MtimeUnixMs = 1_700_000_000_000 }, "Title", Ct).ConfigureAwait(false);
|
||||
GameRow owner = await games.EnsureAsync(new ExecutableFingerprint { ExePath = _twin, SizeBytes = ownerSize, MtimeUnixMs = 1_700_000_000_000 }, "Title (H:)", Ct).ConfigureAwait(false);
|
||||
DateTimeOffset early = DateTimeOffset.Parse("2026-09-01T00:00:00Z", System.Globalization.CultureInfo.InvariantCulture);
|
||||
DateTimeOffset late = DateTimeOffset.Parse("2026-09-22T09:39:00Z", System.Globalization.CultureInfo.InvariantCulture);
|
||||
games.Rows[_stored] = stale = stale with { AddedAt = staleFirst ? early : late, HookEnabled = true };
|
||||
games.Rows[_twin] = owner = owner with { AddedAt = staleFirst ? late : early };
|
||||
var disk = new DiskByPath();
|
||||
disk.Put(_twin, size: ownerSize);
|
||||
var merge = new FakeGameMerge(games);
|
||||
List<string> log = [];
|
||||
return new Twins(new ExecutableRelocator(games, disk, static () => [@"C:\", @"D:\", @"H:\"], log.Add, merge: merge, busy: busy), games, merge, disk, log, stale, owner);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCandidatesAreTheSamePathUnderEveryOtherDriveLetter()
|
||||
{
|
||||
@@ -63,7 +84,7 @@ public sealed class ExecutableRelocatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AFileStillAtTheRowsPathADifferentSizeOrTwoCandidatesMoveNothing()
|
||||
public async Task AFileStillAtTheRowsPathOrTwoCandidatesMoveNothing()
|
||||
{
|
||||
(ExecutableRelocator relocator, FakeGameRepository games, DiskByPath disk, List<string> log, GameRow row) = await BuildAsync(@"C:\", @"D:\", @"H:\");
|
||||
|
||||
@@ -72,18 +93,146 @@ public sealed class ExecutableRelocatorTests
|
||||
disk.Put(@"H:\SteamLibrary\steamapps\common\Title\game.exe");
|
||||
(await relocator.TryRelocateAsync(row, Ct)).Should().BeNull();
|
||||
|
||||
// Gone from the row's path, and the candidate is a different binary: the size is the consent's, not the path's.
|
||||
disk.Files.Remove(_stored);
|
||||
disk.Put(@"H:\SteamLibrary\steamapps\common\Title\game.exe", size: 501);
|
||||
(await relocator.TryRelocateAsync(row, Ct)).Should().BeNull();
|
||||
|
||||
// Two drives hold the same bytes: an ambiguity, and ambiguity refuses.
|
||||
disk.Put(@"H:\SteamLibrary\steamapps\common\Title\game.exe");
|
||||
disk.Files.Remove(_stored);
|
||||
disk.Put(@"C:\SteamLibrary\steamapps\common\Title\game.exe");
|
||||
(await relocator.TryRelocateAsync(row, Ct)).Should().BeNull();
|
||||
log.Should().ContainSingle().Which.Should().Contain("2 drives hold");
|
||||
|
||||
// Two drives hold other bytes: the same ambiguity — D27 follows one changed file, never a guess between two.
|
||||
disk.Put(@"H:\SteamLibrary\steamapps\common\Title\game.exe", size: 501);
|
||||
disk.Put(@"C:\SteamLibrary\steamapps\common\Title\game.exe", size: 502);
|
||||
(await relocator.TryRelocateAsync(row, Ct)).Should().BeNull();
|
||||
|
||||
log.Should().HaveCount(2).And.AllSatisfy(static l => l.Should().Contain("2 drives hold"));
|
||||
games.Rows.Should().ContainKey(_stored, "nothing moved");
|
||||
games.Relocations.Should().BeEmpty();
|
||||
games.Changes.Should().BeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// D27 (owner, 2026-09-23): the row's file is gone and the only file at its path under another letter has other bytes —
|
||||
/// the game was updated while the drive had another letter. The row follows it as <i>Change executable</i> does:
|
||||
/// hooking off, consent cleared. Until this date it stayed "unreadable" for good.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task AnUpdatedExecutableOnTheOtherLetterIsFollowedWithHookingOff()
|
||||
{
|
||||
(ExecutableRelocator relocator, FakeGameRepository games, DiskByPath disk, List<string> log, GameRow row) = await BuildAsync(@"C:\", @"D:\", @"H:\");
|
||||
games.Rows[_stored] = row = row with { HookEnabled = true, HookConsentAt = DateTimeOffset.UnixEpoch, HookPrescanState = "clean", HookBlockedReason = "a block" };
|
||||
disk.Put(_twin, size: 501);
|
||||
|
||||
ExecutableFingerprint? followed = await relocator.TryRelocateAsync(row, Ct);
|
||||
|
||||
followed!.Value.ExePath.Should().Be(_twin);
|
||||
GameRow after = games.Rows[_twin];
|
||||
after.Id.Should().Be(row.Id, "the same entry, pointed at the file");
|
||||
after.Fingerprint.SizeBytes.Should().Be(501);
|
||||
after.HookEnabled.Should().BeFalse("other bytes are not the binary the consent was given for");
|
||||
after.HookConsentAt.Should().BeNull();
|
||||
after.HookBlockedReason.Should().Be("a block", "nothing clears a block");
|
||||
games.Relocations.Should().BeEmpty("a move keeps consent; this is a change, which does not");
|
||||
log.Should().ContainSingle().Which.Should().Contain("hooking OFF");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheWatcherFollowsAnUpdatedExecutableWithHookingOffToo()
|
||||
{
|
||||
(ExecutableRelocator relocator, FakeGameRepository games, DiskByPath disk, _, GameRow row) = await BuildAsync(@"C:\", @"D:\");
|
||||
games.Rows[_stored] = row = row with { HookEnabled = true };
|
||||
disk.Put(_twin, size: 501);
|
||||
|
||||
(await relocator.TryAdoptAsync(row, _twin, Ct)).Should().BeTrue("the only file at the row's path, on the letter it runs from");
|
||||
|
||||
games.Rows[_twin].HookEnabled.Should().BeFalse();
|
||||
games.Changes.Should().ContainSingle();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// D26 (owner, 2026-09-23): the owner's library showed an <c>H:</c> twin beside each game on the re-lettered drive, and
|
||||
/// once the letter was back neither could move onto the other's path — "could not be moved", every 15 s. Two entries
|
||||
/// for the same bytes under two letters become one: the entry made first stays, at the file.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TwinsWithTheSameBytesAreMergedAndTheEntryMadeFirstStays()
|
||||
{
|
||||
Twins t = await TwinsAsync(staleFirst: true);
|
||||
|
||||
ExecutableFingerprint? now = await t.Relocator.TryRelocateAsync(t.Stale, Ct);
|
||||
|
||||
GameMergePlan plan = t.Merge.Plans.Should().ContainSingle().Subject;
|
||||
plan.SurvivorId.Should().Be(t.Stale.Id, "added first");
|
||||
plan.DroppedId.Should().Be(t.Owner.Id);
|
||||
plan.SurvivorMoves.Should().BeTrue();
|
||||
now!.Value.ExePath.Should().Be(_twin, "the surviving entry lives at the file now");
|
||||
t.Games.Rows.Should().ContainSingle().Which.Value.Id.Should().Be(t.Stale.Id);
|
||||
t.Log.Should().ContainSingle().Which.Should().Contain("merged").And.Contain("'Title' stays");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheTwinWasMadeFirstItStaysAndTheStaleEntryIsGone()
|
||||
{
|
||||
Twins t = await TwinsAsync(staleFirst: false);
|
||||
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull("the stale entry is not an entry any more");
|
||||
|
||||
t.Merge.Plans.Should().ContainSingle().Which.SurvivorId.Should().Be(t.Owner.Id);
|
||||
t.Games.Rows.Should().ContainSingle().Which.Value.Id.Should().Be(t.Owner.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AMergeWaitsWhileASessionOfEitherEntryRunsOrWaitsForRecoveryAndSaysSoOnce()
|
||||
{
|
||||
long busyId = 0;
|
||||
Twins t = await TwinsAsync(busy: id => id == busyId);
|
||||
busyId = t.Owner.Id;
|
||||
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull();
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull();
|
||||
|
||||
t.Merge.Plans.Should().BeEmpty("a session re-keyed under a deleted entry would be dropped");
|
||||
t.Log.Should().ContainSingle().Which.Should().Contain("merged once no session");
|
||||
|
||||
busyId = 0;
|
||||
await t.Relocator.TryRelocateAsync(t.Stale, Ct);
|
||||
t.Merge.Plans.Should().ContainSingle("the next pass merges once nothing runs");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TwinsWithDifferentBytesAreNotMergedAndTheLogSaysWhatToDo()
|
||||
{
|
||||
Twins t = await TwinsAsync(ownerSize: 501);
|
||||
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull();
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull();
|
||||
|
||||
t.Merge.Plans.Should().BeEmpty("D26 merges the same bytes: other bytes do not prove the other entry is this game");
|
||||
t.Games.Rows.Should().HaveCount(2);
|
||||
t.Log.Should().ContainSingle().Which.Should().Contain("not merged").And.Contain("remove the entry you do not want");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AMergeThatFoundARowChangedIsSaidOnceAndTriedAgainNextPass()
|
||||
{
|
||||
Twins t = await TwinsAsync();
|
||||
t.Merge.Refuse = true;
|
||||
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull();
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull();
|
||||
|
||||
t.Merge.Plans.Should().HaveCount(2, "asked again on every pass");
|
||||
t.Log.Should().ContainSingle().Which.Should().Contain("changed underneath");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnEntryRemovedFromTheLibraryIsNotMergedWith()
|
||||
{
|
||||
Twins t = await TwinsAsync();
|
||||
t.Games.Rows[_twin] = t.Owner with { RemovedAt = DateTimeOffset.UnixEpoch };
|
||||
|
||||
(await t.Relocator.TryRelocateAsync(t.Stale, Ct)).Should().BeNull();
|
||||
|
||||
t.Merge.Plans.Should().BeEmpty("the user removed it; a merge must not bring its sessions back");
|
||||
t.Log.Should().ContainSingle().Which.Should().Contain("could not be moved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -103,10 +252,10 @@ public sealed class ExecutableRelocatorTests
|
||||
(await relocator.TryAdoptAsync(row, running, Ct)).Should().BeTrue();
|
||||
games.Rows.Should().ContainKey(running).And.NotContainKey(_stored);
|
||||
|
||||
// A different binary under the row's name is not adopted.
|
||||
GameRow other = await games.EnsureAsync(new ExecutableFingerprint { ExePath = @"D:\Other\game.exe", SizeBytes = 7, MtimeUnixMs = 7 }, "Other", Ct);
|
||||
disk.Put(@"H:\Other\game.exe", size: 8);
|
||||
(await relocator.TryAdoptAsync(other, @"H:\Other\game.exe", Ct)).Should().BeFalse();
|
||||
// A different binary at another folder's path is not adopted; the same path with other bytes is D27's (its own test).
|
||||
GameRow other = await games.EnsureAsync(new ExecutableFingerprint { ExePath = @"D:\\Other\\game.exe", SizeBytes = 7, MtimeUnixMs = 7 }, "Other", Ct);
|
||||
disk.Put(@"H:\Elsewhere\game.exe", size: 8);
|
||||
(await relocator.TryAdoptAsync(other, @"H:\Elsewhere\game.exe", Ct)).Should().BeFalse();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Application.Tests.Recording;
|
||||
|
||||
namespace FrameLedger.Application.Tests.Watch;
|
||||
|
||||
/// <summary>
|
||||
/// An <see cref="IGameMerge"/> over <see cref="FakeGameRepository"/>'s rows (2026-09-23): the dropped row goes, the survivor
|
||||
/// stands at the target with any block carried. The SQL — sessions, the order the schema needs — has its own tests
|
||||
/// (<c>SqliteGameMergeTests</c>); this is what the relocator's callers see.
|
||||
/// </summary>
|
||||
internal sealed class FakeGameMerge(FakeGameRepository games) : IGameMerge
|
||||
{
|
||||
public List<GameMergePlan> Plans { get; } = [];
|
||||
|
||||
/// <summary>When set, every merge answers "a row changed underneath" and writes nothing.</summary>
|
||||
public bool Refuse { get; set; }
|
||||
|
||||
public ValueTask<int?> MergeAsync(GameMergePlan plan, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
Plans.Add(plan);
|
||||
if (Refuse)
|
||||
{
|
||||
return ValueTask.FromResult<int?>(null);
|
||||
}
|
||||
|
||||
GameRow keep = games.Rows.Values.Single(r => r.Id == plan.SurvivorId);
|
||||
GameRow drop = games.Rows.Values.Single(r => r.Id == plan.DroppedId);
|
||||
games.Rows.Remove(drop.Fingerprint.ExePath);
|
||||
games.Rows.Remove(keep.Fingerprint.ExePath);
|
||||
games.Rows[plan.Target.ExePath] = keep with
|
||||
{
|
||||
Fingerprint = plan.SurvivorMoves ? plan.Target : keep.Fingerprint,
|
||||
HookBlockedReason = keep.HookBlockedReason ?? drop.HookBlockedReason,
|
||||
HookEnabled = keep.HookEnabled && keep.HookBlockedReason is null && drop.HookBlockedReason is null,
|
||||
HookCrashCount = keep.HookCrashCount + drop.HookCrashCount,
|
||||
};
|
||||
return ValueTask.FromResult<int?>(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Globalization;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Domain.Consent;
|
||||
|
||||
namespace FrameLedger.Application.Tests.Watch;
|
||||
|
||||
/// <summary>Which of two twin entries stays (2026-09-23, D26): the one made first, a tie keeping the lower id.</summary>
|
||||
public sealed class GameMergePlanTests
|
||||
{
|
||||
private static GameRow Row(long id, string path, string added) => new()
|
||||
{
|
||||
Id = id,
|
||||
Name = "T" + id.ToString(CultureInfo.InvariantCulture),
|
||||
Fingerprint = new ExecutableFingerprint { ExePath = path, SizeBytes = 1, MtimeUnixMs = 1 },
|
||||
HookEnabled = false,
|
||||
HookCrashCount = 0,
|
||||
AddedAt = DateTimeOffset.Parse(added, CultureInfo.InvariantCulture),
|
||||
UpdatedAt = DateTimeOffset.UnixEpoch,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void TheEntryMadeFirstStaysAndATieKeepsTheLowerId()
|
||||
{
|
||||
GameRow stale = Row(7, @"D:\G\g.exe", "2026-09-01T00:00:00Z");
|
||||
GameRow owner = Row(9, @"H:\G\g.exe", "2026-09-22T09:39:00Z");
|
||||
|
||||
GameMergePlan first = GameMergePlan.For(stale, owner, owner.Fingerprint);
|
||||
first.SurvivorId.Should().Be(7);
|
||||
first.DroppedId.Should().Be(9);
|
||||
first.SurvivorPath.Should().Be(@"D:\G\g.exe");
|
||||
first.SurvivorMoves.Should().BeTrue("the stale entry takes the file's path");
|
||||
|
||||
GameMergePlan later = GameMergePlan.For(stale with { AddedAt = owner.AddedAt.AddDays(1) }, owner, owner.Fingerprint);
|
||||
later.SurvivorId.Should().Be(9);
|
||||
later.SurvivorMoves.Should().BeFalse("the entry already at the file stays where it is");
|
||||
|
||||
GameMergePlan.For(stale with { Id = 12, AddedAt = owner.AddedAt }, owner, owner.Fingerprint).SurvivorId.Should().Be(9, "a tie keeps the lower id");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEntryIsNotItsOwnTwinAndTheOwnerIsTheEntryAtTheTarget()
|
||||
{
|
||||
GameRow a = Row(1, @"D:\G\g.exe", "2026-09-01T00:00:00Z");
|
||||
GameRow b = Row(2, @"H:\G\g.exe", "2026-09-02T00:00:00Z");
|
||||
|
||||
((Action)(() => GameMergePlan.For(a, a, a.Fingerprint))).Should().Throw<ArgumentException>();
|
||||
((Action)(() => GameMergePlan.For(a, b, a.Fingerprint))).Should().Throw<ArgumentException>("the owner must be the entry at the file");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System.Globalization;
|
||||
using Dapper;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Application.Persistence;
|
||||
using FrameLedger.Domain.Consent;
|
||||
using FrameLedger.Domain.Sessions;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Two entries for one executable under two drive letters become one (2026-09-23, D26), on a real ledger: the sessions
|
||||
/// re-parented before the cascade could take them, the path taken after the UNIQUE holder is gone, a block either carried
|
||||
/// kept, no consent moved — or nothing written at all when a row is not what the plan saw.
|
||||
/// </summary>
|
||||
public sealed class SqliteGameMergeTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private static readonly ExecutableFingerprint _d = new() { ExePath = @"D:\Games\T\t.exe", SizeBytes = 10, MtimeUnixMs = 20 };
|
||||
|
||||
private static readonly ExecutableFingerprint _h = _d with { ExePath = @"H:\Games\T\t.exe" };
|
||||
|
||||
private static Task<int> SetAsync(LedgerFixture f, long id, string assignments) =>
|
||||
f.Db.WriteAsync((c, tx, ct) => c.ExecuteAsync(new CommandDefinition($"UPDATE games SET {assignments} WHERE id = @id", new { id }, tx, cancellationToken: ct)), Ct).AsTask();
|
||||
|
||||
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);
|
||||
return await new SqliteSessionRepository(f.Db).InsertFinalizedAsync(new FinalizedSession
|
||||
{
|
||||
Row = new SessionRow
|
||||
{
|
||||
SessionGuid = Guid.NewGuid(),
|
||||
GameId = gameId,
|
||||
SnapshotId = snapshotId,
|
||||
StartedAt = DateTimeOffset.UnixEpoch,
|
||||
EndedAt = DateTimeOffset.UnixEpoch.AddSeconds(60),
|
||||
QpcEpoch = 0,
|
||||
QpcFrequency = 1,
|
||||
Tier = CaptureTier.NotHooked,
|
||||
Mode = CaptureMode.Attach,
|
||||
ExitStatus = ExitStatus.Normal,
|
||||
},
|
||||
}, Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task<(SqliteGameRepository Repo, GameRow Stale, GameRow Twin)> TwinsAsync(LedgerFixture f, long staleAdded, long twinAdded)
|
||||
{
|
||||
var repo = new SqliteGameRepository(f.Db);
|
||||
GameRow stale = await repo.EnsureAsync(_d, "Title", Ct).ConfigureAwait(false);
|
||||
GameRow twin = await repo.EnsureAsync(_h, "Title (H:)", Ct).ConfigureAwait(false);
|
||||
await SetAsync(f, stale.Id, "added_at = " + staleAdded.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
await SetAsync(f, twin.Id, "added_at = " + twinAdded.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
||||
return (repo, stale, twin);
|
||||
}
|
||||
|
||||
private static async Task<GameMergePlan> PlanAsync(SqliteGameRepository repo, GameRow stale, GameRow twin) =>
|
||||
GameMergePlan.For((await repo.FindByIdAsync(stale.Id, Ct).ConfigureAwait(false))!, (await repo.FindByIdAsync(twin.Id, Ct).ConfigureAwait(false))!, _h);
|
||||
|
||||
[Fact]
|
||||
public async Task TheEntryMadeFirstTakesTheTwinsSessionsItsBlockAndItsPath()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(SqliteGameRepository repo, GameRow stale, GameRow twin) = await TwinsAsync(f, staleAdded: 1_000, twinAdded: 2_000);
|
||||
await SetAsync(f, stale.Id, "hook_enabled = 1, hook_consent_at = 5, hook_consent_provenance = 'ConsentDialog', hook_consent_disclosure_version = 'v', "
|
||||
+ "hook_prescan_state = 'clean', hook_crash_count = 1, hook_last_injected_at = 30");
|
||||
await SetAsync(f, twin.Id, "hook_blocked_reason = 'BlockedModule: Easy Anti-Cheat', hook_prescan_state = 'blocked', hook_crash_count = 2, hook_last_injected_at = 40");
|
||||
long mine = await AddSessionAsync(f, stale.Id);
|
||||
long theirs = await AddSessionAsync(f, twin.Id);
|
||||
|
||||
int? moved = await new SqliteGameMerge(f.Db).MergeAsync(await PlanAsync(repo, stale, twin), Ct);
|
||||
|
||||
moved.Should().Be(1);
|
||||
(await repo.FindByIdAsync(twin.Id, Ct)).Should().BeNull("the twin is gone");
|
||||
GameRow kept = (await repo.FindByIdAsync(stale.Id, Ct))!;
|
||||
kept.Fingerprint.Should().Be(_h, "it lives at the file now — the same bytes, so the move keeps its consent record");
|
||||
kept.HookConsentAt.Should().NotBeNull();
|
||||
kept.HookBlockedReason.Should().Be("BlockedModule: Easy Anti-Cheat", "a block either entry carried is kept; nothing clears one");
|
||||
kept.HookEnabled.Should().BeFalse("and the block turns hooking off");
|
||||
kept.HookPrescanState.Should().Be("blocked");
|
||||
kept.HookCrashCount.Should().Be(3);
|
||||
kept.HookLastInjectedAt.Should().Be(DateTimeOffset.FromUnixTimeMilliseconds(40));
|
||||
kept.AddedAt.Should().Be(DateTimeOffset.FromUnixTimeMilliseconds(1_000));
|
||||
var sessions = new SqliteSessionRepository(f.Db);
|
||||
(await sessions.FindByIdAsync(mine, Ct))!.GameId.Should().Be(stale.Id);
|
||||
(await sessions.FindByIdAsync(theirs, Ct))!.GameId.Should().Be(stale.Id, "re-parented before the delete, not cascaded away with it");
|
||||
(await repo.FindAsync(_d.ExePath, Ct)).Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheTwinWasMadeFirstItStaysAndNoConsentMovesToIt()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(SqliteGameRepository repo, GameRow stale, GameRow twin) = await TwinsAsync(f, staleAdded: 2_000, twinAdded: 1_000);
|
||||
await SetAsync(f, stale.Id, "hook_enabled = 1, hook_consent_at = 5, hook_consent_provenance = 'ConsentDialog', hook_consent_disclosure_version = 'v', hook_prescan_state = 'clean'");
|
||||
long session = await AddSessionAsync(f, stale.Id);
|
||||
|
||||
(await new SqliteGameMerge(f.Db).MergeAsync(await PlanAsync(repo, stale, twin), Ct)).Should().Be(1);
|
||||
|
||||
(await repo.FindByIdAsync(stale.Id, Ct)).Should().BeNull();
|
||||
GameRow kept = (await repo.FindByIdAsync(twin.Id, Ct))!;
|
||||
kept.Fingerprint.Should().Be(_h);
|
||||
kept.HookEnabled.Should().BeFalse("the dropped entry's consent is about that entry; a merge never grants");
|
||||
kept.HookConsentAt.Should().BeNull();
|
||||
(await new SqliteSessionRepository(f.Db).FindByIdAsync(session, Ct))!.GameId.Should().Be(twin.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ACrashAutoDisableStillInForceIsCarriedAndOneAlreadyLiftedIsNot()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(SqliteGameRepository repo, GameRow stale, GameRow twin) = await TwinsAsync(f, staleAdded: 1_000, twinAdded: 2_000);
|
||||
await SetAsync(f, stale.Id, "hook_enabled = 1");
|
||||
await SetAsync(f, twin.Id, "hook_enabled = 0, hook_autodisabled_reason = 'crashed 3 times', hook_autodisabled_at = 77");
|
||||
|
||||
(await new SqliteGameMerge(f.Db).MergeAsync(await PlanAsync(repo, stale, twin), Ct)).Should().Be(0);
|
||||
|
||||
GameRow kept = (await repo.FindByIdAsync(stale.Id, Ct))!;
|
||||
kept.HookEnabled.Should().BeFalse("the crash policy turned this executable's hooking off, under either entry");
|
||||
kept.HookAutoDisabledReason.Should().Be("crashed 3 times");
|
||||
|
||||
await using LedgerFixture g = await LedgerFixture.OpenAsync();
|
||||
(repo, stale, twin) = await TwinsAsync(g, staleAdded: 1_000, twinAdded: 2_000);
|
||||
await SetAsync(g, stale.Id, "hook_enabled = 1");
|
||||
await SetAsync(g, twin.Id, "hook_enabled = 1, hook_autodisabled_reason = 'crashed 3 times', hook_autodisabled_at = 77");
|
||||
|
||||
(await new SqliteGameMerge(g.Db).MergeAsync(await PlanAsync(repo, stale, twin), Ct)).Should().Be(0);
|
||||
|
||||
GameRow lifted = (await repo.FindByIdAsync(stale.Id, Ct))!;
|
||||
lifted.HookEnabled.Should().BeTrue("the user turned hooking back on after that auto-disable; it is history, not a state");
|
||||
lifted.HookAutoDisabledReason.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ARowThatIsNotWhatThePlanSawIsNotMergedAndNothingIsWritten()
|
||||
{
|
||||
await using LedgerFixture f = await LedgerFixture.OpenAsync();
|
||||
(SqliteGameRepository repo, GameRow stale, GameRow twin) = await TwinsAsync(f, staleAdded: 1_000, twinAdded: 2_000);
|
||||
long session = await AddSessionAsync(f, twin.Id);
|
||||
GameMergePlan plan = await PlanAsync(repo, stale, twin);
|
||||
var merge = new SqliteGameMerge(f.Db);
|
||||
|
||||
// The survivor's bytes are no longer the file's: a move now would carry its consent to another binary.
|
||||
await SetAsync(f, stale.Id, "exe_size_bytes = 11");
|
||||
(await merge.MergeAsync(plan, Ct)).Should().BeNull();
|
||||
|
||||
// The twin was removed from the library meanwhile.
|
||||
await SetAsync(f, stale.Id, "exe_size_bytes = 10");
|
||||
(await repo.RemoveAsync(twin.Id, keepSessions: true, Ct)).Should().BeTrue();
|
||||
(await merge.MergeAsync(plan, Ct)).Should().BeNull();
|
||||
|
||||
(await repo.FindByIdAsync(stale.Id, Ct))!.Fingerprint.Should().Be(_d, "nothing moved");
|
||||
(await repo.FindByIdAsync(twin.Id, Ct)).Should().NotBeNull("nothing deleted");
|
||||
(await new SqliteSessionRepository(f.Db).FindByIdAsync(session, Ct))!.GameId.Should().Be(twin.Id, "nothing re-parented");
|
||||
}
|
||||
}
|
||||
@@ -20,19 +20,36 @@ public sealed class PartialSessionStoreTests : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private static PartialHeader Header(Guid guid) => new()
|
||||
private static PartialHeader Header(Guid guid, long gameId = 1) => new()
|
||||
{
|
||||
SessionGuid = guid,
|
||||
StartedAt = DateTimeOffset.UnixEpoch,
|
||||
QpcEpoch = 1,
|
||||
QpcFrequency = 10_000_000,
|
||||
GameId = 1,
|
||||
GameId = gameId,
|
||||
SnapshotId = 1,
|
||||
ExePath = @"C:\g\game.exe",
|
||||
Tier = CaptureTier.NotHooked,
|
||||
Mode = CaptureMode.Attach,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The entries pending files name (2026-09-23): what a merge of two entries waits for. Read beside a running session's
|
||||
/// writer, which shares its file for reading only — a plain read would fail on it — and a damaged file names nothing.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void PendingGameIdsAreReadBesideARunningSessionsWriter()
|
||||
{
|
||||
var store = new PartialSessionStore(_dir);
|
||||
store.PendingGameIds().Should().BeEmpty("no directory yet is no sessions");
|
||||
|
||||
using IPartialSessionWriter running = store.Create(Header(Guid.NewGuid(), gameId: 7));
|
||||
store.Create(Header(Guid.NewGuid(), gameId: 9)).Dispose();
|
||||
File.WriteAllBytes(Path.Combine(_dir, Guid.NewGuid().ToString("N") + ".partial"), [1, 2, 3]);
|
||||
|
||||
store.PendingGameIds().Should().BeEquivalentTo([7L, 9L]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreatesUnderTheDirectoryListsOldestFirstReadsBackAndDeletes()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user