Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfd47a9a54 |
No files matched your search
@@ -61,6 +61,30 @@ under a `## [x.y.z] - date` heading in the same commit that bumps `VERSION`, the
|
||||
§Migrations). And a failed dump names dbghelp's error instead of 0: CsWin32 declares `MiniDumpWriteDump` without
|
||||
`SetLastError`, so the code is read with `GetLastSystemError` (`ParentDumpTests`: an exited process).
|
||||
|
||||
- **One Agent per data folder: an App started as administrator no longer starts an Agent per connect round
|
||||
(2026-09-17).** On the owner's machine the installed 0.1.0-beta.1 ran four `FrameLedger.Agent.exe --serve`: the App
|
||||
opened at 10:04 was elevated, the pipe of the Agent already serving refused it, and it took the refusal for an absent
|
||||
Agent and started three more, elevated like itself, 17 seconds apart. Nothing in the Agent noticed the first — the
|
||||
single instance `01_ARCHITECTURE` §Lifecycle specified was never built — so every game launched in the next hour was
|
||||
injected, read and recorded by all four (four copies of each session, equal frame counts), and the three extras
|
||||
logged "accept failed" every 260 ms for four hours. The cause of the refusal: `PipeOptions.CurrentUserOnly` compares
|
||||
the pipe's owner with the client token's default *owner*, which an elevated token sets to Administrators (the elevated
|
||||
Agents' log files are owned by Administrators, measured), not with its *user*.
|
||||
- `Infrastructure.Startup.AgentInstanceLock`: a named mutex per data folder, claimed by `--serve` and the console's
|
||||
`capture` / `launch` / `recover` before logging, rules and the ledger; a second process exits **10** with one line.
|
||||
- The App starts an Agent only when no process holds the folder and the one it started last has exited; it logs why a
|
||||
connect failed, once per reason, and the exit code of the Agent it started.
|
||||
- The pipe states its owner (`O:<user>` in the SDDL) and the client checks the owner against its token user
|
||||
(`PipeAccessControl.RequireOwnedByCurrentUser`), so an elevated App and an unelevated Agent reach each other in both
|
||||
directions.
|
||||
- A pipe instance that cannot be created backs off 250 ms → 10 s and is logged with its Win32 error, once per streak
|
||||
(CsWin32 declares `CreateNamedPipeW` without `SetLastError`; the error is read with `GetLastSystemError`).
|
||||
- Tests: `AgentInstanceLockTests`, `OneAgentPerDataFolderTests` (the shipped binary against a claimed scratch folder),
|
||||
`AgentConnectionTests` (an Agent that is up and does not answer is never started again; the real launcher sees the
|
||||
claim), `PipeServerClientTests` (the owner; an Administrators-owning token trusts its user's pipe and refuses an
|
||||
Administrators one — on CI's elevated runner; the backoff logs once with error 231). Docs: `01_ARCHITECTURE`
|
||||
§Lifecycle, `07_IPC` §C and §Client behavior, `08_UI`, `12_BUILD`, `20_OPEN_QUESTIONS` §G.
|
||||
|
||||
### Added
|
||||
|
||||
- **A session whose frame-generation state changed publishes its steady state, with its share (2026-09-17, owner
|
||||
|
||||
@@ -93,6 +93,16 @@ Guard re-runs every 30 s for the life of the session; anti-cheat appearing late
|
||||
- UI exit does not stop the Agent when background capture is enabled; otherwise UI sends `Shutdown`.
|
||||
- Single instance via named mutexes; the ring name is per-PID so multiple games can be captured simultaneously (rare but supported).
|
||||
|
||||
> **The single instance was specified here and not built until 2026-09-17**, and 0.1.0-beta.1 ran four Agents: an
|
||||
> App started as administrator was refused by the pipe of the Agent already serving (`07_IPC` §C, amended the same
|
||||
> day), took the refusal for an absent Agent, and started another on each connect round — and every game launched in
|
||||
> the next hour was injected, read and recorded by all four. **Built:** `Infrastructure.Startup.AgentInstanceLock`,
|
||||
> one named mutex per data folder (`Local\FrameLedger.Agent.<hash of the folder>`), claimed by `--serve` and the
|
||||
> console's capturing verbs (`capture`, `launch`, `recover`) before logging, rules or the ledger; a second process
|
||||
> exits **10** with one line on stderr. The App probes the same claim before it starts an Agent (`07_IPC` §Client
|
||||
> behavior). What it does not cover: two Agents on two data folders (a developer's `--console --data-dir` beside the
|
||||
> installed Agent) can still both attach to one game's ring — `20_OPEN_QUESTIONS` §G, Agent lifecycle.
|
||||
|
||||
## Failure domains
|
||||
|
||||
| Failure | Behavior |
|
||||
|
||||
+26
-1
@@ -291,7 +291,24 @@ Unchanged in spirit from v1, bumped to `v2` for the new message set.
|
||||
SDDL `D:P(A;;GA;;;<user SID>)(A;;GA;;;BA)` on the instance — `PipeAccessControl.Sddl`, what `20_OPEN_QUESTIONS`
|
||||
§G asked for — and the token check by impersonation on the client's FIRST frame, because the kernel refuses
|
||||
`ImpersonateNamedPipeClient` before the client has written; a stranger is disconnected without an answer and
|
||||
counted. The client side uses `PipeOptions.CurrentUserOnly`, the mirror check on the server's owner.)*
|
||||
counted. ~~The client side uses `PipeOptions.CurrentUserOnly`, the mirror check on the server's owner.~~)*
|
||||
|
||||
> **Amended 2026-09-17: the owner is stated, and the client compares it with its token USER.** The SDDL is now
|
||||
> `O:<user SID>D:P(A;;GA;;;<user SID>)(A;;GA;;;BA)`. Left to default, a pipe's owner is its creator token's default
|
||||
> owner, and an elevated token's is `BUILTIN\Administrators` — measured on the owner's machine that morning: the log
|
||||
> files the elevated Agents created are owned by Administrators, the unelevated ones' by the user.
|
||||
> `PipeOptions.CurrentUserOnly` compares the pipe's owner with the client token's default OWNER
|
||||
> (`NamedPipeClientStream.ValidateRemotePipeUser` in dotnet/runtime), so an App started as administrator refused the
|
||||
> user's own unelevated Agent, silently, as though none were there, and started another on every connect round
|
||||
> (`01_ARCHITECTURE` §Lifecycle). The client connects without that option and calls
|
||||
> `PipeAccessControl.RequireOwnedByCurrentUser` before it writes a byte; `PipeServerClientTests` pins the owner and
|
||||
> drives both directions on a token that owns as Administrators (CI's elevated runner — an unelevated run skips it).
|
||||
>
|
||||
> **Accept failures back off.** An instance that cannot be created is retried 250 ms doubling to 10 s and logged on
|
||||
> the first failure, on a change of error and at 10, 100, 1000… in a row, with the Win32 error. The three extra
|
||||
> Agents of that morning logged the bare "accept failed" every 260 ms for four hours, 2 MB each. The error is read
|
||||
> with `GetLastSystemError`: CsWin32 0.3.298 declares `CreateNamedPipeW` without `SetLastError`, so
|
||||
> `GetLastPInvokeError` read 0.
|
||||
- Framing: 4-byte LE length + UTF-8 JSON, max 1 MB. `System.Text.Json` source-generated contexts in `FrameLedger.Shared`.
|
||||
*(Header and body go out in one write, so on the message-mode pipe one frame is one message; the reader
|
||||
reassembles by length alone. Over the cap, or a stream ending inside a frame, is `IpcFramingException`.)*
|
||||
@@ -364,6 +381,14 @@ message, and that message always re-scans.
|
||||
## Client behavior (UI)
|
||||
|
||||
- Connect with 250 ms × 8 backoff; on failure start the Agent, retry; then show an Agent status banner with Repair.
|
||||
|
||||
> **Amended 2026-09-17: never a second Agent.** A round that ends without a connection starts one only when no
|
||||
> process holds the user's data folder (`AgentInstanceLock`, probed through `IAgentLauncher.RunningAgent`) and the
|
||||
> Agent this App started last has exited. Otherwise it starts nothing and logs why the connect failed and that it
|
||||
> is not starting another — once per distinct reason, not once per round (`AgentConnection.LastConnectFailure`;
|
||||
> before this the reason was swallowed, and a refusal looked exactly like an absent Agent). The Agent it does start
|
||||
> is watched until it exits and its exit code logged, so exit 10 — the folder was already claimed — is visible in
|
||||
> the App's log. `AgentConnectionTests` pins both.
|
||||
- Treat the pipe as unreliable: library, history and charts must all work with the Agent offline. Only live status degrades.
|
||||
- SQLite is the source of truth for anything persisted; pipe events are refresh signals (except `SessionProgress`, which is live-only by design).
|
||||
- `CaptureRefused` and `SafetyUnhook` are **never** collapsed into a generic error toast — they get dedicated, explanatory UI (`08_UI` §Notifications).
|
||||
|
||||
@@ -55,6 +55,7 @@ The Menu sits in its own row **below** the TitleBar (never inside the drag regio
|
||||
> are empty states; Settings has Appearance (theme + language, both persisted in `settings` — D16's
|
||||
> `ui.theme`/`ui.language`). The App starts `FrameLedger.Agent.exe --serve` beside itself when the pipe
|
||||
> is absent (`07_IPC` §Client behavior, 8 × 250 ms) and shows **Missing** when there is no Agent to start.
|
||||
> *(Since 2026-09-17: and only when no Agent already holds the data folder — `07_IPC` §Client behavior.)*
|
||||
> Measured on the dev box: first window at 1.3 s from process start (NFR-4's 2 s). ~~The tray is PR-8's.~~
|
||||
> **Tray built 2026-09-14 (P3 PR-8b).** `Services/TrayHost` over `TrayViewModel` (no WPF in the view model,
|
||||
> `TrayViewModelTests`): the four icons are drawn at start (`TrayIcons`, a PNG inside an in-memory `.ico`,
|
||||
|
||||
@@ -105,6 +105,12 @@ Agent flags: `--serve`, `--console`, `--write-crash-dump <file>` (2026-09-17: th
|
||||
> `db path` opens no file at all. Until then every verb went through the migrating open, and `sessions` run against
|
||||
> the owner's ledger applied two scripts to it (`06_DATA_MODEL` §Migrations). `AgentReadOnlyVerbsTests` pins the set.
|
||||
|
||||
> **One capturing process per data folder (2026-09-17).** `--serve`, `capture`, `launch` and `recover` claim the data
|
||||
> folder (`AgentInstanceLock`) before logging, rules or the ledger, and exit **10** — one line on stderr, nothing
|
||||
> written — when another process holds it; the other verbs run beside a serving Agent, as the App's `--install-task`
|
||||
> does. `OneAgentPerDataFolderTests` runs the shipped binary against a claimed scratch folder
|
||||
> (`01_ARCHITECTURE` §Lifecycle).
|
||||
|
||||
## Bundled assets
|
||||
|
||||
- ~~`assets/native/PresentMon.exe` (pinned, SHA-256 verified at build) for the Tier-2 fallback~~ — **DROPPED 2026-08-27, and there are no bundled native assets at all.** §S31 measured PresentMon classifying every frame of a ×4 capture as an application frame (row P2); the owner then dropped it outright. It is not bundled, not fetched, not used, and `tools/frametype-oracle.ps1` — the parser that consumed its output — is deleted with it. `assets/` does not exist and now has no reason to. **And since 2026-08-28 Tier 2 is not a measurement at all**: the ladder is two rungs, `EtwFrameSource` is deleted from the design, and whether a shipped build ever regains a no-injection measurement is `20_OPEN_QUESTIONS` §G.
|
||||
|
||||
@@ -4306,12 +4306,12 @@ Each of these is referenced by an existing doc but specified nowhere.
|
||||
|
||||
| Area | What is missing | Referenced by |
|
||||
|---|---|---|
|
||||
| **Agent lifecycle** | Scheduled-task definition, start-at-logon, how elevation is requested and persisted, what "Repair" repairs. **`--serve` exists since 2026-09-10 (P2 PR-F)** — a Generic Host around the watcher, stopped by Ctrl+C with a 15 s finalize grace — and `--install-task` / `--uninstall-task` answer "not implemented in P2"; the task definition and start-at-logon are what stays open | `08_UI` Settings, `11_UPDATER`, `12_BUILD` flags |
|
||||
| **Agent lifecycle** | Scheduled-task definition, start-at-logon, how elevation is requested and persisted, what "Repair" repairs. **`--serve` exists since 2026-09-10 (P2 PR-F)** — a Generic Host around the watcher, stopped by Ctrl+C with a 15 s finalize grace — and `--install-task` / `--uninstall-task` answer "not implemented in P2"; the task definition and start-at-logon are what stays open. **One Agent per data folder since 2026-09-17** (`01_ARCHITECTURE` §Lifecycle: `AgentInstanceLock`, exit 10; beta.1 ran four after an elevated App was refused by the pipe). **Still open from that morning:** (1) the ring's single consumer is enforced across data folders only by `NoSecondRingReaderTests`' source sweep — a developer's `--console --data-dir` capture beside the installed Agent can still attach a second reader to one game's `Local\FrameLedger.Ring.<pid>`, and a runtime claim beside the mapping would close it; (2) elevation is inherited, not chosen — an App started as administrator starts an elevated Agent, which injects and writes the ledger as administrator | `08_UI` Settings, `11_UPDATER`, `12_BUILD` flags |
|
||||
| **Session identity** | ~~`sessions` has no GUID column, yet `SessionStarted`/`StopSession`/`.partial` files are all keyed by `sessionGuid`.~~ **`sessions.session_guid` (UNIQUE) exists since 2026-09-09 (P2 PR-B), with `qpc_epoch` / `qpc_frequency` beside it.** ~~Still open: the `.partial` file format is undefined, and it is the crash-recovery artifact — PR-D's, pre-committed in HANDOFF §P2 (CRC-framed append-only chunks, the valid prefix wins)~~ **Built 2026-09-10 (P2 PR-D): `06_DATA_MODEL` §The `.partial` file, `PartialSessionFile` + `PartialRecovery`, killed at every byte in the merge gate.** What stays open here is the pipe's use of the guid (P3) | `07_IPC`, `04_CAPTURE`, `06_DATA_MODEL` |
|
||||
| ~~**Settings registry**~~ | ~~The `settings` table is key/value with no key list, defaults, types, or validation — and no message for the UI to push a changed setting to the Agent.~~ **Decided 2026-09-13 (HANDOFF §P3 decision D16)**: the key list with defaults and ranges, and *no* push message — the Agent re-reads its keys at each session start. **Built the same day (P3 PR-3):** `06_DATA_MODEL` §Settings registry (12 keys), `Application.Settings.SettingsRegistry` + `RegisteredSettings` (validating writes, tolerant reads), `SettingsRecorderPolicy` resolving `capture.min_session_s` / `telemetry.interval_ms` / `retention.raw_sessions_per_game` at each session start. **Row closed** | `06_DATA_MODEL`, FR-10 |
|
||||
| **Error taxonomy** | `07_IPC` lists `CaptureError` codes; no canonical mapping to resx keys and user-facing text, though `09_I18N` requires safety strings to be reviewed as legal text | `07_IPC`, `09_I18N` |
|
||||
| ~~**Threading model**~~ | ~~Which component owns which thread, UI-thread rules, and how the 1 Hz telemetry poller, 10 Hz drain and pipe reader interact~~ **Answered 2026-09-09 (P2 PR-C): `04_CAPTURE` §Threading model** — four threads, one owner per shared object, the pipe reader named as one more producer. This row was not struck when the section was written; struck 2026-09-13. What is still unspecified is the UI thread's own rules, which is `08_UI`'s in P3 | `04_CAPTURE`, `18_GPU_VENDOR_APIS` |
|
||||
| **Pipe/shm security** | Stated as policy ("DACL granting the current user's SID") but not as implementable SDDL, nor who creates the objects with what rights. The shm half is built (`fl_shm_host.h`, the Overlay creates the section under the current user's SID); the pipe half is **built 2026-09-13 (P3 PR-1, HANDOFF §P3 decision D11)**: `D:P(A;;GA;;;<user>)(A;;GA;;;BA)` handed to `CreateNamedPipe` with `PIPE_REJECT_REMOTE_CLIENTS`, and the client's token user compared by impersonation on its first frame (`Infrastructure.Ipc.PipeAccessControl`, pinned by `PipeServerClientTests` including the refused stranger). **Row closed** | `07_IPC` |
|
||||
| **Pipe/shm security** | Stated as policy ("DACL granting the current user's SID") but not as implementable SDDL, nor who creates the objects with what rights. The shm half is built (`fl_shm_host.h`, the Overlay creates the section under the current user's SID); the pipe half is **built 2026-09-13 (P3 PR-1, HANDOFF §P3 decision D11)**: `D:P(A;;GA;;;<user>)(A;;GA;;;BA)` (with the owner `O:<user>` stated since 2026-09-17, `07_IPC` §C) handed to `CreateNamedPipe` with `PIPE_REJECT_REMOTE_CLIENTS`, and the client's token user compared by impersonation on its first frame (`Infrastructure.Ipc.PipeAccessControl`, pinned by `PipeServerClientTests` including the refused stranger). **Row closed** | `07_IPC` |
|
||||
| ~~**Legal doc versioning**~~ | ~~FR-11 re-shows documents "when a document version increments". Nothing says where the current version lives, who writes `legal_acceptance.version`, or how the markdown is rendered in-app~~ **Answered 2026-09-14 (P3 PR-9):** the version is the document's own `**Version:**` line, read from the copy embedded in the App at build (`App.Services.LegalDocuments`); the App writes `legal_acceptance.version` on the one Accept and re-shows any document whose embedded version differs from its row; the markdown is shown as text with authoring comments stripped, not rendered (`08_UI` §First-run flow built note) | FR-11, `06_DATA_MODEL` |
|
||||
| **Accessibility / DPI** | NFR-9 states requirements; no design anywhere | NFR-9, `08_UI` |
|
||||
| **Uninstall / data deletion** | One Velopack clause. No in-app "delete all my data", despite the privacy position | `12_BUILD`, `legal/PRIVACY_POLICY.md` |
|
||||
|
||||
@@ -26,7 +26,8 @@ internal sealed class WatcherHostedService(PartialRecovery recovery, CaptureOrch
|
||||
Log.Information("recover: {Guid} {Status} {Detail}", o.SessionGuid.ToString("N"), o.Status, o.Detail);
|
||||
}
|
||||
|
||||
Log.Information("serve: watching the games table at 1 Hz; hooking only where a game is enabled and consented");
|
||||
Log.Information("serve: watching the games table at 1 Hz; hooking only where a game is enabled and consented ({Elevation}, pid {Pid})",
|
||||
Environment.IsPrivilegedProcess ? "elevated" : "not elevated", Environment.ProcessId);
|
||||
await orchestrator.RunAsync(stoppingToken).ConfigureAwait(false);
|
||||
Log.Information("serve: stopped");
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
// The Agent is the sole owner of %LOCALAPPDATA%\FrameLedger (§S18 blocker 3, ratified) and the only
|
||||
// thing that may write there; `--data-dir` exists only under `--console` (HANDOFF §P2 decision D6).
|
||||
//
|
||||
// One process per data folder runs the capturing verbs (--serve, capture, launch, recover): Infrastructure.Startup's
|
||||
// AgentInstanceLock, claimed before logging, and a second exits 10 (2026-09-17 — beta.1 ran four Agents at once).
|
||||
//
|
||||
// The maintenance flags (P3 PR-8b) — --register-vklayer, --unregister-vklayer, --install-task, --uninstall-task —
|
||||
// run over the product directory and exit; --diag is the App's (10_LOGGING) and answers "not implemented", exit 2.
|
||||
|
||||
@@ -20,6 +23,7 @@ using FrameLedger.Application.Rules;
|
||||
using FrameLedger.Infrastructure.Diagnostics;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using FrameLedger.Infrastructure.Rules;
|
||||
using FrameLedger.Infrastructure.Startup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Serilog;
|
||||
@@ -47,6 +51,12 @@ internal static class Program
|
||||
}
|
||||
|
||||
AgentPaths paths = cmd.DataDirectory is { } dir ? new AgentPaths(Path.GetFullPath(dir)) : AgentPaths.Default;
|
||||
using AgentInstanceLock? claim = ClaimDataDirectory(cmd.Verb, paths, out bool heldElsewhere);
|
||||
if (heldElsewhere)
|
||||
{
|
||||
return AgentInstanceLock.ExitHeldElsewhere;
|
||||
}
|
||||
|
||||
ConfigureLogging(paths);
|
||||
HookCrashHandlers(paths);
|
||||
|
||||
@@ -126,6 +136,34 @@ internal static class Program
|
||||
internal static bool PrintsOnly(AgentVerb verb) =>
|
||||
verb is AgentVerb.Sessions or AgentVerb.ConsentList or AgentVerb.KillSwitchStatus or AgentVerb.DbPath;
|
||||
|
||||
/// <summary>
|
||||
/// The verbs that inject, read a ring or finalize sessions: one process per data folder may run them (2026-09-17). The
|
||||
/// others (consent, games, the kill switch, the maintenance flags, the read-only verbs) run beside a serving Agent, as
|
||||
/// the App's own <c>--install-task</c> does.
|
||||
/// </summary>
|
||||
internal static bool Captures(AgentVerb verb) =>
|
||||
verb is AgentVerb.Serve or AgentVerb.Capture or AgentVerb.Launch or AgentVerb.Recover;
|
||||
|
||||
private static AgentInstanceLock? ClaimDataDirectory(AgentVerb verb, AgentPaths paths, out bool heldElsewhere)
|
||||
{
|
||||
heldElsewhere = false;
|
||||
if (!Captures(verb))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
AgentInstanceLock? claim = AgentInstanceLock.TryAcquire(paths.DataDirectory);
|
||||
if (claim is null)
|
||||
{
|
||||
// Before logging, rules and the ledger: the Agent holding the folder holds the day's log file too, so a second one
|
||||
// leaves nothing behind but this line and its exit code, which the App's log records when the App started it.
|
||||
heldElsewhere = true;
|
||||
AgentConsole.Problem($"another FrameLedger Agent is already capturing for {paths.DataDirectory}; this one exits (exit {AgentInstanceLock.ExitHeldElsewhere})");
|
||||
}
|
||||
|
||||
return claim;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Null when a print verb refuses the ledger — at another schema, or not there — said on the console and in the log
|
||||
/// rather than as a crash: nothing about this machine is broken.
|
||||
|
||||
@@ -8,9 +8,9 @@ namespace FrameLedger.App.Services;
|
||||
/// <summary>
|
||||
/// The App's end of the pipe as a long-running state machine (<c>07_IPC</c> §Client behavior): a connect
|
||||
/// round of <see cref="AgentConnectionOptions.ConnectAttempts"/> × backoff; on failure start the Agent beside
|
||||
/// this executable and try again; then <c>Hello</c>, <c>GetStatus</c>, keepalive pings, and the event stream
|
||||
/// until the pipe drops — then the next round. "Treat the pipe as unreliable": everything persisted comes from
|
||||
/// SQLite, and this class only ever degrades the live status.
|
||||
/// this executable — unless one is already up (<see cref="IAgentLauncher.RunningAgent"/>) — and try again; then
|
||||
/// <c>Hello</c>, <c>GetStatus</c>, keepalive pings, and the event stream until the pipe drops — then the next round.
|
||||
/// "Treat the pipe as unreliable": everything persisted comes from SQLite, and this class only ever degrades the live status.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Runs on the thread pool; <see cref="Changed"/> and <see cref="EventReceived"/> fire there, and a view model
|
||||
@@ -28,6 +28,8 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable
|
||||
private long _rounds;
|
||||
private long _launches;
|
||||
private volatile bool _holdLaunches;
|
||||
private volatile string? _lastFailure;
|
||||
private string? _reported;
|
||||
|
||||
public AgentConnection(IAgentLauncher launcher, Func<PipeClient> pipes, AgentConnectionOptions options, string appVersion)
|
||||
{
|
||||
@@ -54,6 +56,12 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable
|
||||
/// <summary>How many times the Agent was started from beside this executable.</summary>
|
||||
public long Launches => Interlocked.Read(ref _launches);
|
||||
|
||||
/// <summary>
|
||||
/// Why the last connect attempt failed (<c>TimeoutException: …</c>, <c>UnauthorizedAccessException: …</c>), or null once
|
||||
/// connected. Before 2026-09-17 this was swallowed, and an App refused by the pipe looked exactly like an App with no Agent.
|
||||
/// </summary>
|
||||
public string? LastConnectFailure => _lastFailure;
|
||||
|
||||
/// <summary>Skip the wait before the next round (the banner's Retry).</summary>
|
||||
public void RetryNow() => _retryNow.Release();
|
||||
|
||||
@@ -136,22 +144,32 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable
|
||||
{
|
||||
Set(AgentConnectionState.Connecting, null, null);
|
||||
PipeClient? client = await TryConnectAsync(ct).ConfigureAwait(false);
|
||||
string? running = null;
|
||||
if (client is null && _launcher.CanLaunch && !_holdLaunches)
|
||||
{
|
||||
Set(AgentConnectionState.Starting, null, null);
|
||||
if (_launcher.TryStart())
|
||||
// Never a second Agent (2026-09-17): one that is up and does not answer this App is reported, not duplicated.
|
||||
running = _launcher.RunningAgent;
|
||||
if (running is null)
|
||||
{
|
||||
Interlocked.Increment(ref _launches);
|
||||
client = await TryConnectAsync(ct).ConfigureAwait(false);
|
||||
Set(AgentConnectionState.Starting, null, null);
|
||||
if (_launcher.TryStart())
|
||||
{
|
||||
Interlocked.Increment(ref _launches);
|
||||
client = await TryConnectAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (client is null)
|
||||
{
|
||||
ReportOnce(running is null
|
||||
? $"agent: no connection ({_lastFailure})"
|
||||
: $"agent: no connection ({_lastFailure}); not starting another — {running}");
|
||||
Set(_launcher.CanLaunch ? AgentConnectionState.Offline : AgentConnectionState.Missing, null, null);
|
||||
return;
|
||||
}
|
||||
|
||||
_reported = null;
|
||||
_client = client;
|
||||
try
|
||||
{
|
||||
@@ -181,10 +199,12 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(_options.ConnectTimeout, ct).ConfigureAwait(false);
|
||||
_lastFailure = null;
|
||||
return client;
|
||||
}
|
||||
catch (Exception ex) when (ex is TimeoutException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
_lastFailure = $"{ex.GetType().Name}: {ex.Message}";
|
||||
await client.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -233,6 +253,18 @@ public sealed class AgentConnection : IAgentLink, IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A round's failure, logged when it differs from the last one logged: a refusal every 7 s is one line, not 500 an hour.</summary>
|
||||
private void ReportOnce(string line)
|
||||
{
|
||||
if (string.Equals(line, _reported, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_reported = line;
|
||||
Log.Warning("{Line}", line);
|
||||
}
|
||||
|
||||
private void Set(AgentConnectionState state, HelloAck? hello, StatusAck? status)
|
||||
{
|
||||
lock (_lock)
|
||||
|
||||
@@ -1,17 +1,41 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using FrameLedger.Infrastructure.Startup;
|
||||
using Serilog;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>Starts the Agent beside this executable, as its own process — it must outlive the App (background capture).</summary>
|
||||
/// <remarks>
|
||||
/// Never a second one (2026-09-17): <see cref="RunningAgent"/> probes the data folder's <see cref="AgentInstanceLock"/>,
|
||||
/// and the last Agent this App started is watched until it exits, with its exit code logged — exit
|
||||
/// <see cref="AgentInstanceLock.ExitHeldElsewhere"/> is an Agent that found the folder already claimed.
|
||||
/// </remarks>
|
||||
public sealed class AgentLauncher : IAgentLauncher
|
||||
{
|
||||
private readonly string _dataDirectory;
|
||||
private Task _lastStarted = Task.CompletedTask;
|
||||
|
||||
public AgentLauncher()
|
||||
: this(UiPaths.DataDirectory)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>A launcher that probes <paramref name="dataDirectory"/>'s claim — a test's folder, never the user's.</summary>
|
||||
internal AgentLauncher(string dataDirectory) =>
|
||||
_dataDirectory = dataDirectory ?? throw new ArgumentNullException(nameof(dataDirectory));
|
||||
|
||||
private static string AgentPath => Path.Combine(AppContext.BaseDirectory, "FrameLedger.Agent.exe");
|
||||
|
||||
public bool CanLaunch => File.Exists(AgentPath);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? RunningAgent =>
|
||||
AgentInstanceLock.IsHeld(_dataDirectory) ? $"an Agent already holds {_dataDirectory}"
|
||||
: !_lastStarted.IsCompleted ? "the Agent this App started last is still starting"
|
||||
: null;
|
||||
|
||||
public bool TryStart()
|
||||
{
|
||||
if (!CanLaunch)
|
||||
@@ -19,21 +43,43 @@ public sealed class AgentLauncher : IAgentLauncher
|
||||
return false;
|
||||
}
|
||||
|
||||
Process? started;
|
||||
try
|
||||
{
|
||||
using Process? started = Process.Start(new ProcessStartInfo(AgentPath, "--serve")
|
||||
started = Process.Start(new ProcessStartInfo(AgentPath, "--serve")
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
WorkingDirectory = AppContext.BaseDirectory,
|
||||
});
|
||||
Log.Information("agent: started {Path} --serve (pid {Pid})", AgentPath, started?.Id);
|
||||
return started is not null;
|
||||
}
|
||||
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or IOException)
|
||||
{
|
||||
Log.Warning(ex, "agent: could not start {Path}", AgentPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (started is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// An elevated App starts an elevated Agent: the token is inherited, and it is what 07_IPC §C's owner check is about.
|
||||
Log.Information("agent: started {Path} --serve (pid {Pid}{Elevated})", AgentPath, started.Id,
|
||||
Environment.IsPrivilegedProcess ? ", elevated like this App" : string.Empty);
|
||||
_lastStarted = WatchUntilExitAsync(started);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static async Task WatchUntilExitAsync(Process agent)
|
||||
{
|
||||
using (agent)
|
||||
{
|
||||
int pid = agent.Id;
|
||||
await agent.WaitForExitAsync().ConfigureAwait(false);
|
||||
int code = agent.ExitCode;
|
||||
Log.Information("agent: pid {Pid} exited {Code}{Meaning}", pid, code,
|
||||
code == AgentInstanceLock.ExitHeldElsewhere ? " — another Agent already holds the data folder" : string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,13 @@ public interface IAgentLauncher
|
||||
/// <summary>Whether an Agent executable is beside this one at all.</summary>
|
||||
bool CanLaunch { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Why starting an Agent now would start a SECOND one, or null when none is up: an Agent already holds this user's data
|
||||
/// folder (the logon task's, an earlier App's, a console's), or the one this App started last has not exited and not yet
|
||||
/// claimed it. 2026-09-17: an App that could not connect started one per round, and four recorded every session.
|
||||
/// </summary>
|
||||
string? RunningAgent { get; }
|
||||
|
||||
/// <summary>Start <c>FrameLedger.Agent.exe --serve</c>, detached; false when it could not be started.</summary>
|
||||
bool TryStart();
|
||||
}
|
||||
@@ -13,14 +13,20 @@ namespace FrameLedger.Infrastructure.Ipc;
|
||||
public static class PipeAccessControl
|
||||
{
|
||||
/// <summary>
|
||||
/// <c>D:P(A;;GA;;;<user>)(A;;GA;;;BA)</c> — a protected DACL (no inheritance), full access to the user
|
||||
/// and to Administrators, nothing to anyone else. Not the ACL alone: an administrator of a DIFFERENT account
|
||||
/// passes it and is then refused by <see cref="ClientUserOf"/> against <see cref="CurrentUser"/>.
|
||||
/// <c>O:<user>D:P(A;;GA;;;<user>)(A;;GA;;;BA)</c> — owned by the user, a protected DACL (no inheritance), full
|
||||
/// access to the user and to Administrators, nothing to anyone else. Not the ACL alone: an administrator of a DIFFERENT
|
||||
/// account passes it and is then refused by <see cref="ClientUserOf"/> against <see cref="CurrentUser"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>The owner is stated, not defaulted</b> (2026-09-17). Left out, it is the creating token's default owner, and an
|
||||
/// elevated token's is <c>BUILTIN\Administrators</c> (the log files the elevated Agents of that morning created are owned
|
||||
/// by it; the unelevated ones' by the user) — so a pipe's owner would depend on how its Agent was started, and a client
|
||||
/// checking it would refuse the same user's Agent across elevation.
|
||||
/// </remarks>
|
||||
public static string Sddl(SecurityIdentifier user)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(user);
|
||||
return $"D:P(A;;GA;;;{user.Value})(A;;GA;;;BA)";
|
||||
return $"O:{user.Value}D:P(A;;GA;;;{user.Value})(A;;GA;;;BA)";
|
||||
}
|
||||
|
||||
/// <summary>The self-relative binary form <c>SECURITY_ATTRIBUTES.lpSecurityDescriptor</c> points at.</summary>
|
||||
@@ -55,4 +61,28 @@ public static class PipeAccessControl
|
||||
});
|
||||
return sid;
|
||||
}
|
||||
|
||||
/// <summary>The owner of the pipe <paramref name="pipe"/> is connected to, read from its security descriptor.</summary>
|
||||
public static SecurityIdentifier? OwnerOf(PipeStream pipe)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(pipe);
|
||||
return pipe.GetAccessControl().GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The client's half, run on a connected pipe before anything is written to it: the pipe must be owned by this process's
|
||||
/// token USER. <c>PipeOptions.CurrentUserOnly</c> compares it with the token's default OWNER instead, which an elevated
|
||||
/// token sets to Administrators — so an App started "as administrator" refused the same user's Agent, took the refusal
|
||||
/// for an absent Agent, and started another one on every connect round (2026-09-17, four Agents).
|
||||
/// </summary>
|
||||
/// <exception cref="UnauthorizedAccessException">The pipe is owned by someone else.</exception>
|
||||
public static void RequireOwnedByCurrentUser(SecurityIdentifier? owner, SecurityIdentifier user, string pipeName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(user);
|
||||
if (owner is null || !owner.Equals(user))
|
||||
{
|
||||
throw new UnauthorizedAccessException(
|
||||
$@"\\.\pipe\{pipeName} is owned by {owner?.Value ?? "nobody"}, not by this process's user {user.Value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,9 @@ namespace FrameLedger.Infrastructure.Ipc;
|
||||
|
||||
/// <summary>
|
||||
/// The UI's end of channel C (<c>07_IPC</c> §Client behavior): connect, correlate acks by id, hand events to a
|
||||
/// reader. <c>PipeOptions.CurrentUserOnly</c> makes the client refuse a server that is not owned by its own user,
|
||||
/// the mirror of the server's check on it.
|
||||
/// reader. The client refuses a pipe that is not owned by its own token user — the mirror of the server's check on it —
|
||||
/// through <see cref="PipeAccessControl.RequireOwnedByCurrentUser"/>, not <c>PipeOptions.CurrentUserOnly</c>, whose
|
||||
/// comparison with the token's default owner refused the same user's Agent from an elevated App (2026-09-17).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Backoff and "start the Agent, retry" are the App's (P3 PR-2); this class connects once and reports.
|
||||
@@ -18,6 +19,7 @@ namespace FrameLedger.Infrastructure.Ipc;
|
||||
public sealed class PipeClient : IAsyncDisposable
|
||||
{
|
||||
private readonly NamedPipeClientStream _pipe;
|
||||
private readonly string _pipeName;
|
||||
private readonly Channel<IpcEnvelope> _events = Channel.CreateUnbounded<IpcEnvelope>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true });
|
||||
private readonly ConcurrentDictionary<string, TaskCompletionSource<IpcEnvelope>> _pending = new(StringComparer.Ordinal);
|
||||
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
||||
@@ -29,7 +31,8 @@ public sealed class PipeClient : IAsyncDisposable
|
||||
public PipeClient(string pipeName = IpcProtocol.PipeName)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(pipeName);
|
||||
_pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
|
||||
_pipeName = pipeName;
|
||||
_pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
|
||||
}
|
||||
|
||||
/// <summary>Everything the Agent sent without an id, in order. Completes when the pipe closes.</summary>
|
||||
@@ -39,9 +42,11 @@ public sealed class PipeClient : IAsyncDisposable
|
||||
|
||||
/// <summary>Connect once and start reading; the App's backoff and "start the Agent" live above this.</summary>
|
||||
/// <exception cref="TimeoutException">No server, or both instances busy, within <paramref name="timeout"/>.</exception>
|
||||
/// <exception cref="UnauthorizedAccessException">The pipe is not owned by this process's user; nothing was written to it.</exception>
|
||||
public async Task ConnectAsync(TimeSpan timeout, CancellationToken ct = default)
|
||||
{
|
||||
await _pipe.ConnectAsync((int)timeout.TotalMilliseconds, ct).ConfigureAwait(false);
|
||||
PipeAccessControl.RequireOwnedByCurrentUser(PipeAccessControl.OwnerOf(_pipe), PipeAccessControl.CurrentUser(), _pipeName);
|
||||
_reader = ReadLoopAsync(_lifetime.Token);
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,7 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
/// <summary>Accept until cancelled; every client's tasks end with the token too.</summary>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
var failures = new AcceptFailures(_log);
|
||||
while (true)
|
||||
{
|
||||
await _slots.WaitAsync(ct).ConfigureAwait(false);
|
||||
@@ -96,6 +97,7 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
try
|
||||
{
|
||||
stream = CreateInstance();
|
||||
failures.Recovered();
|
||||
await stream.WaitForConnectionAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
@@ -106,10 +108,10 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or Win32Exception)
|
||||
{
|
||||
_log($"pipe: accept failed: {ex.Message}");
|
||||
TimeSpan wait = failures.Failed(ex);
|
||||
await DisposeQuietlyAsync(stream).ConfigureAwait(false);
|
||||
_slots.Release();
|
||||
await Task.Delay(250, ct).ConfigureAwait(false);
|
||||
await Task.Delay(wait, ct).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -178,9 +180,13 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
_bufferBytes,
|
||||
0,
|
||||
&attributes);
|
||||
// The system error, read at once: CsWin32 0.3.298 declares CreateNamedPipeW without SetLastError, so
|
||||
// GetLastPInvokeError() is whatever an earlier call left there — 0 when measured (2026-09-17). Its own
|
||||
// SetLastError wrappers read GetLastSystemError() at this same point.
|
||||
int error = Marshal.GetLastSystemError();
|
||||
if (handle.IsNull || (nint)handle.Value == -1)
|
||||
{
|
||||
throw new Win32Exception(Marshal.GetLastPInvokeError(), $"CreateNamedPipe({_fullName})");
|
||||
throw new Win32Exception(error, $"CreateNamedPipe({_fullName}): {Marshal.GetPInvokeErrorMessage(error)} (error {error})");
|
||||
}
|
||||
|
||||
var safe = new SafePipeHandle((nint)handle.Value, ownsHandle: true);
|
||||
@@ -255,6 +261,60 @@ public sealed class PipeServer : IIpcEventPublisher, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Failed accepts in a row and the wait before the next: 250 ms doubling to 10 s, logged on the first failure, when the
|
||||
/// error changes, and at 10, 100, 1000… in a row. 2026-09-17: three extra Agents that could not create an instance — the
|
||||
/// name's two were taken — logged "accept failed" every 260 ms for four hours, 2 MB of log each, without the error.
|
||||
/// </summary>
|
||||
private sealed class AcceptFailures(Action<string> log)
|
||||
{
|
||||
private static readonly TimeSpan _floor = TimeSpan.FromMilliseconds(250);
|
||||
private static readonly TimeSpan _ceiling = TimeSpan.FromSeconds(10);
|
||||
|
||||
private long _count;
|
||||
private int _lastError;
|
||||
private TimeSpan _next = _floor;
|
||||
|
||||
/// <summary>Count <paramref name="ex"/>; the result is how long to wait before the next attempt.</summary>
|
||||
public TimeSpan Failed(Exception ex)
|
||||
{
|
||||
_count++;
|
||||
int error = ex is Win32Exception win32 ? win32.NativeErrorCode : ex.HResult & 0xFFFF;
|
||||
if (_count == 1 || error != _lastError || IsPowerOfTen(_count))
|
||||
{
|
||||
log($"pipe: accept failed ({_count} in a row): {ex.Message}; retrying, at most {_ceiling.TotalSeconds:0} s apart");
|
||||
}
|
||||
|
||||
_lastError = error;
|
||||
TimeSpan wait = _next;
|
||||
_next = TimeSpan.FromTicks(Math.Min(_next.Ticks * 2, _ceiling.Ticks));
|
||||
return wait;
|
||||
}
|
||||
|
||||
/// <summary>An instance was created: the streak, if there was one, is over.</summary>
|
||||
public void Recovered()
|
||||
{
|
||||
if (_count > 0)
|
||||
{
|
||||
log($"pipe: accepting again after {_count} failed attempt(s)");
|
||||
}
|
||||
|
||||
_count = 0;
|
||||
_lastError = 0;
|
||||
_next = _floor;
|
||||
}
|
||||
|
||||
private static bool IsPowerOfTen(long n)
|
||||
{
|
||||
while (n >= 10 && n % 10 == 0)
|
||||
{
|
||||
n /= 10;
|
||||
}
|
||||
|
||||
return n == 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One connection: a reader that answers requests, a writer that drains the outbound queue.</summary>
|
||||
private sealed class Client : IDisposable
|
||||
{
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Startup;
|
||||
|
||||
/// <summary>
|
||||
/// One capturing Agent per data folder (2026-09-17): a named mutex in this logon session's namespace, keyed by the
|
||||
/// folder, that <c>--serve</c> and the console's capture verbs claim before logging, rules or the ledger, and that the
|
||||
/// App probes before it starts an Agent. Without it, 0.1.0-beta.1 ran four: an elevated App could not connect to the
|
||||
/// Agent already serving (<c>07_IPC</c> §C), started another on every connect round, and every game launched in the next
|
||||
/// hour was injected, read and recorded by all four.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Held, never waited on.</b> The kernel object lives exactly as long as some process holds a handle to it, so
|
||||
/// "created, not opened" is the claim, and a crashed holder releases it with its handles: there is no abandoned state and
|
||||
/// nothing to clean up.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Across elevation.</b> An Agent started by an elevated App creates the object under an administrator's default
|
||||
/// security, which an unelevated process may not open at all. <see cref="UnauthorizedAccessException"/> therefore means
|
||||
/// "held by someone", never "free". The other direction opens normally.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>The name carries a hash of the folder, not the folder</b>: one key however the path is spelled, and no user path in
|
||||
/// the object namespace. A test's temporary folder is a different key, so a test never collides with an installed Agent.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class AgentInstanceLock : IDisposable
|
||||
{
|
||||
/// <summary>The exit code of an Agent refused because another process holds its data folder.</summary>
|
||||
public const int ExitHeldElsewhere = 10;
|
||||
|
||||
private readonly Mutex _mutex;
|
||||
|
||||
private AgentInstanceLock(Mutex mutex, string name)
|
||||
{
|
||||
_mutex = mutex;
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary><c>Local\FrameLedger.Agent.<32 hex digits></c> for <paramref name="dataDirectory"/>, however it is spelled.</summary>
|
||||
public static string NameFor(string dataDirectory)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(dataDirectory);
|
||||
string folder = Path.TrimEndingDirectorySeparator(Path.GetFullPath(dataDirectory)).ToUpperInvariant();
|
||||
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(folder));
|
||||
return @"Local\FrameLedger.Agent." + Convert.ToHexString(hash, 0, 16);
|
||||
}
|
||||
|
||||
/// <summary>The claim on <paramref name="dataDirectory"/>, or null when another process already holds it.</summary>
|
||||
public static AgentInstanceLock? TryAcquire(string dataDirectory)
|
||||
{
|
||||
string name = NameFor(dataDirectory);
|
||||
Mutex? mutex = null;
|
||||
try
|
||||
{
|
||||
mutex = new Mutex(initiallyOwned: false, name, out bool createdNew);
|
||||
if (!createdNew)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var claim = new AgentInstanceLock(mutex, name);
|
||||
mutex = null;
|
||||
return claim;
|
||||
}
|
||||
catch (Exception ex) when (ex is UnauthorizedAccessException or WaitHandleCannotBeOpenedException)
|
||||
{
|
||||
// Held by an elevated process, or the name is taken by an object that is not a mutex: either way, not ours.
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
mutex?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while any process, this one included, holds the claim on <paramref name="dataDirectory"/>.</summary>
|
||||
public static bool IsHeld(string dataDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Mutex.TryOpenExisting(NameFor(dataDirectory), out Mutex? existing))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
existing.Dispose();
|
||||
return true;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _mutex.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Diagnostics;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Agent.Cli;
|
||||
using FrameLedger.Infrastructure.Startup;
|
||||
|
||||
namespace FrameLedger.Agent.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// One capturing Agent per data folder, in the shipped binary (2026-09-17). While this test holds a temporary folder's
|
||||
/// claim, <c>FrameLedger.Agent.exe --console --data-dir <it> recover</c> exits 10 with one line and creates nothing: the
|
||||
/// claim comes before logging, rules and the ledger. <c>--serve</c> claims the profile folder the same way, and a test must
|
||||
/// never run against that folder, so a capturing console verb stands in for it.
|
||||
/// </summary>
|
||||
public sealed class OneAgentPerDataFolderTests : IDisposable
|
||||
{
|
||||
private static readonly AgentVerb[] _capturing = [AgentVerb.Serve, AgentVerb.Capture, AgentVerb.Launch, AgentVerb.Recover];
|
||||
|
||||
private readonly string _dataDir = Path.Combine(Path.GetTempPath(), "fl-oneagent-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
private static string Agent => Path.Combine(AppContext.BaseDirectory, "FrameLedger.Agent.exe");
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(_dataDir))
|
||||
{
|
||||
Directory.Delete(_dataDir, recursive: true);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ACapturingVerbForAFolderAnotherProcessHoldsExitsBeforeItLogsOrOpensAnything()
|
||||
{
|
||||
File.Exists(Agent).Should().BeTrue("the Agent must be built and copied beside this test");
|
||||
using AgentInstanceLock? held = AgentInstanceLock.TryAcquire(_dataDir);
|
||||
held.Should().NotBeNull("nothing else holds a folder named for this test");
|
||||
|
||||
var start = new ProcessStartInfo(Agent) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (string arg in (string[])["--console", "--data-dir", _dataDir, "recover"])
|
||||
{
|
||||
start.ArgumentList.Add(arg);
|
||||
}
|
||||
|
||||
using Process agent = Process.Start(start)!;
|
||||
Task<string> stdout = agent.StandardOutput.ReadToEndAsync(Ct);
|
||||
string stderr = await agent.StandardError.ReadToEndAsync(Ct).ConfigureAwait(true);
|
||||
await agent.WaitForExitAsync(Ct).ConfigureAwait(true);
|
||||
string output = await stdout.ConfigureAwait(true);
|
||||
|
||||
agent.ExitCode.Should().Be(AgentInstanceLock.ExitHeldElsewhere, "{0}{1}", output, stderr);
|
||||
stderr.Should().Contain("already capturing").And.Contain(_dataDir);
|
||||
Directory.Exists(_dataDir).Should().BeFalse("refused before logging and the ledger: no logs folder, no ledger.db");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OnlyTheVerbsThatInjectReadARingOrFinalizeSessionsClaimTheFolder()
|
||||
{
|
||||
foreach (AgentVerb verb in Enum.GetValues<AgentVerb>())
|
||||
{
|
||||
Program.Captures(verb).Should().Be(_capturing.Contains(verb),
|
||||
"{0}: the capturing verbs claim the folder; the rest run beside a serving Agent, as the App's own --install-task does", verb);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
using System.IO;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.App.Services;
|
||||
using FrameLedger.Application.Ipc;
|
||||
using FrameLedger.Infrastructure.Ipc;
|
||||
using FrameLedger.Infrastructure.Startup;
|
||||
using FrameLedger.Shared.Ipc;
|
||||
|
||||
namespace FrameLedger.App.Tests;
|
||||
@@ -41,6 +43,11 @@ public sealed class AgentConnectionTests : IAsyncDisposable
|
||||
{
|
||||
public bool CanLaunch { get; set; }
|
||||
|
||||
/// <summary>What <see cref="IAgentLauncher.RunningAgent"/> answers: an Agent that is up, whether or not it answers.</summary>
|
||||
public string? Running { get; set; }
|
||||
|
||||
public string? RunningAgent => Running;
|
||||
|
||||
public int Starts { get; private set; }
|
||||
|
||||
public bool TryStart()
|
||||
@@ -215,6 +222,53 @@ public sealed class AgentConnectionTests : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnAgentThatIsUpButDoesNotAnswerIsReportedAndNeverStartedAgain()
|
||||
{
|
||||
// 2026-09-17: an elevated App was refused by the pipe of the Agent already serving, took the refusal for an absent
|
||||
// Agent, and started one per round; four Agents recorded every session four times. Here nothing answers, the launcher
|
||||
// knows an Agent holds the data folder, and a start would bring a server up — so it must never be called.
|
||||
FakeLauncher? launcher = null;
|
||||
launcher = new FakeLauncher(() =>
|
||||
{
|
||||
StartServer();
|
||||
return true;
|
||||
})
|
||||
{ CanLaunch = true, Running = "an Agent already holds the test folder" };
|
||||
AgentConnection c = Start(launcher);
|
||||
|
||||
await WaitForAsync(() => c.Rounds >= 3, "three rounds found no pipe").ConfigureAwait(true);
|
||||
launcher.Starts.Should().Be(0, "one Agent per data folder, however many rounds fail");
|
||||
c.Launches.Should().Be(0);
|
||||
c.LastConnectFailure.Should().StartWith(nameof(TimeoutException), "why the round failed is kept, not swallowed");
|
||||
lock (_seen)
|
||||
{
|
||||
_seen.Should().NotContain(AgentConnectionState.Starting);
|
||||
}
|
||||
|
||||
launcher.Running = null;
|
||||
c.RetryNow();
|
||||
await WaitForAsync(() => c.State == AgentConnectionState.Connected, "that Agent is gone: this App starts one and connects").ConfigureAwait(true);
|
||||
launcher.Starts.Should().Be(1);
|
||||
c.LastConnectFailure.Should().BeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheLauncherSeesAnAgentHoldingItsDataFolderWhoeverStartedIt()
|
||||
{
|
||||
string folder = Path.Combine(Path.GetTempPath(), "fl-launcher-" + Guid.NewGuid().ToString("N"));
|
||||
var launcher = new AgentLauncher(folder);
|
||||
launcher.RunningAgent.Should().BeNull("nothing holds a folder named for this test, and this launcher started nothing");
|
||||
|
||||
using (AgentInstanceLock? held = AgentInstanceLock.TryAcquire(folder))
|
||||
{
|
||||
held.Should().NotBeNull();
|
||||
launcher.RunningAgent.Should().Contain(folder, "the logon task's Agent, a console's or another App's — the claim is the same");
|
||||
}
|
||||
|
||||
launcher.RunningAgent.Should().BeNull("the claim went with its handle");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ALostAgentIsOfflineAndAReturningOneIsConnectedAgain()
|
||||
{
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.IO.Pipes;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using FluentAssertions;
|
||||
@@ -75,11 +77,100 @@ public sealed class PipeServerClientTests : IAsyncDisposable
|
||||
PipeServer server = Start();
|
||||
SecurityIdentifier me = PipeAccessControl.CurrentUser();
|
||||
|
||||
server.SecurityDescriptor.Should().Be($"D:P(A;;GA;;;{me.Value})(A;;GA;;;BA)");
|
||||
server.SecurityDescriptor.Should().Be($"O:{me.Value}D:P(A;;GA;;;{me.Value})(A;;GA;;;BA)");
|
||||
PipeAccessControl.DescriptorBytes(server.SecurityDescriptor).Should().NotBeEmpty("the SDDL must parse into a binary descriptor");
|
||||
server.PipeName.Should().Be(_pipeName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThePipeIsOwnedByThisUserWhateverTheTokensDefaultOwner()
|
||||
{
|
||||
// 2026-09-17: left to default, the owner of an elevated Agent's pipe is Administrators (on CI's elevated runner,
|
||||
// this test's), and a client checking the owner refuses the same user's Agent across elevation.
|
||||
Start();
|
||||
await using var raw = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
|
||||
await raw.ConnectAsync(_timeout, Ct).ConfigureAwait(true);
|
||||
|
||||
PipeAccessControl.OwnerOf(raw).Should().Be(PipeAccessControl.CurrentUser());
|
||||
(await ConnectAsync().ConfigureAwait(true)).IsConnected.Should().BeTrue("the client's own owner check passes");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ATokenThatOwnsAsAdministratorsTrustsItsUsersPipeAndRefusesAnAdministratorsOne()
|
||||
{
|
||||
// The morning of 2026-09-17, as a test: an App started as administrator, whose token's default owner is
|
||||
// Administrators, and the user's Agent, whose pipe the user owns. PipeOptions.CurrentUserOnly compared the two and
|
||||
// refused; the check is the token USER. Only such a token can build the second pipe, which is why this needs one —
|
||||
// CI's runner is elevated; an unelevated run has nothing to show here.
|
||||
using WindowsIdentity identity = WindowsIdentity.GetCurrent();
|
||||
var administrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
|
||||
Assert.SkipUnless(identity.Owner == administrators, "this token's default owner is its user, not Administrators (an unelevated run)");
|
||||
|
||||
(await ConnectToAPipeOwnedByAsync(PipeAccessControl.CurrentUser()).ConfigureAwait(true))
|
||||
.Should().BeNull("the user's own Agent, reached from an elevated App");
|
||||
UnauthorizedAccessException? refused = await ConnectToAPipeOwnedByAsync(administrators).ConfigureAwait(true);
|
||||
refused.Should().NotBeNull("a pipe the user does not own is not the user's Agent, elevated or not");
|
||||
refused!.Message.Should().Contain(administrators.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnInstanceThatCannotBeCreatedIsRetriedWithBackoffAndLoggedOnceWithItsError()
|
||||
{
|
||||
// 2026-09-17: three extra Agents could not create an instance of a name whose limit a fourth had reached, and each
|
||||
// logged "accept failed" every 260 ms for four hours, without the error. Here the first server takes the only instance.
|
||||
Start(maxClients: 1);
|
||||
var lines = new List<string>();
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(Ct);
|
||||
using var second = new PipeServer(new PipeServerOptions { PipeName = _pipeName, MaxClients = 1 },
|
||||
new AgentRequestHandler(_identity, static () => "l1", () => _status), lines.Add);
|
||||
Task running = second.RunAsync(stop.Token);
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(3), Ct).ConfigureAwait(true);
|
||||
await stop.CancelAsync().ConfigureAwait(true);
|
||||
try
|
||||
{
|
||||
await running.ConfigureAwait(true);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
|
||||
lines.Should().ContainSingle("250 ms doubling is four attempts in three seconds, and only the first is logged; the fixed 250 ms loop wrote twelve")
|
||||
.Which.Should().Contain("(error 231)", "ERROR_PIPE_BUSY: the name's instances are all taken");
|
||||
}
|
||||
|
||||
/// <summary>A <see cref="PipeClient"/> against a bare pipe owned by <paramref name="owner"/>: its refusal, or null when it connected.</summary>
|
||||
private async Task<UnauthorizedAccessException?> ConnectToAPipeOwnedByAsync(SecurityIdentifier owner)
|
||||
{
|
||||
string name = _pipeName + ".owned";
|
||||
var security = new PipeSecurity();
|
||||
security.SetOwner(owner);
|
||||
security.AddAccessRule(new PipeAccessRule(PipeAccessControl.CurrentUser(), PipeAccessRights.FullControl, AccessControlType.Allow));
|
||||
NamedPipeServerStream server = NamedPipeServerStreamAcl.Create(
|
||||
name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0, security);
|
||||
await using (server.ConfigureAwait(false))
|
||||
{
|
||||
Task accepted = server.WaitForConnectionAsync(Ct);
|
||||
var client = new PipeClient(name);
|
||||
await using (client.ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(_timeout, Ct).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
return ex;
|
||||
}
|
||||
finally
|
||||
{
|
||||
await accepted.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HelloGetStatusAndPingRoundTripThroughTheRealHandler()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using FluentAssertions;
|
||||
using FrameLedger.Infrastructure.Persistence;
|
||||
using FrameLedger.Infrastructure.Startup;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Tests.Startup;
|
||||
|
||||
/// <summary>
|
||||
/// One capturing Agent per data folder (2026-09-17): the first process to claim a folder holds it, every other claim is
|
||||
/// refused until its handle goes, however the folder is spelled, and another folder is another claim. The folders here are
|
||||
/// named for the test, so an installed Agent's claim on the profile folder is never touched.
|
||||
/// </summary>
|
||||
public sealed class AgentInstanceLockTests
|
||||
{
|
||||
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-claim-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
[Fact]
|
||||
public void TheFirstClaimHoldsTheFolderAndEveryOtherIsRefusedUntilItIsReleased()
|
||||
{
|
||||
AgentInstanceLock.IsHeld(_dir).Should().BeFalse();
|
||||
using (AgentInstanceLock? first = AgentInstanceLock.TryAcquire(_dir))
|
||||
{
|
||||
first.Should().NotBeNull();
|
||||
AgentInstanceLock.IsHeld(_dir).Should().BeTrue();
|
||||
AgentInstanceLock.TryAcquire(_dir).Should().BeNull("a second Agent for the same folder");
|
||||
AgentInstanceLock.TryAcquire(_dir.ToUpperInvariant() + Path.DirectorySeparatorChar).Should().BeNull("the same folder, spelled differently");
|
||||
AgentInstanceLock.IsHeld(_dir + "-elsewhere").Should().BeFalse("another folder is another Agent's");
|
||||
}
|
||||
|
||||
AgentInstanceLock.IsHeld(_dir).Should().BeFalse("the claim goes with its handle, so a crashed Agent leaves nothing behind");
|
||||
using AgentInstanceLock? again = AgentInstanceLock.TryAcquire(_dir);
|
||||
again.Should().NotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheNameLivesInThisSessionsNamespaceAndCarriesAHashNotThePath()
|
||||
{
|
||||
const string prefix = @"Local\FrameLedger.Agent.";
|
||||
string name = AgentInstanceLock.NameFor(_dir);
|
||||
|
||||
name.Should().StartWith(prefix).And.HaveLength(prefix.Length + 32);
|
||||
name.Should().NotContainEquivalentOf("fl-claim");
|
||||
AgentInstanceLock.NameFor(_dir + Path.DirectorySeparatorChar).Should().Be(name);
|
||||
AgentInstanceLock.NameFor(LedgerPaths.DefaultDirectory).Should().NotBe(name, "a test's folder is never the profile's");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user