|
| 1 | +# Staged Apply + Verbose Logging Architecture |
| 2 | + |
| 3 | +This document describes the architecture introduced in v0.1.38 that fixed the "every click immediately writes to disk and triggers a UAC prompt" bug from v0.1.37. The key idea: the Settings UI mutates a **draft copy** of `AppConfig`; the live config and `config.json` are untouched until the user explicitly clicks **Apply** or **Save & close**. Cancel (and closing the window without Save) discards the draft. |
| 4 | + |
| 5 | +## Diagram |
| 6 | + |
| 7 | +``` |
| 8 | ++-------------------------------------------------------+ |
| 9 | +| SettingsWindow | |
| 10 | +| | |
| 11 | +| on open: | |
| 12 | +| _config = _store.Load(); | |
| 13 | +| _draft = AppConfigCloner.Clone(_config); -------+----+ |
| 14 | +| | | |
| 15 | +| every row binds to _draft.* references. | | the UI |
| 16 | +| on toggle: row setter writes to _draft, increments | | is fully |
| 17 | +| _pendingCount, logs PREF-STAGE. | | isolated |
| 18 | +| | | from disk |
| 19 | +| Cancel: _suppressSaveOnClose = true; Close() | | and from |
| 20 | +| (nothing committed -- draft discarded) | | the |
| 21 | +| | | background |
| 22 | +| Apply / Save & close: | | monitor |
| 23 | +| AppConfigCloner.CopyInto(_draft, _config); -+ | | until the |
| 24 | +| _store.Save(_config); | | | user |
| 25 | +| CheckDrift + Apply + Verify pass | | | commits. |
| 26 | +| RebaseDraftFromConfig(); | | | |
| 27 | +| LoadGlobals / Services / WindowsAi (...); | | | |
| 28 | ++--------------------------------------------------|----|----| |
| 29 | + | | |
| 30 | ++-------------------+ +--------------------+| | |
| 31 | +| MonitorService | | ConfigStore || | |
| 32 | +| | | || | |
| 33 | +| on each tick: | reads | config.json |<+ | |
| 34 | +| _store.Load() ------> | | | |
| 35 | +| CheckDrift | | |
| 36 | +| (auto-apply if AutoApply) | | |
| 37 | +| | | |
| 38 | +| tracks _lastVerified[settingId] for | | |
| 39 | +| external-reset detection | | |
| 40 | ++-------------------+ +--------------------+ | |
| 41 | + | |
| 42 | ++----------------+ writes verbose lines for | |
| 43 | +| ChangeLogger | every commit, drift, external reset, | |
| 44 | +| | session start, etc. | |
| 45 | +| changes.log |<--------------------------------------+ |
| 46 | ++----------------+ |
| 47 | +``` |
| 48 | + |
| 49 | +## Data shapes |
| 50 | + |
| 51 | +### `AppConfig` (`Models/AppConfig.cs`) |
| 52 | + |
| 53 | +Plain POCO. JSON-serialized to `%APPDATA%\GamerGuardian\config.json`. Fully deep-cloneable via JSON round-trip (that's what `AppConfigCloner.Clone` does). Background components like `MonitorService` keep a reference to the live `_config` instance; that's why `AppConfigCloner.CopyInto(source, target)` exists -- it commits the draft's field values into the existing live reference without breaking the captured pointer. |
| 54 | + |
| 55 | +### `IMonitoredSetting` (`Monitors/IMonitoredSetting.cs`) |
| 56 | + |
| 57 | +```csharp |
| 58 | +public interface IMonitoredSetting |
| 59 | +{ |
| 60 | + string Id { get; } |
| 61 | + IEnumerable<DriftItem> CheckDrift(AppConfig config); |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +One implementation per managed setting kind (`HagsMonitor`, `WindowsServiceMonitor`, `CopilotMonitor`, etc.). `CheckDrift` reads the current OS state and yields `DriftItem` records only when current != desired. Each `DriftItem` carries an `Apply` lambda the runner calls; the lambda is responsible for performing the change (often shelling out to `sc.exe`, `reg.exe`, or AppX cmdlets). |
| 66 | + |
| 67 | +### `DriftItem` (`Models/DriftReport.cs`) |
| 68 | + |
| 69 | +```csharp |
| 70 | +public sealed record DriftItem( |
| 71 | + string SettingId, string DisplayKey, string DisplayLabel, string Description, |
| 72 | + string CurrentValue, string DesiredValue, bool AutoApply, Func<Task> Apply, |
| 73 | + bool RequiresReboot = false, bool IsMonitored = true, |
| 74 | + string RawBefore = "", string RawDesired = ""); |
| 75 | +``` |
| 76 | + |
| 77 | +`RawBefore` / `RawDesired` carry the actual underlying values (registry dwords, sc-start-types, package names) so the log can record both display and raw forms. |
| 78 | + |
| 79 | +### `ApplyResult` (`Models/ApplyResult.cs`) |
| 80 | + |
| 81 | +The verbose record per applied change. Fields the log writes: `SettingId`, `Description`, `Before/Desired/After` (both display + raw), `Mechanism`, `ApplyCommand` (PowerShell), `VerifyCommand` (PowerShell), `ElapsedMs`, `Source` (manual / auto / auto-revert), `SessionId`, `ErrorMessage`, `ExternalResetDetected`, `StickinessCount`. |
| 82 | + |
| 83 | +### `SettingDetails` (`Models/SettingDetails.cs`) |
| 84 | + |
| 85 | +Long-form documentation per setting. Populated in `Services/SettingDocsCatalog`. Rendered to `docs/SETTINGS-REFERENCE.md` by `Services/SettingsReferenceGen` and surfaced in the UI's "Learn more" expander. |
| 86 | + |
| 87 | +## Lifecycle traces |
| 88 | + |
| 89 | +### User opens Settings, toggles a service to Disabled, clicks Apply |
| 90 | + |
| 91 | +1. `SettingsWindow` ctor: `_config = _store.Load(); _draft = AppConfigCloner.Clone(_config);`. |
| 92 | +2. `LoadServices()` populates `ServiceRows` with `ServiceRow` instances whose `_pref` references point at `_draft.Services[name]`. |
| 93 | +3. User clicks the "Disabled" radio. `ServiceRow.DesiredDisabled` setter calls `SetDesired(ServiceTargetState.Disabled)` which mutates `_draft.Services[name].Desired`. Fires `_onPrefChanged` callback. |
| 94 | +4. `SettingsWindow.OnRowPrefChanged` logs `[PREF-STAGE]` to `changes.log` and increments `_pendingCount`. Status text shows "1 pending change." |
| 95 | +5. (Nothing else happens. No disk write. No UAC. Background `MonitorService` still sees the un-modified `_config` via `_store.Load()` on next tick.) |
| 96 | +6. User clicks Apply. `ApplyButton_Click` -> `ApplyChangesAsync(closeAfter: false)`: |
| 97 | + - `PersistFormToDraft()` flushes the form-level controls (LaunchAtStartup, PollSeconds, Theme, PowerPlan combo) into `_draft`. |
| 98 | + - `AppConfigCloner.CopyInto(_draft, _config)` commits the draft. |
| 99 | + - `_store.Save(_config)` writes `config.json`. |
| 100 | + - `CheckDrift` runs against `_config` for every monitor; returns the list of `DriftItem`s the user just caused. |
| 101 | + - `ChangeApplier.ApplyAndVerifyAsync(...)` runs each `Apply` lambda, then re-runs `CheckDrift` to verify. Per-item timings captured. |
| 102 | + - `ChangeLogger.LogApplyResults(results, "manual")` emits the `[APPLY-START]` / per-change record / `[APPLY-END]` lines. |
| 103 | + - `_monitorService.RecordVerifiedApplies(results)` seeds the in-memory `_lastVerified` table so the next background tick can correctly detect external resets without a one-cycle blind spot. |
| 104 | + - `RebaseDraftFromConfig()` re-clones `_config` into a fresh `_draft` and resets `_pendingCount`. |
| 105 | + - UI rebuilds rows from the new `_draft`. `ApplyResultsWindow.Show(...)` displays the per-change verify result. |
| 106 | + |
| 107 | +### User clicks Save & close after a successful Apply |
| 108 | + |
| 109 | +1. `SaveButton_Click`: `if (_pendingCount == 0) { Close(); return; }`. |
| 110 | +2. Because the previous Apply rebased the draft and reset the pending count, this guard short-circuits. No drift check, no UAC, just close. |
| 111 | + |
| 112 | +### Background tick auto-applies a drifted setting and detects an external reset |
| 113 | + |
| 114 | +1. `MonitorService.TickAsync` runs every `PollIntervalSeconds`. Loads `_config` from disk and runs `CheckDrift` for every monitor. |
| 115 | +2. For each `DriftItem` where `_lastVerified` has an entry, that's by definition an external reset (Windows or another tool changed a value we'd previously applied). `_stickiness[settingId]` is incremented and `[EXTRESET]` is logged. |
| 116 | +3. `auto` (the subset with `AutoApply == true` and not in the 15-minute backoff window) is split into `corrective` (settings with EXTRESET) and `initial`. |
| 117 | +4. Each gets its own session id. Corrective applies log as `source=auto-revert` with `ExternalResetDetected = true` and the current stickiness count, so a single `grep '\[EXTRESET'` / `grep 'auto-revert'` answers "what does Windows keep undoing, and what's GamerGuardian doing about it?" |
| 118 | +5. Verification failures move the setting into the 15-minute backoff so a stubborn setting doesn't pop UAC every 30 seconds. |
| 119 | + |
| 120 | +## Log schema (`changes.log`) |
| 121 | + |
| 122 | +| Marker | Written by | Meaning | |
| 123 | +|---|---|---| |
| 124 | +| `[SESSION ]` | `ChangeLogger.LogSessionStart` | App started. Includes version, OS, CLR, machine, user (elevated y/n), PID, config path. | |
| 125 | +| `[PREF-STAGE]` | `OnRowPrefChanged` | User toggled a draft preference. Not applied yet. | |
| 126 | +| `[APPLY-START]` | `LogApplyResults` | A batch of changes is about to apply. Includes session id, source, count. | |
| 127 | +| `[manual ]` etc. per-record | `LogApplyResults` | One verbose entry per change. Multi-line: settingId, location, before/desired/after, applyCmd, verifyCmd, elapsedMs, status. | |
| 128 | +| `[APPLY-END ]` | `LogApplyResults` | Same session id. Includes `verified=N/M` summary and total elapsed ms. | |
| 129 | +| `[EXTRESET ]` | `LogExternalReset` | Windows or another tool changed a value we'd previously applied. Includes how long the previous applied value held and the current stickiness count. | |
| 130 | +| `[PAUSE ]` | `LogPauseEvent` | MonitorService entered or left a paused state (fullscreen, benchmark, user manual). | |
| 131 | +| `[MEM ]` | `LogMemorySnapshot` | Periodic process memory snapshot. | |
| 132 | + |
| 133 | +Source tags on per-change records: |
| 134 | + |
| 135 | +| Source | Origin | |
| 136 | +|---|---| |
| 137 | +| `manual` | User clicked Apply or Save & close. | |
| 138 | +| `auto` | Background MonitorService tick auto-applied a setting that had drifted and had no prior verified state (i.e. first time we've seen it drift). | |
| 139 | +| `auto-revert` | Background tick auto-applied a setting Windows had externally reset (an EXTRESET line was logged immediately before). | |
| 140 | + |
| 141 | +## Settings-reference doc |
| 142 | + |
| 143 | +`docs/SETTINGS-REFERENCE.md` is **generated** from `Services/SettingDocsCatalog`. To regenerate: |
| 144 | + |
| 145 | +```pwsh |
| 146 | +dotnet build src/GamerGuardian/GamerGuardian.csproj -c Debug |
| 147 | +.\src\GamerGuardian\bin\Debug\net8.0-windows10.0.22000.0\GamerGuardian.exe --gen-docs docs\SETTINGS-REFERENCE.md |
| 148 | +``` |
| 149 | + |
| 150 | +A unit test in `tests/GamerGuardian.Tests/SettingsReferenceGenTests.cs` asserts the committed file matches the generated output -- so the doc and the catalog can't drift apart silently. |
| 151 | + |
| 152 | +## File map |
| 153 | + |
| 154 | +| Concern | File | |
| 155 | +|---|---| |
| 156 | +| Deep clone / commit | `Services/AppConfigCloner.cs` | |
| 157 | +| Per-setting docs (data) | `Models/SettingDetails.cs` | |
| 158 | +| Per-setting docs (content) | `Services/SettingDocsCatalog.cs` | |
| 159 | +| Markdown rendering | `Services/SettingsReferenceGen.cs` | |
| 160 | +| Apply orchestration | `Services/ChangeApplier.cs` | |
| 161 | +| Verbose logger | `Services/ChangeLogger.cs` | |
| 162 | +| Background monitor + external-reset detection | `Services/MonitorService.cs` | |
| 163 | +| One-line mechanism / verify / apply PowerShell | `Services/SettingDocs.cs` | |
| 164 | +| Draft UI + Apply/Save&close/Cancel | `UI/SettingsWindow.xaml.cs` | |
| 165 | +| Verbose per-change result UI | `UI/ApplyResultsWindow.xaml.cs` | |
0 commit comments