mxc-sdk 1.1.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Persisted, per-user telemetry consent.
//!
//! See `docs/development/architecture/telemetry-consent-design.md` for the full design and
//! privacy rationale. In short:
//!
//! - MXC does not and must not collect telemetry on any platform other than
//!   Windows, so this module is the **single** consent surface — and it is
//!   compiled out entirely on non-Windows targets, replaced by a stub that
//!   never touches disk and always reports [`ConsentState::NotApplicable`].
//! - On Windows, consent is a per-user choice persisted at
//!   `%LOCALAPPDATA%\mxc\telemetry-consent.json`. The default (no file, or an
//!   unreadable/corrupt one) is [`ConsentState::Undetermined`], which is
//!   treated as "not collecting" everywhere telemetry gating is decided
//!   ([`super::is_enabled`]) — MXC fails closed, never open.
//! - This module never emits a telemetry event for a consent transition
//!   itself; flipping the flag is a silent, local, atomic file write.

// Serde, the persisted record, and its helpers exist only for the Windows
// consent store; the non-Windows stub persists nothing.
#[cfg(target_os = "windows")]
use serde::{Deserialize, Serialize};
use std::fmt;

use super::consent_prompt::{prompt_for_locale, ConsentPrompt};

/// Current schema version for the persisted consent record. Bump when the
/// on-disk shape changes in a way that isn't purely additive; unknown/older
/// versions are treated as [`ConsentState::Undetermined`] on read (fail
/// closed) rather than guessed at.
#[cfg(target_os = "windows")]
const CONSENT_SCHEMA_VERSION: u32 = 2;

/// The user's telemetry consent decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentState {
    /// The user has explicitly agreed to telemetry collection.
    Granted,
    /// The user has explicitly declined telemetry collection.
    Denied,
    /// No decision has been recorded yet (fresh install, or a corrupt/missing
    /// store). Treated identically to `Denied` for gating purposes — the only
    /// difference is that a host application should offer a first-run prompt
    /// when it sees this state.
    Undetermined,
    /// Not a Windows host. MXC does not collect telemetry here, so consent is
    /// not a meaningful concept — hosts must not offer a consent prompt at
    /// all on these platforms.
    NotApplicable,
}

/// Why persisted consent does not currently authorize collection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentStatusReason {
    /// No consent record exists for this user.
    NoRecord,
    /// The consent store could not be read.
    StoreUnreadable,
    /// The consent record was not valid JSON or did not have a recognized
    /// consent value.
    StoreMalformed,
    /// The persisted consent schema is not supported by this build.
    ConsentSchemaUnsupported,
    /// A stored grant predates versioned canonical consent language.
    PromptVersionMissing,
    /// A stored grant references a different canonical prompt version.
    PromptVersionUnsupported,
    /// Telemetry consent is not applicable on this platform.
    NotApplicable,
}

impl ConsentStatusReason {
    /// Stable wire representation used by status APIs and bindings.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NoRecord => "no-record",
            Self::StoreUnreadable => "store-unreadable",
            Self::StoreMalformed => "store-malformed",
            Self::ConsentSchemaUnsupported => "consent-schema-unsupported",
            Self::PromptVersionMissing => "prompt-version-missing",
            Self::PromptVersionUnsupported => "prompt-version-unsupported",
            Self::NotApplicable => "not-applicable",
        }
    }
}

/// Persisted and effective telemetry consent at one point in time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConsentStatus {
    /// Decision found in the consent record, when one could be recovered.
    pub stored_state: ConsentState,
    /// State used by the telemetry gate after validating the record and prompt
    /// version.
    pub effective_state: ConsentState,
    /// Fail-closed reason when the record is absent, invalid, or inapplicable.
    pub reason: Option<ConsentStatusReason>,
}

impl ConsentStatus {
    /// Whether an explicit consent request may offer the canonical prompt.
    pub fn needs_prompt(&self) -> bool {
        matches!(self.effective_state, ConsentState::Undetermined)
    }
}

/// Explicit result returned by a consent presenter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentDecision {
    Yes,
    No,
    Dismissed,
}

/// Result of requesting or withdrawing telemetry consent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsentActionResult {
    Granted,
    Denied,
    Dismissed,
    Withdrawn,
    AlreadyGranted,
    PolicyBlocked,
    NotApplicable,
}

/// Consent action result together with the resulting status and policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConsentActionOutcome {
    pub result: ConsentActionResult,
    pub status: ConsentStatus,
    pub policy: super::policy::PolicyState,
}

/// Failure to present or persist a consent decision.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConsentActionError {
    Presenter(String),
    Persist(String),
}

impl fmt::Display for ConsentActionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Presenter(message) => write!(formatter, "consent presenter failed: {message}"),
            Self::Persist(message) => write!(formatter, "failed to persist consent: {message}"),
        }
    }
}

impl std::error::Error for ConsentActionError {}

impl ConsentState {
    /// Stable, lowercase wire representation used by the CLI flags, the FFI
    /// boundary, and the SDKs. Kept separate from `Debug` so the on-the-wire
    /// strings never drift if the Rust variant names change.
    pub fn as_str(&self) -> &'static str {
        match self {
            ConsentState::Granted => "granted",
            ConsentState::Denied => "denied",
            ConsentState::Undetermined => "undetermined",
            ConsentState::NotApplicable => "not-applicable",
        }
    }

    /// Whether telemetry may be collected under this consent state alone
    /// (still subject to the explicit config kill-switch — see
    /// [`super::is_enabled`]).
    pub fn allows_collection(&self) -> bool {
        matches!(self, ConsentState::Granted)
    }

    /// Whether this consent state represents an absent user decision.
    ///
    /// Policy-blind: this only reflects the stored consent state. Host
    /// applications must use [`needs_consent_prompt`], which also suppresses
    /// the prompt under an administrative block.
    pub fn needs_prompt(&self) -> bool {
        matches!(self, ConsentState::Undetermined)
    }
}

/// Whether a hosting application should offer its own first-run telemetry
/// consent prompt right now.
///
/// This is [`get_consent`]`().`[`needs_prompt`](ConsentState::needs_prompt)`()`
/// additionally suppressed when an administrator has denied telemetry via
/// [`super::policy`]. Prompting under an administrative denial would be asking
/// the user to decide something MXC would then ignore, so the answer there is
/// always `false` — regardless of whether a decision has been recorded.
pub fn needs_consent_prompt() -> bool {
    if super::policy::is_blocked_by_policy() {
        return false;
    }
    get_consent().needs_prompt()
}

/// The on-disk consent record. Additive fields only; `source` and
/// `prompted_mxc_version` are provenance for support/debugging and are never
/// transmitted anywhere.
#[cfg(target_os = "windows")]
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ConsentRecord {
    #[serde(rename = "schemaVersion")]
    schema_version: u32,
    consent: String,
    #[serde(default)]
    source: String,
    #[serde(rename = "promptedMxcVersion", default)]
    prompted_mxc_version: String,
    #[serde(rename = "promptResourceVersion", default)]
    prompt_resource_version: Option<u32>,
    #[serde(rename = "promptLocale", default)]
    prompt_locale: String,
    /// Unix seconds at the time of the last grant/revoke. Debug/support
    /// provenance only — never used for gating — so a plain epoch integer is
    /// enough; `#[serde(default)]` means older or foreign records missing
    /// this field just read back as `0` rather than failing to parse.
    #[serde(rename = "updatedAtEpoch", default)]
    updated_at_epoch: u64,
    /// Monotonic record identity used to reject a stale presenter decision
    /// even when a concurrent writer preserves the effective consent state.
    #[serde(default)]
    revision: u64,
}

/// Returns the current, persisted telemetry consent state.
///
/// Fail-closed: a missing file, an unreadable file, or unparseable JSON resolves
/// to [`ConsentState::Undetermined`]. An unrecognized `schemaVersion`
/// invalidates a stored grant to `Undetermined`, while a stored denial remains
/// denied. Always [`ConsentState::NotApplicable`] on non-Windows platforms,
/// without any filesystem access.
pub fn get_consent() -> ConsentState {
    get_status().effective_state
}

/// Returns persisted and effective consent plus a typed fail-closed reason.
pub fn get_status() -> ConsentStatus {
    platform::read_status()
}

pub(crate) fn local_app_data_dir() -> Option<std::path::PathBuf> {
    platform::local_app_data_dir()
}

#[cfg(test)]
pub(crate) fn set_consent(granted: bool, source: &str) -> Result<(), String> {
    platform::with_store_lock(|| platform::write(granted, source))
}

/// Request telemetry consent through a host-owned presenter.
///
/// The presenter receives the complete canonical resource. Only an explicit
/// [`ConsentDecision::Yes`] returned from this invocation can create a grant.
pub fn request_consent<F>(
    locale: Option<&str>,
    presenter: F,
) -> Result<ConsentActionOutcome, ConsentActionError>
where
    F: FnOnce(&ConsentPrompt) -> Result<ConsentDecision, String>,
{
    let (prompt, policy, status, revision) = match consent_preflight(locale) {
        ConsentPreflight::Complete(outcome) => return Ok(outcome),
        ConsentPreflight::Failed(error) => return Err(ConsentActionError::Persist(error)),
        ConsentPreflight::Present {
            prompt,
            policy,
            status,
            revision,
        } => (prompt, policy, status, revision),
    };

    let decision = presenter(prompt).map_err(ConsentActionError::Presenter)?;
    persist_presented_decision(decision, prompt, policy, status, revision)
}

/// Asynchronous counterpart to [`request_consent`].
///
/// The presenter callback is asynchronous. The surrounding synchronous
/// registry/filesystem work is offloaded to short-lived worker threads so the
/// caller's executor thread does not run the blocking persistence path itself.
pub async fn request_consent_async<F, Fut>(
    locale: Option<&str>,
    presenter: F,
) -> Result<ConsentActionOutcome, ConsentActionError>
where
    F: FnOnce(&ConsentPrompt) -> Fut,
    Fut: std::future::Future<Output = Result<ConsentDecision, String>>,
{
    let locale = locale.map(str::to_owned);
    match BlockingTask::spawn(move || consent_preflight(locale.as_deref())).await {
        ConsentPreflight::Complete(outcome) => Ok(outcome),
        ConsentPreflight::Failed(error) => Err(ConsentActionError::Persist(error)),
        ConsentPreflight::Present {
            prompt,
            policy,
            status,
            revision,
        } => {
            let decision = presenter(prompt)
                .await
                .map_err(ConsentActionError::Presenter)?;
            BlockingTask::spawn(move || {
                persist_presented_decision(decision, prompt, policy, status, revision)
            })
            .await
        }
    }
}

struct BlockingTask<T> {
    shared: std::sync::Arc<BlockingTaskState<T>>,
}

struct BlockingTaskState<T> {
    result: std::sync::Mutex<Option<std::thread::Result<T>>>,
    waker: std::sync::Mutex<Option<std::task::Waker>>,
}

impl<T: Send + 'static> BlockingTask<T> {
    fn spawn(operation: impl FnOnce() -> T + Send + 'static) -> Self {
        let shared = std::sync::Arc::new(BlockingTaskState {
            result: std::sync::Mutex::new(None),
            waker: std::sync::Mutex::new(None),
        });
        let worker = std::sync::Arc::clone(&shared);
        std::thread::spawn(move || {
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation));
            *worker.result.lock().unwrap_or_else(|e| e.into_inner()) = Some(result);
            if let Some(waker) = worker
                .waker
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .take()
            {
                waker.wake();
            }
        });
        Self { shared }
    }
}

impl<T> std::future::Future for BlockingTask<T> {
    type Output = T;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        if let Some(result) = self
            .shared
            .result
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .take()
        {
            return std::task::Poll::Ready(match result {
                Ok(value) => value,
                Err(payload) => std::panic::resume_unwind(payload),
            });
        }

        *self.shared.waker.lock().unwrap_or_else(|e| e.into_inner()) = Some(cx.waker().clone());

        match self
            .shared
            .result
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .take()
        {
            Some(result) => {
                self.shared
                    .waker
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .take();
                std::task::Poll::Ready(match result {
                    Ok(value) => value,
                    Err(payload) => std::panic::resume_unwind(payload),
                })
            }
            None => std::task::Poll::Pending,
        }
    }
}

enum ConsentPreflight {
    Complete(ConsentActionOutcome),
    Failed(String),
    Present {
        prompt: &'static ConsentPrompt,
        policy: super::policy::PolicyState,
        status: ConsentStatus,
        revision: Option<u64>,
    },
}

fn consent_preflight(locale: Option<&str>) -> ConsentPreflight {
    let policy = super::policy::get_policy();
    let (status, revision) = match platform::with_store_lock(|| {
        let status = platform::read_status_unlocked();
        let revision = platform::read_revision_unlocked()?;
        Ok((status, revision))
    }) {
        Ok(snapshot) => snapshot,
        Err(error) => return ConsentPreflight::Failed(error),
    };

    if status.effective_state == ConsentState::NotApplicable {
        return ConsentPreflight::Complete(ConsentActionOutcome {
            result: ConsentActionResult::NotApplicable,
            status,
            policy,
        });
    }
    if !policy.allows_collection() {
        return ConsentPreflight::Complete(ConsentActionOutcome {
            result: ConsentActionResult::PolicyBlocked,
            status,
            policy,
        });
    }
    if status.effective_state == ConsentState::Granted {
        return ConsentPreflight::Complete(ConsentActionOutcome {
            result: ConsentActionResult::AlreadyGranted,
            status,
            policy,
        });
    }

    let prompt = prompt_for_locale(locale);
    ConsentPreflight::Present {
        prompt,
        policy,
        status,
        revision,
    }
}

fn persist_presented_decision(
    decision: ConsentDecision,
    prompt: &ConsentPrompt,
    policy: super::policy::PolicyState,
    status: ConsentStatus,
    revision: Option<u64>,
) -> Result<ConsentActionOutcome, ConsentActionError> {
    platform::with_store_lock(|| {
        let current_policy = super::policy::get_policy();
        let current_status = platform::read_status_unlocked();
        let current_revision = platform::read_revision_unlocked()?;
        if current_status.effective_state == ConsentState::NotApplicable {
            return Ok(ConsentActionOutcome {
                result: ConsentActionResult::NotApplicable,
                status: current_status,
                policy: current_policy,
            });
        }
        if !current_policy.allows_collection() {
            return Ok(ConsentActionOutcome {
                result: ConsentActionResult::PolicyBlocked,
                status: current_status,
                policy: current_policy,
            });
        }
        if current_status.effective_state == ConsentState::Granted
            && !matches!(decision, ConsentDecision::No)
        {
            return Ok(ConsentActionOutcome {
                result: ConsentActionResult::AlreadyGranted,
                status: current_status,
                policy: current_policy,
            });
        }
        let is_concurrent_grant_being_withdrawn = matches!(decision, ConsentDecision::No)
            && current_status.effective_state == ConsentState::Granted
            && status.effective_state != ConsentState::Granted;
        if current_policy != policy
            || ((current_status.effective_state != status.effective_state
                || current_revision != revision)
                && !is_concurrent_grant_being_withdrawn)
        {
            return Err(
                "consent state changed while the presenter was open; no decision was written"
                    .to_string(),
            );
        }

        match decision {
            ConsentDecision::Yes => {
                platform::write_presented(true, "prompt", prompt)?;
                Ok(ConsentActionOutcome {
                    result: ConsentActionResult::Granted,
                    status: platform::read_status_unlocked(),
                    policy: current_policy,
                })
            }
            ConsentDecision::No => {
                platform::write_presented(false, "prompt", prompt)?;
                Ok(ConsentActionOutcome {
                    result: ConsentActionResult::Denied,
                    status: platform::read_status_unlocked(),
                    policy: current_policy,
                })
            }
            ConsentDecision::Dismissed => Ok(ConsentActionOutcome {
                result: ConsentActionResult::Dismissed,
                status: current_status,
                policy: current_policy,
            }),
        }
    })
    .map_err(ConsentActionError::Persist)
}

/// Idempotently withdraw telemetry consent.
///
/// Withdrawal does not require a permitting administrative policy. Off
/// Windows it succeeds as a typed `NotApplicable` result without storage.
pub fn withdraw_consent() -> Result<ConsentActionOutcome, ConsentActionError> {
    #[cfg(not(target_os = "windows"))]
    {
        let current_status = get_status();
        Ok(ConsentActionOutcome {
            result: ConsentActionResult::NotApplicable,
            status: current_status,
            policy: super::policy::get_policy(),
        })
    }

    #[cfg(target_os = "windows")]
    {
        platform::with_store_lock(|| {
            platform::begin_withdrawal()?;
            platform::write(false, "withdrawal")?;
            platform::finish_withdrawal()?;
            Ok(ConsentActionOutcome {
                result: ConsentActionResult::Withdrawn,
                status: platform::read_status_unlocked(),
                policy: super::policy::get_policy(),
            })
        })
        .map_err(ConsentActionError::Persist)
    }
}

/// Current time as Unix seconds. Debug/support provenance only (see
/// [`ConsentRecord::updated_at_epoch`]) — a raw epoch avoids pulling in a
/// date-formatting dependency, or hand-rolling calendar math, just to stamp
/// a field nothing ever gates on.
#[cfg(target_os = "windows")]
fn now_epoch_seconds() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

// ---------------------------------------------------------------------------
// Windows implementation — real, persisted, per-user consent store.
// ---------------------------------------------------------------------------

#[cfg(target_os = "windows")]
mod platform {
    use super::{
        now_epoch_seconds, ConsentRecord, ConsentState, ConsentStatus, ConsentStatusReason,
        CONSENT_SCHEMA_VERSION,
    };
    use crate::mxc_common::telemetry::consent_prompt::{CONSENT_RESOURCE_VERSION, FALLBACK_LOCALE};
    use crate::mxc_common::telemetry::FailureReporter;
    use std::fs;
    use std::io::{Read, Write};
    use std::os::windows::ffi::OsStrExt;
    use std::path::{Path, PathBuf};
    use std::sync::OnceLock;
    use std::time::Duration;

    /// Number of attempts for filesystem operations that can transiently fail
    /// under Windows file-lock contention (AV real-time scanning, the search
    /// indexer, or a concurrent `wxc-exec` grant/revoke in another process).
    const IO_RETRY_ATTEMPTS: u32 = 5;
    #[cfg(test)]
    const IO_RETRY_DELAY: Duration = Duration::ZERO;
    #[cfg(not(test))]
    const IO_RETRY_DELAY: Duration = Duration::from_millis(20);
    /// `ERROR_SHARING_VIOLATION` — another handle holds the file with a
    /// conflicting share mode (AV scanner, indexer, racing sibling process).
    const ERROR_SHARING_VIOLATION: i32 = 32;
    /// `ERROR_LOCK_VIOLATION` — a byte-range lock is held on the file.
    const ERROR_LOCK_VIOLATION: i32 = 33;
    const MAX_CONSENT_FILE_BYTES: u64 = 16 * 1024;
    const WITHDRAWAL_PENDING_FILE: &str = "telemetry-consent.withdrawal-pending";
    const CONSENT_LOCK_FILE: &str = "telemetry-consent.lock";
    const WITHDRAWAL_MARKER_STALE_AFTER: Duration = Duration::from_secs(5);

    fn report_consent_store_failure(signature: String) {
        static FAILURES: OnceLock<FailureReporter> = OnceLock::new();
        FAILURES
            .get_or_init(FailureReporter::default)
            .report(signature, |detail| {
                let stderr = std::io::stderr();
                let mut handle = stderr.lock();
                let _ = writeln!(
                    handle,
                    "mxc: telemetry consent store failure ({detail}); \
                     treating consent as undetermined"
                );
                let _ = handle.flush();
            });
    }

    /// Resolves the per-user `%LocalAppData%` directory through the Windows
    /// known-folder API rather than trusting `LOCALAPPDATA`. A parent process
    /// controls the child's environment, so trusting that variable could
    /// redirect the consent store and forge a grant. The resolved path is
    /// cached for the process, but only after a successful resolution so a
    /// transient failure can be retried later in the same process.
    fn known_folder_local_app_data() -> Option<PathBuf> {
        static CACHED: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
        cache_successful_resolution(&CACHED, resolve_known_folder_local_app_data)
    }

    fn cache_successful_resolution(
        cache: &std::sync::OnceLock<PathBuf>,
        resolver: impl FnOnce() -> Option<PathBuf>,
    ) -> Option<PathBuf> {
        if let Some(cached) = cache.get() {
            return Some(cached.clone());
        }

        let resolved = resolver()?;
        let _ = cache.set(resolved.clone());
        Some(resolved)
    }

    /// Opens the current **process** token with `TOKEN_QUERY | TOKEN_IMPERSONATE`.
    ///
    /// Passing `None` to `SHGetKnownFolderPath` would resolve against the
    /// calling *thread's* token — the impersonated one, if the host has
    /// impersonated another user. That would both invalidate the memoization
    /// above and let an embedding host redirect the consent store simply by
    /// impersonating, which is the same class of attack the known-folder API
    /// is being used to prevent in the first place. Binding explicitly to the
    /// process token keeps the answer a stable property of the process.
    ///
    /// `SHGetKnownFolderPath` requires the token it is handed to be opened
    /// with both `TOKEN_QUERY` *and* `TOKEN_IMPERSONATE` (it duplicates the
    /// handle into an impersonation token internally); on systems that
    /// enforce that contract, a `TOKEN_QUERY`-only handle makes resolution
    /// fail, so consent would always read as `Undetermined` and every
    /// grant/revoke would fail closed.
    fn process_token() -> Option<crate::mxc_common::process_util::OwnedHandle> {
        use windows::Win32::Foundation::HANDLE;
        use windows::Win32::Security::{TOKEN_IMPERSONATE, TOKEN_QUERY};
        use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

        let mut token = HANDLE::default();
        // SAFETY: `GetCurrentProcess` returns a pseudo-handle that needs no
        // release, and `token` is a valid out-pointer for the duration of the
        // call. On success the returned handle is immediately wrapped in
        // `OwnedHandle`, whose `Drop` closes it exactly once.
        unsafe {
            OpenProcessToken(
                GetCurrentProcess(),
                TOKEN_QUERY | TOKEN_IMPERSONATE,
                &mut token,
            )
        }
        .ok()?;
        Some(crate::mxc_common::process_util::OwnedHandle::new(token))
    }

    fn resolve_known_folder_local_app_data() -> Option<PathBuf> {
        use crate::mxc_common::string_util::CoTaskMemPWSTR;
        use windows::Win32::UI::Shell::{
            FOLDERID_LocalAppData, SHGetKnownFolderPath, KF_FLAG_DEFAULT,
        };

        // SAFETY: `FOLDERID_LocalAppData` is a valid, static, well-known GUID
        // constant. The token argument is this process's own token, so the
        // result is independent of any thread impersonation the host may have
        // in effect (see `process_token`); it stays alive for the duration of
        // the call because `token` is still in scope. The returned `PWSTR` is
        // COM-allocated and is immediately wrapped in `CoTaskMemPWSTR`, whose
        // `Drop` frees it via `CoTaskMemFree` exactly once.
        let token = process_token()?;
        let pwstr = unsafe {
            SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, Some(token.get()))
        }
        .ok()?;
        let owned = CoTaskMemPWSTR::new(pwstr.0);
        let resolved = owned.to_string_lossy();
        if resolved.is_empty() {
            None
        } else {
            Some(PathBuf::from(resolved))
        }
    }

    /// Test-only escape hatch so deterministic tests — this crate's own unit
    /// tests, `mxc_ffi`'s Rust tests, and a local `dotnet test`/`npm test` run
    /// against a debug-profile native binary — can redirect the consent store
    /// to a throwaway temp directory.
    ///
    /// Active only under `cfg(test)` (this crate's own test harness, which is
    /// how CI exercises it — CI runs `cargo test --release`, so gating on
    /// `debug_assertions` alone would silently drop every consent test from
    /// CI *and* let them read and overwrite the real store) or in a debug
    /// build (which is what lets `mxc_ffi`'s cross-crate tests, where
    /// `cfg(test)` does not apply to this crate, redirect it).
    ///
    /// Neither condition holds for a binary MXC ships: a release
    /// `wxc-exec.exe` is not compiled with `--test` and has
    /// `debug_assertions` off, so this branch and the env-var read backing it
    /// are compiled out entirely, and a parent process has no way to redirect
    /// the store.
    #[cfg(any(test, all(feature = "test-support", debug_assertions)))]
    fn debug_local_app_data_override() -> Option<PathBuf> {
        crate::mxc_common::telemetry::consent::test_support::current_local_app_data_override()
            .or_else(
            crate::mxc_common::telemetry::consent::test_support::inherited_local_app_data_override,
        )
    }

    pub(super) fn local_app_data_dir() -> Option<PathBuf> {
        #[cfg(any(test, all(feature = "test-support", debug_assertions)))]
        if let Some(over) = debug_local_app_data_override() {
            return Some(over);
        }
        known_folder_local_app_data()
    }

    pub(super) fn with_store_lock<T>(
        operation: impl FnOnce() -> Result<T, String>,
    ) -> Result<T, String> {
        use std::os::windows::fs::OpenOptionsExt;
        use std::os::windows::io::AsRawHandle;
        use windows::Win32::Foundation::HANDLE;
        use windows::Win32::Storage::FileSystem::{
            LockFileEx, FILE_SHARE_READ, FILE_SHARE_WRITE, LOCKFILE_EXCLUSIVE_LOCK,
        };
        use windows::Win32::System::IO::OVERLAPPED;

        let path = consent_file_path().ok_or_else(|| {
            "could not resolve %LocalAppData%; cannot lock telemetry consent".to_string()
        })?;
        let dir = path
            .parent()
            .ok_or_else(|| "invalid telemetry consent path".to_string())?;
        fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
        let lock_path = dir.join(CONSENT_LOCK_FILE);
        let mut options = fs::OpenOptions::new();
        options
            .read(true)
            .write(true)
            .create(true)
            .share_mode(FILE_SHARE_READ.0 | FILE_SHARE_WRITE.0);
        let file = with_io_retry(|| options.open(&lock_path))
            .map_err(|error| format!("failed to open telemetry consent lock: {error}"))?;

        // The persistent file is only the rendezvous point. LockFileEx waits
        // for the current owner instead of making correctness depend on a
        // fixed retry budget under scheduler or filesystem contention.
        // SAFETY: an all-zero `OVERLAPPED` selects byte offset 0 and has no
        // pointer or resource fields that require separate initialization.
        let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
        // SAFETY: `file` owns a valid synchronous handle and remains alive for
        // the lock's lifetime. The call completes synchronously, so the
        // mutable `overlapped` pointer remains valid until LockFileEx returns.
        unsafe {
            LockFileEx(
                HANDLE(file.as_raw_handle()),
                LOCKFILE_EXCLUSIVE_LOCK,
                None,
                u32::MAX,
                u32::MAX,
                &mut overlapped,
            )
        }
        .map_err(|error| format!("failed to lock telemetry consent: {error}"))?;
        let _lock = file;
        operation()
    }

    /// Test-only accessor for [`known_folder_local_app_data`], which is
    /// otherwise private to this module.
    #[cfg(test)]
    pub(super) fn known_folder_local_app_data_for_test() -> Option<PathBuf> {
        known_folder_local_app_data()
    }

    #[cfg(test)]
    pub(super) fn local_app_data_dir_for_test() -> Option<PathBuf> {
        local_app_data_dir()
    }

    #[cfg(test)]
    pub(super) fn cache_successful_resolution_for_test(
        cache: &std::sync::OnceLock<PathBuf>,
        resolver: impl FnOnce() -> Option<PathBuf>,
    ) -> Option<PathBuf> {
        cache_successful_resolution(cache, resolver)
    }

    /// Per-user consent store path: `<LocalAppData>\mxc\telemetry-consent.json`.
    /// Per-user (not `%ProgramData%`) because consent is a personal choice —
    /// multiple people sharing one machine each control their own, with no
    /// elevation required to change it (mirrors `wxc-exec.exe` never
    /// self-elevating).
    fn consent_file_path() -> Option<PathBuf> {
        local_app_data_dir().map(|dir| dir.join("mxc").join("telemetry-consent.json"))
    }

    /// Whether an I/O error is plausibly a *transient* lock/share conflict
    /// worth waiting out, as opposed to a settled answer.
    ///
    /// This distinction is load-bearing for startup latency, not just tidiness:
    /// the overwhelmingly common state is "no consent file yet" (every fresh
    /// install, and every user who has not yet been prompted), which surfaces
    /// as `NotFound`. Retrying that would add `IO_RETRY_ATTEMPTS - 1` sleeps —
    /// 80 ms — to the consent read on the critical path of *every* sandbox
    /// launch, to re-confirm a result that cannot change.
    fn is_transient_io_error(e: &std::io::Error) -> bool {
        if matches!(
            e.raw_os_error(),
            Some(ERROR_SHARING_VIOLATION) | Some(ERROR_LOCK_VIOLATION)
        ) {
            return true;
        }
        matches!(
            e.kind(),
            std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::Interrupted
        )
    }

    /// Retries `op` up to [`IO_RETRY_ATTEMPTS`] times with a short fixed
    /// delay, to ride out transient Windows file-lock contention (AV
    /// scanning, indexing, a racing sibling process) rather than failing the
    /// very first time a lock is briefly held by someone else.
    ///
    /// Only [`is_transient_io_error`] failures are retried; anything else
    /// (notably `NotFound`) is returned immediately.
    fn with_io_retry<T>(mut op: impl FnMut() -> std::io::Result<T>) -> std::io::Result<T> {
        let mut attempt = 0;
        loop {
            match op() {
                Ok(v) => return Ok(v),
                Err(e) if attempt + 1 < IO_RETRY_ATTEMPTS && is_transient_io_error(&e) => {
                    attempt += 1;
                    std::thread::sleep(IO_RETRY_DELAY);
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Test-only accessor for [`with_io_retry`], which is otherwise private
    /// to this module.
    #[cfg(test)]
    pub(super) fn with_io_retry_for_test<T>(
        op: impl FnMut() -> std::io::Result<T>,
    ) -> std::io::Result<T> {
        with_io_retry(op)
    }

    /// Test-only constructor for a synthetic transient error, so retry tests
    /// don't have to guess which raw OS codes this module treats as transient.
    #[cfg(test)]
    pub(super) fn transient_io_error_for_test() -> std::io::Error {
        std::io::Error::from_raw_os_error(ERROR_SHARING_VIOLATION)
    }

    #[cfg(test)]
    pub(super) const IO_RETRY_ATTEMPTS_FOR_TEST: u32 = IO_RETRY_ATTEMPTS;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(super) enum WithdrawalMarkerState {
        Absent,
        Pending,
        Stale,
    }

    fn withdrawal_marker_state(marker: &Path) -> std::io::Result<WithdrawalMarkerState> {
        match with_io_retry(|| fs::metadata(marker)) {
            Ok(metadata) => {
                let is_stale = metadata
                    .modified()
                    .ok()
                    .and_then(|modified| std::time::SystemTime::now().duration_since(modified).ok())
                    .is_some_and(|age| age >= WITHDRAWAL_MARKER_STALE_AFTER);
                Ok(if is_stale {
                    WithdrawalMarkerState::Stale
                } else {
                    WithdrawalMarkerState::Pending
                })
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                Ok(WithdrawalMarkerState::Absent)
            }
            Err(error) => Err(error),
        }
    }

    #[cfg(test)]
    pub(super) fn read_status_unlocked_with_marker_for_test(
        marker_state: std::io::Result<WithdrawalMarkerState>,
    ) -> ConsentStatus {
        read_status_unlocked_inner(
            |_| marker_state,
            recover_stale_withdrawal_marker,
            report_consent_store_failure,
        )
    }

    #[cfg(test)]
    pub(super) fn read_status_unlocked_with_reporter_for_test(
        marker_state: std::io::Result<WithdrawalMarkerState>,
        report: impl FnMut(String),
    ) -> ConsentStatus {
        read_status_unlocked_inner(|_| marker_state, recover_stale_withdrawal_marker, report)
    }

    pub(super) fn read_status() -> ConsentStatus {
        match with_store_lock(|| Ok(read_status_unlocked())) {
            Ok(status) => status,
            Err(error) => {
                report_consent_store_failure(format!("lock consent store: {error}"));
                unreadable_status()
            }
        }
    }

    pub(super) fn read_status_unlocked() -> ConsentStatus {
        read_status_unlocked_inner(
            withdrawal_marker_state,
            recover_stale_withdrawal_marker,
            report_consent_store_failure,
        )
    }

    pub(super) fn read_revision_unlocked() -> Result<Option<u64>, String> {
        let Some(path) = consent_file_path() else {
            return Ok(None);
        };
        Ok(read_record(&path)?.map(|record| record.revision))
    }

    fn read_status_unlocked_inner(
        marker_check: impl FnOnce(&Path) -> std::io::Result<WithdrawalMarkerState>,
        recover_stale: impl FnOnce(&Path, &Path) -> Result<(), String>,
        mut report: impl FnMut(String),
    ) -> ConsentStatus {
        fn no_record_status() -> ConsentStatus {
            ConsentStatus {
                stored_state: ConsentState::Undetermined,
                effective_state: ConsentState::Undetermined,
                reason: Some(ConsentStatusReason::NoRecord),
            }
        }

        let Some(path) = consent_file_path() else {
            report("resolve consent store path".to_string());
            return unreadable_status();
        };
        let Some(dir) = path.parent() else {
            report("resolve consent store parent directory".to_string());
            return unreadable_status();
        };
        let marker_path = dir.join(WITHDRAWAL_PENDING_FILE);
        match marker_check(&marker_path) {
            Ok(WithdrawalMarkerState::Absent) => {}
            Ok(WithdrawalMarkerState::Pending) => {
                return unreadable_status();
            }
            Err(error) => {
                report(format!(
                    "inspect withdrawal marker: kind={:?}, os_error={:?}, error={error}",
                    error.kind(),
                    error.raw_os_error()
                ));
                return unreadable_status();
            }
            Ok(WithdrawalMarkerState::Stale) => {
                if let Err(error) = recover_stale(&path, &marker_path) {
                    report(format!("recover stale withdrawal marker: {error}"));
                    return unreadable_status();
                }
            }
        }
        let data = match with_io_retry(|| read_bounded(&path)) {
            Ok(data) => data,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return no_record_status();
            }
            Err(error) => {
                report(format!(
                    "read consent record: kind={:?}, os_error={:?}, error={error}",
                    error.kind(),
                    error.raw_os_error()
                ));
                return unreadable_status();
            }
        };
        let record = match serde_json::from_str::<ConsentRecord>(&data) {
            Ok(record) => record,
            Err(error) => {
                report(format!("parse consent record: {error}"));
                return malformed_status();
            }
        };

        let stored_state = match record.consent.as_str() {
            "granted" => ConsentState::Granted,
            "denied" => ConsentState::Denied,
            _ => {
                report("validate consent record: unrecognized consent value".to_string());
                return malformed_status();
            }
        };

        if stored_state == ConsentState::Denied {
            return ConsentStatus {
                stored_state,
                effective_state: ConsentState::Denied,
                reason: None,
            };
        }

        if record.schema_version != CONSENT_SCHEMA_VERSION {
            return ConsentStatus {
                stored_state,
                effective_state: ConsentState::Undetermined,
                reason: Some(if record.prompt_resource_version.is_none() {
                    ConsentStatusReason::PromptVersionMissing
                } else {
                    ConsentStatusReason::ConsentSchemaUnsupported
                }),
            };
        }

        match record.prompt_resource_version {
            Some(CONSENT_RESOURCE_VERSION) if record.prompt_locale == FALLBACK_LOCALE => {
                ConsentStatus {
                    stored_state,
                    effective_state: ConsentState::Granted,
                    reason: None,
                }
            }
            Some(CONSENT_RESOURCE_VERSION) => {
                report("validate consent record: unsupported prompt locale".to_string());
                ConsentStatus {
                    stored_state,
                    effective_state: ConsentState::Undetermined,
                    reason: Some(ConsentStatusReason::PromptVersionUnsupported),
                }
            }
            None => ConsentStatus {
                stored_state,
                effective_state: ConsentState::Undetermined,
                reason: Some(ConsentStatusReason::PromptVersionMissing),
            },
            Some(_) => ConsentStatus {
                stored_state,
                effective_state: ConsentState::Undetermined,
                reason: Some(ConsentStatusReason::PromptVersionUnsupported),
            },
        }
    }

    fn unreadable_status() -> ConsentStatus {
        ConsentStatus {
            stored_state: ConsentState::Undetermined,
            effective_state: ConsentState::Undetermined,
            reason: Some(ConsentStatusReason::StoreUnreadable),
        }
    }

    fn malformed_status() -> ConsentStatus {
        ConsentStatus {
            stored_state: ConsentState::Undetermined,
            effective_state: ConsentState::Undetermined,
            reason: Some(ConsentStatusReason::StoreMalformed),
        }
    }

    fn read_bounded(path: &Path) -> std::io::Result<String> {
        let file = fs::File::open(path)?;
        let mut bytes = Vec::new();
        file.take(MAX_CONSENT_FILE_BYTES + 1)
            .read_to_end(&mut bytes)?;
        if bytes.len() as u64 > MAX_CONSENT_FILE_BYTES {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "telemetry consent file exceeds the supported size",
            ));
        }
        String::from_utf8(bytes)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
    }

    fn read_record(path: &Path) -> Result<Option<ConsentRecord>, String> {
        let data = match with_io_retry(|| read_bounded(path)) {
            Ok(data) => data,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => {
                return Err(format!(
                    "failed to read telemetry consent record revision: {error}"
                ));
            }
        };
        Ok(serde_json::from_str(&data).ok())
    }

    fn recover_stale_withdrawal_marker(_path: &Path, marker: &Path) -> Result<(), String> {
        match withdrawal_marker_state(marker)
            .map_err(|e| format!("failed to inspect stale withdrawal marker: {e}"))?
        {
            WithdrawalMarkerState::Absent => Ok(()),
            WithdrawalMarkerState::Pending | WithdrawalMarkerState::Stale => write_record(
                false,
                "withdrawal-recovery",
                Some(CONSENT_RESOURCE_VERSION),
                FALLBACK_LOCALE,
            ),
        }
    }

    /// Best-effort cleanup of a leftover temp file; failures here are not
    /// reported since the operation they were cleaning up after has already
    /// failed (or, on the success path, this is a pure best-effort tidy-up).
    fn remove_best_effort(path: &Path) {
        let _ = fs::remove_file(path);
    }

    pub(super) fn write(granted: bool, source: &str) -> Result<(), String> {
        write_record(
            granted,
            source,
            Some(CONSENT_RESOURCE_VERSION),
            FALLBACK_LOCALE,
        )
    }

    pub(super) fn write_presented(
        granted: bool,
        source: &str,
        prompt: &crate::mxc_common::telemetry::consent_prompt::ConsentPrompt,
    ) -> Result<(), String> {
        write_record(
            granted,
            source,
            Some(prompt.resource_version),
            prompt.locale,
        )
    }

    pub(super) fn begin_withdrawal() -> Result<(), String> {
        let path = consent_file_path().ok_or_else(|| {
            "could not resolve %LocalAppData%; cannot persist telemetry consent".to_string()
        })?;
        let dir = path
            .parent()
            .ok_or_else(|| "invalid telemetry consent path".to_string())?;
        fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
        let marker = dir.join(WITHDRAWAL_PENDING_FILE);
        with_io_retry(|| {
            let mut file = fs::File::create(&marker)?;
            file.write_all(b"pending")?;
            file.sync_all()
        })
        .map_err(|e| format!("failed to durably mark withdrawal pending: {e}"))
    }

    pub(super) fn finish_withdrawal() -> Result<(), String> {
        let path = consent_file_path().ok_or_else(|| {
            "could not resolve %LocalAppData%; cannot persist telemetry consent".to_string()
        })?;
        clear_withdrawal_marker(&path)
    }

    fn write_record(
        granted: bool,
        source: &str,
        prompt_resource_version: Option<u32>,
        prompt_locale: &str,
    ) -> Result<(), String> {
        let path = consent_file_path().ok_or_else(|| {
            "could not resolve %LocalAppData%; cannot persist telemetry consent".to_string()
        })?;
        let dir = path
            .parent()
            .ok_or_else(|| "invalid telemetry consent path".to_string())?;
        fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
        let revision = read_record(&path)?
            .map_or(0, |record| record.revision)
            .checked_add(1)
            .ok_or_else(|| "telemetry consent record revision is exhausted".to_string())?;

        let record = ConsentRecord {
            schema_version: CONSENT_SCHEMA_VERSION,
            consent: if granted { "granted" } else { "denied" }.to_string(),
            source: source.to_string(),
            prompted_mxc_version: crate::mxc_common::telemetry::version().to_string(),
            prompt_resource_version,
            prompt_locale: prompt_locale.to_string(),
            updated_at_epoch: now_epoch_seconds(),
            revision,
        };
        let json = serde_json::to_string_pretty(&record)
            .map_err(|e| format!("failed to serialize telemetry consent record: {e}"))?;

        // Atomic write: write to a *unique* temp file in the same directory
        // (process id + a random suffix, so two concurrent `wxc-exec`
        // grant/revoke invocations never share — and thus never race on —
        // the same temp path), then replace the real path with write-through
        // semantics. A crash
        // mid-write never leaves a torn/corrupt file in place of a
        // previously-valid one; if the rename itself fails, the temp file is
        // removed rather than left behind as a leaked, orphaned artifact.
        let unique = format!("{}-{:x}", std::process::id(), random_suffix());
        let tmp_path = path.with_extension(format!("json.{unique}.tmp"));

        if let Err(e) = with_io_retry(|| {
            let mut file = fs::File::create(&tmp_path)?;
            file.write_all(json.as_bytes())?;
            file.sync_all()
        }) {
            remove_best_effort(&tmp_path);
            return Err(format!("failed to write {}: {e}", tmp_path.display()));
        }
        if let Err(e) = with_io_retry(|| replace_file_write_through(&tmp_path, &path)) {
            remove_best_effort(&tmp_path);
            return Err(format!("failed to finalize {}: {e}", path.display()));
        }
        clear_withdrawal_marker(&path)
    }

    pub(super) fn replace_file_write_through(
        source: &Path,
        destination: &Path,
    ) -> std::io::Result<()> {
        use windows::core::PCWSTR;
        use windows::Win32::Storage::FileSystem::{
            MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
        };

        let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
        let destination: Vec<u16> = destination
            .as_os_str()
            .encode_wide()
            .chain(Some(0))
            .collect();

        // SAFETY: both paths are valid, NUL-terminated UTF-16 buffers that
        // remain alive for the duration of the call.
        unsafe {
            MoveFileExW(
                PCWSTR(source.as_ptr()),
                PCWSTR(destination.as_ptr()),
                MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
            )
        }
        .map_err(windows_error_to_io)
    }

    fn windows_error_to_io(error: windows::core::Error) -> std::io::Error {
        let hresult = error.code().0 as u32;
        let raw_error = if hresult & 0xffff_0000 == 0x8007_0000 {
            (hresult & 0xffff) as i32
        } else {
            hresult as i32
        };
        std::io::Error::from_raw_os_error(raw_error)
    }

    fn clear_withdrawal_marker(path: &Path) -> Result<(), String> {
        let dir = path
            .parent()
            .ok_or_else(|| "invalid telemetry consent path".to_string())?;
        match with_io_retry(|| fs::remove_file(dir.join(WITHDRAWAL_PENDING_FILE))) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(format!("failed to clear withdrawal marker: {e}")),
        }
    }

    /// Returns a process-local unique suffix for a temporary filename.
    fn random_suffix() -> u64 {
        use std::sync::atomic::{AtomicU64, Ordering};
        static NEXT_SUFFIX: AtomicU64 = AtomicU64::new(0);

        NEXT_SUFFIX.fetch_add(1, Ordering::Relaxed)
    }
}

// ---------------------------------------------------------------------------
// Non-Windows stub — no file, no prompt, no pretend consent.
// ---------------------------------------------------------------------------

#[cfg(not(target_os = "windows"))]
mod platform {
    use super::{ConsentState, ConsentStatus, ConsentStatusReason};
    use std::path::PathBuf;

    pub(super) fn with_store_lock<T>(
        operation: impl FnOnce() -> Result<T, String>,
    ) -> Result<T, String> {
        operation()
    }

    pub(super) fn read_status() -> ConsentStatus {
        ConsentStatus {
            stored_state: ConsentState::NotApplicable,
            effective_state: ConsentState::NotApplicable,
            reason: Some(ConsentStatusReason::NotApplicable),
        }
    }

    pub(super) fn local_app_data_dir() -> Option<PathBuf> {
        None
    }

    pub(super) fn read_status_unlocked() -> ConsentStatus {
        read_status()
    }

    pub(super) fn read_revision_unlocked() -> Result<Option<u64>, String> {
        Ok(None)
    }

    #[cfg(test)]
    pub(super) fn write(_granted: bool, _source: &str) -> Result<(), String> {
        Err("telemetry is Windows-only; consent is not applicable on this platform".to_string())
    }

    pub(super) fn write_presented(
        _granted: bool,
        _source: &str,
        _prompt: &crate::mxc_common::telemetry::consent_prompt::ConsentPrompt,
    ) -> Result<(), String> {
        Err("telemetry is Windows-only; consent is not applicable on this platform".to_string())
    }
}

// ---------------------------------------------------------------------------
// Test support — shared with `telemetry::mod`'s `is_enabled` tests so both
// modules can safely mutate the process-global consent-store override
// without racing each other under parallel test execution.
//
// This keeps the debug-only override in process-local test state by default,
// and only stamps `MXC_TEST_LOCALAPPDATA_OVERRIDE` onto an explicit child
// `Command` when a test asks for inheritance. The real `LOCALAPPDATA` variable
// is never touched here, and the override path is compiled out of release
// binaries entirely.
// ---------------------------------------------------------------------------

#[cfg(any(test, all(feature = "test-support", debug_assertions)))]
pub mod test_support {
    use std::path::Path;
    #[cfg(target_os = "windows")]
    use std::path::PathBuf;
    use std::sync::{Mutex, MutexGuard};

    #[cfg(target_os = "windows")]
    const LOCAL_APPDATA_OVERRIDE_ENV: &str = "MXC_TEST_LOCALAPPDATA_OVERRIDE";
    #[cfg(target_os = "windows")]
    const LOCAL_APPDATA_OVERRIDE_OWNER_ENV: &str = "MXC_TEST_LOCALAPPDATA_OVERRIDE_OWNER_PID";

    /// `get_consent`/`set_consent` read the debug-only override, which is
    /// process-global state. Guarded internally by [`LocalAppDataGuard::set`]
    /// so a caller can never forget to hold it — see that type's doc comment.
    /// `pub(crate)` only so the rare test that must mutate the override
    /// directly (bypassing the guard, e.g. to test the "no override set"
    /// fallback path) can still serialize against guard-holding tests.
    pub(crate) static ENV_LOCK: Mutex<()> = Mutex::new(());
    #[cfg(target_os = "windows")]
    static LOCAL_APP_DATA_OVERRIDE: Mutex<Option<PathBuf>> = Mutex::new(None);

    /// Redirects the consent store (Windows only) to a fresh temp directory
    /// for the lifetime of the guard, restoring the previous value on drop.
    /// Acquires and holds [`ENV_LOCK`] for the guard's entire lifetime, so
    /// tests cannot accidentally construct the guard without the lock.
    /// A no-op holder on non-Windows, where consent is `NotApplicable`
    /// regardless — kept as a real (if inert) guard type so callers don't
    /// need `#[cfg]` at every call site.
    pub struct LocalAppDataGuard {
        _lock: MutexGuard<'static, ()>,
        #[cfg(target_os = "windows")]
        previous_override: Option<PathBuf>,
    }

    impl LocalAppDataGuard {
        #[cfg(target_os = "windows")]
        pub fn set(path: &Path) -> Self {
            let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            let previous_override = LOCAL_APP_DATA_OVERRIDE
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .clone();
            *LOCAL_APP_DATA_OVERRIDE
                .lock()
                .unwrap_or_else(|e| e.into_inner()) = Some(path.to_path_buf());
            Self {
                _lock: lock,
                previous_override,
            }
        }

        #[cfg(not(target_os = "windows"))]
        pub fn set(_path: &Path) -> Self {
            let lock = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            Self { _lock: lock }
        }
    }

    #[cfg(all(
        target_os = "windows",
        any(test, all(feature = "test-support", debug_assertions))
    ))]
    pub(crate) fn current_local_app_data_override() -> Option<PathBuf> {
        LOCAL_APP_DATA_OVERRIDE
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    #[cfg(all(
        target_os = "windows",
        any(test, all(feature = "test-support", debug_assertions))
    ))]
    pub(crate) fn inherited_local_app_data_override() -> Option<PathBuf> {
        let path = std::env::var_os(LOCAL_APPDATA_OVERRIDE_ENV)
            .filter(|value| !value.is_empty())
            .map(PathBuf::from)?;
        scoped_local_app_data_override(
            path,
            std::env::var_os(LOCAL_APPDATA_OVERRIDE_OWNER_ENV),
            direct_parent_process_id(),
        )
    }

    #[cfg(all(
        target_os = "windows",
        any(test, all(feature = "test-support", debug_assertions))
    ))]
    fn scoped_local_app_data_override(
        path: PathBuf,
        owner: Option<std::ffi::OsString>,
        parent_process_id: Option<u32>,
    ) -> Option<PathBuf> {
        let owner = owner?.to_str()?.parse::<u32>().ok()?;
        (Some(owner) == parent_process_id).then_some(path)
    }

    #[cfg(all(
        target_os = "windows",
        any(test, all(feature = "test-support", debug_assertions))
    ))]
    fn direct_parent_process_id() -> Option<u32> {
        use windows::Win32::Foundation::CloseHandle;
        use windows::Win32::System::Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
            TH32CS_SNAPPROCESS,
        };

        let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }.ok()?;
        let mut entry = PROCESSENTRY32W {
            dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
            ..Default::default()
        };
        let mut parent = None;
        unsafe {
            if Process32FirstW(snapshot, &mut entry).is_ok() {
                loop {
                    if entry.th32ProcessID == std::process::id() {
                        parent = Some(entry.th32ParentProcessID);
                        break;
                    }
                    if Process32NextW(snapshot, &mut entry).is_err() {
                        break;
                    }
                }
            }
            let _ = CloseHandle(snapshot);
        }
        parent
    }

    #[cfg(all(target_os = "windows", test))]
    pub(crate) fn apply_inherited_override(command: &mut std::process::Command, path: &Path) {
        command.env(LOCAL_APPDATA_OVERRIDE_ENV, path).env(
            LOCAL_APPDATA_OVERRIDE_OWNER_ENV,
            std::process::id().to_string(),
        );
    }

    #[cfg(target_os = "windows")]
    impl Drop for LocalAppDataGuard {
        fn drop(&mut self) {
            *LOCAL_APP_DATA_OVERRIDE
                .lock()
                .unwrap_or_else(|e| e.into_inner()) = self.previous_override.clone();
        }
    }

    #[cfg(all(target_os = "windows", test))]
    mod tests {
        use super::scoped_local_app_data_override;
        use std::path::PathBuf;

        #[test]
        fn inherited_override_requires_direct_parent_owner() {
            let path = PathBuf::from("isolated");
            assert_eq!(
                scoped_local_app_data_override(path.clone(), Some("41".into()), Some(41)),
                Some(path.clone())
            );
            assert_eq!(
                scoped_local_app_data_override(path.clone(), Some("42".into()), Some(41)),
                None
            );
            assert_eq!(
                scoped_local_app_data_override(path.clone(), Some("invalid".into()), Some(41)),
                None
            );
            assert_eq!(scoped_local_app_data_override(path, None, Some(41)), None);
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::test_support::LocalAppDataGuard;
    use super::*;

    fn block_on<F: std::future::Future>(future: F) -> F::Output {
        fn raw_waker() -> std::task::RawWaker {
            fn clone(_: *const ()) -> std::task::RawWaker {
                raw_waker()
            }
            fn wake(_: *const ()) {}
            fn wake_by_ref(_: *const ()) {}
            fn drop(_: *const ()) {}

            std::task::RawWaker::new(
                std::ptr::null(),
                &std::task::RawWakerVTable::new(clone, wake, wake_by_ref, drop),
            )
        }

        let waker = unsafe { std::task::Waker::from_raw(raw_waker()) };
        let mut future = std::pin::pin!(future);
        let mut context = std::task::Context::from_waker(&waker);

        loop {
            match future.as_mut().poll(&mut context) {
                std::task::Poll::Ready(result) => return result,
                std::task::Poll::Pending => std::thread::sleep(std::time::Duration::from_millis(1)),
            }
        }
    }

    #[test]
    fn blocking_task_propagates_worker_panic_without_hanging() {
        struct SignalWaker(std::sync::mpsc::Sender<()>);

        impl std::task::Wake for SignalWaker {
            fn wake(self: std::sync::Arc<Self>) {
                let _ = self.0.send(());
            }

            fn wake_by_ref(self: &std::sync::Arc<Self>) {
                let _ = self.0.send(());
            }
        }

        let (sender, receiver) = std::sync::mpsc::channel();
        let waker = std::task::Waker::from(std::sync::Arc::new(SignalWaker(sender)));
        let mut context = std::task::Context::from_waker(&waker);
        let mut task = std::pin::pin!(BlockingTask::spawn(|| -> () { panic!("worker panic") }));

        let propagated = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            if std::future::Future::poll(task.as_mut(), &mut context).is_pending() {
                receiver
                    .recv_timeout(std::time::Duration::from_secs(10))
                    .expect("blocking task did not wake after its worker panicked");
                let _ = std::future::Future::poll(task.as_mut(), &mut context);
            }
        }))
        .is_err();

        assert!(
            propagated,
            "blocking task did not propagate its worker panic"
        );
    }

    #[test]
    fn consent_state_as_str_is_stable() {
        assert_eq!(ConsentState::Granted.as_str(), "granted");
        assert_eq!(ConsentState::Denied.as_str(), "denied");
        assert_eq!(ConsentState::Undetermined.as_str(), "undetermined");
        assert_eq!(ConsentState::NotApplicable.as_str(), "not-applicable");
    }

    #[test]
    fn only_granted_allows_collection() {
        assert!(ConsentState::Granted.allows_collection());
        assert!(!ConsentState::Denied.allows_collection());
        assert!(!ConsentState::Undetermined.allows_collection());
        assert!(!ConsentState::NotApplicable.allows_collection());
    }

    #[test]
    fn only_undetermined_needs_prompt() {
        assert!(ConsentState::Undetermined.needs_prompt());
        assert!(!ConsentState::Granted.needs_prompt());
        assert!(!ConsentState::Denied.needs_prompt());
        // NotApplicable means "not Windows", where MXC collects nothing and
        // therefore must never ask. Prompting here would be a privacy defect,
        // not merely a redundant dialog.
        assert!(!ConsentState::NotApplicable.needs_prompt());
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn now_epoch_seconds_is_plausible() {
        // Sanity bound: some time after this test was written, and not an
        // absurd far-future value from an overflow/unit bug.
        let secs = now_epoch_seconds();
        assert!(secs > 1_700_000_000, "epoch seconds too small: {secs}");
        assert!(secs < 4_000_000_000, "epoch seconds too large: {secs}");
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn non_windows_is_always_not_applicable_and_write_fails() {
        let _guard = LocalAppDataGuard::set(std::path::Path::new("unused"));
        assert_eq!(get_consent(), ConsentState::NotApplicable);
        assert_eq!(
            request_consent(None, |_| panic!("non-Windows consent must not present"))
                .unwrap()
                .result,
            ConsentActionResult::NotApplicable
        );
        assert_eq!(
            block_on(request_consent_async(None, |_| async {
                panic!("non-Windows async consent must not present")
            }))
            .unwrap()
            .result,
            ConsentActionResult::NotApplicable
        );
        assert_eq!(
            withdraw_consent().unwrap().result,
            ConsentActionResult::NotApplicable
        );
        assert!(set_consent(true, "cli").is_err());
        assert!(set_consent(false, "cli").is_err());
        assert!(
            !needs_consent_prompt(),
            "must never ask for consent where nothing is collected"
        );
    }

    #[cfg(target_os = "windows")]
    mod windows_tests {
        use super::{block_on, LocalAppDataGuard};
        use crate::mxc_common::telemetry::consent::{
            get_consent, get_status, needs_consent_prompt, platform, request_consent,
            request_consent_async, set_consent, withdraw_consent, ConsentActionError,
            ConsentActionResult, ConsentDecision, ConsentState, ConsentStatusReason,
        };

        fn age_withdrawal_marker(store_root: &std::path::Path) {
            let marker = store_root
                .join("mxc")
                .join("telemetry-consent.withdrawal-pending");
            let file = std::fs::OpenOptions::new()
                .write(true)
                .open(&marker)
                .expect("open withdrawal marker");
            let stale_time = std::time::SystemTime::now() - std::time::Duration::from_secs(10);
            file.set_times(std::fs::FileTimes::new().set_modified(stale_time))
                .expect("age withdrawal marker");
        }

        #[test]
        fn needs_consent_prompt_tracks_the_store() {
            let tmp = tempfile::tempdir().unwrap();
            // Also isolates the policy key: `needs_consent_prompt` consults it,
            // so without this the test reads the real machine policy and fails
            // on an administratively managed device.
            let _env =
                crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            assert!(needs_consent_prompt(), "fresh store must prompt");
            set_consent(false, "prompt").unwrap();
            assert!(
                !needs_consent_prompt(),
                "a recorded denial must not re-prompt"
            );
            set_consent(true, "settings-toggle").unwrap();
            assert!(
                !needs_consent_prompt(),
                "a recorded grant must not re-prompt"
            );
        }

        #[test]
        fn needs_consent_prompt_is_suppressed_by_blocking_policy() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(0);
            assert!(
                !needs_consent_prompt(),
                "a blocking policy must suppress a meaningless prompt"
            );
        }

        #[test]
        fn fresh_store_is_undetermined() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            assert_eq!(get_consent(), ConsentState::Undetermined);
        }

        #[test]
        fn store_lock_file_persists_when_released() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let lock_path = tmp.path().join("mxc").join("telemetry-consent.lock");

            platform::with_store_lock(|| {
                assert!(lock_path.exists(), "lock file must exist while held");
                Ok(())
            })
            .expect("acquire store lock");

            assert!(
                lock_path.exists(),
                "lock ownership must not depend on deleting the lock file"
            );
        }

        #[test]
        fn preexisting_unlocked_store_lock_file_can_be_reused() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("telemetry-consent.lock"), []).unwrap();

            set_consent(true, "cli").expect("pre-existing lock file must not block consent writes");

            assert_eq!(get_consent(), ConsentState::Granted);
        }

        #[test]
        fn grant_then_read_round_trips() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            set_consent(true, "cli").expect("grant should succeed");
            assert_eq!(get_consent(), ConsentState::Granted);
        }

        #[test]
        fn deny_then_read_round_trips() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            set_consent(false, "cli").expect("deny should succeed");
            assert_eq!(get_consent(), ConsentState::Denied);
        }

        #[test]
        fn consent_can_be_flipped_repeatedly() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            set_consent(true, "prompt").unwrap();
            assert_eq!(get_consent(), ConsentState::Granted);
            set_consent(false, "settings-toggle").unwrap();
            assert_eq!(get_consent(), ConsentState::Denied);
            set_consent(true, "settings-toggle").unwrap();
            assert_eq!(get_consent(), ConsentState::Granted);
        }

        #[test]
        fn presenter_yes_persists_a_current_version_grant() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);

            let outcome = request_consent(Some("en-US"), |prompt| {
                assert_eq!(
                    prompt.resource_version,
                    crate::mxc_common::telemetry::consent_prompt::CONSENT_RESOURCE_VERSION
                );
                assert_eq!(prompt.locale, "en-US");
                Ok(ConsentDecision::Yes)
            })
            .expect("consent request");

            assert_eq!(outcome.result, ConsentActionResult::Granted);
            assert_eq!(outcome.status.stored_state, ConsentState::Granted);
            assert_eq!(outcome.status.effective_state, ConsentState::Granted);
            assert_eq!(outcome.status.reason, None);
        }

        #[test]
        fn async_presenter_yes_persists_a_current_version_grant() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);

            let outcome = block_on(request_consent_async(Some("en-US"), |prompt| {
                assert_eq!(
                    prompt.resource_version,
                    crate::mxc_common::telemetry::consent_prompt::CONSENT_RESOURCE_VERSION
                );
                assert_eq!(prompt.locale, "en-US");
                async { Ok(ConsentDecision::Yes) }
            }))
            .expect("async consent request");

            assert_eq!(outcome.result, ConsentActionResult::Granted);
            assert_eq!(outcome.status.stored_state, ConsentState::Granted);
            assert_eq!(outcome.status.effective_state, ConsentState::Granted);
            assert_eq!(outcome.status.reason, None);
        }

        #[test]
        fn async_presenter_no_persists_a_denial() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);

            let outcome = block_on(request_consent_async(None, |_| async {
                Ok(ConsentDecision::No)
            }))
            .expect("async denial");

            assert_eq!(outcome.result, ConsentActionResult::Denied);
            assert_eq!(get_consent(), ConsentState::Denied);
        }

        #[test]
        fn async_dismissal_preserves_the_prior_state() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(false, "prompt").unwrap();

            let outcome = block_on(request_consent_async(None, |_| async {
                Ok(ConsentDecision::Dismissed)
            }))
            .expect("async dismissal");

            assert_eq!(outcome.result, ConsentActionResult::Dismissed);
            assert_eq!(get_consent(), ConsentState::Denied);
        }

        #[test]
        fn async_presenter_error_preserves_the_prior_state() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(false, "prompt").unwrap();

            let error = block_on(request_consent_async(None, |_| async {
                Err("host UI failed".to_string())
            }))
            .expect_err("async presenter failure");

            assert_eq!(
                error,
                ConsentActionError::Presenter("host UI failed".to_string())
            );
            assert_eq!(get_consent(), ConsentState::Denied);
        }

        #[test]
        fn async_policy_block_skips_the_presenter() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(0);

            let outcome = block_on(request_consent_async(None, |_| async {
                panic!("blocked policy must not present")
            }))
            .expect("blocked result");

            assert_eq!(outcome.result, ConsentActionResult::PolicyBlocked);
        }

        #[test]
        fn policy_change_while_presenter_is_open_blocks_stale_grant() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);

            let outcome = request_consent(Some("en-US"), |_| {
                env.set_policy_value(0);
                Ok(ConsentDecision::Yes)
            })
            .expect("policy change should produce a typed outcome");

            assert_eq!(outcome.result, ConsentActionResult::PolicyBlocked);
            assert_eq!(outcome.status.effective_state, ConsentState::Undetermined);
            assert_eq!(get_consent(), ConsentState::Undetermined);
        }

        #[test]
        fn consent_change_while_presenter_is_open_rejects_stale_decision() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);

            let error = request_consent(Some("en-US"), |_| {
                set_consent(false, "concurrent-withdrawal").unwrap();
                Ok(ConsentDecision::Yes)
            })
            .expect_err("stale presenter decision must not overwrite a newer denial");

            assert_eq!(
                error,
                ConsentActionError::Persist(
                    "consent state changed while the presenter was open; no decision was written"
                        .to_string()
                )
            );
            assert_eq!(get_consent(), ConsentState::Denied);
        }

        #[test]
        fn same_state_change_while_presenter_is_open_rejects_stale_decision() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(false, "initial-denial").unwrap();

            let error = request_consent(Some("en-US"), |_| {
                set_consent(false, "concurrent-withdrawal").unwrap();
                Ok(ConsentDecision::Yes)
            })
            .expect_err("stale presenter decision must not overwrite a newer denial");

            assert_eq!(
                error,
                ConsentActionError::Persist(
                    "consent state changed while the presenter was open; no decision was written"
                        .to_string()
                )
            );
            assert_eq!(get_consent(), ConsentState::Denied);
            let record =
                std::fs::read_to_string(tmp.path().join("mxc").join("telemetry-consent.json"))
                    .unwrap();
            assert!(record.contains(r#""source": "concurrent-withdrawal""#));
        }

        #[test]
        fn explicit_denial_withdraws_a_concurrent_grant() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);

            let outcome = request_consent(Some("en-US"), |_| {
                set_consent(true, "concurrent-grant").unwrap();
                Ok(ConsentDecision::No)
            })
            .expect("explicit denial should be persisted");

            assert_eq!(outcome.result, ConsentActionResult::Denied);
            assert_eq!(get_consent(), ConsentState::Denied);
        }

        #[test]
        fn explicit_request_can_replace_a_prior_denial() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(false, "prompt").unwrap();

            let outcome = request_consent(None, |_| Ok(ConsentDecision::Yes)).unwrap();

            assert_eq!(outcome.result, ConsentActionResult::Granted);
            assert_eq!(get_consent(), ConsentState::Granted);
        }

        #[test]
        fn dismissed_or_failed_presenter_does_not_rewrite_prior_state() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(false, "prompt").unwrap();

            let dismissed =
                request_consent(None, |_| Ok(ConsentDecision::Dismissed)).expect("dismissal");
            assert_eq!(dismissed.result, ConsentActionResult::Dismissed);
            assert_eq!(get_consent(), ConsentState::Denied);

            let error = request_consent(None, |_| Err("host UI failed".to_string()))
                .expect_err("presenter failure");
            assert_eq!(
                error,
                ConsentActionError::Presenter("host UI failed".to_string())
            );
            assert_eq!(get_consent(), ConsentState::Denied);
        }

        #[test]
        fn policy_block_and_current_grant_skip_the_presenter() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(0);
            let blocked = request_consent(None, |_| panic!("blocked policy must not present"))
                .expect("blocked result");
            assert_eq!(blocked.result, ConsentActionResult::PolicyBlocked);

            env.set_policy_value(3);
            set_consent(true, "prompt").unwrap();
            let granted = request_consent(None, |_| panic!("current grant must not re-present"))
                .expect("already granted result");
            assert_eq!(granted.result, ConsentActionResult::AlreadyGranted);
        }

        #[test]
        fn withdrawal_is_idempotent_and_ignores_blocking_policy() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(true, "prompt").unwrap();
            env.set_policy_value(0);

            for _ in 0..2 {
                let outcome = withdraw_consent().expect("withdrawal");
                assert_eq!(outcome.result, ConsentActionResult::Withdrawn);
                assert_eq!(outcome.status.effective_state, ConsentState::Denied);
            }
        }

        #[test]
        fn withdrawal_reports_the_current_policy_after_waiting_for_the_store_lock() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(true, "prompt").unwrap();

            let outcome = std::thread::scope(|scope| {
                let handle = platform::with_store_lock(|| {
                    let handle = scope.spawn(|| withdraw_consent().expect("withdrawal"));
                    env.set_policy_value(0);
                    Ok(handle)
                })
                .expect("store lock");
                handle.join().unwrap()
            });

            assert_eq!(outcome.result, ConsentActionResult::Withdrawn);
            assert_eq!(outcome.status.effective_state, ConsentState::Denied);
            assert_eq!(
                outcome.policy,
                crate::mxc_common::telemetry::PolicyState::Blocked
            );
        }

        #[test]
        fn consent_read_waits_for_the_store_lock() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            set_consent(true, "prompt").unwrap();

            let (started_tx, started_rx) = std::sync::mpsc::channel();
            let (status_tx, status_rx) = std::sync::mpsc::channel();
            std::thread::scope(|scope| {
                let read_handle = platform::with_store_lock(|| {
                    let handle = scope.spawn(move || {
                        started_tx.send(()).expect("send reader start");
                        status_tx.send(get_status()).expect("send consent status");
                    });
                    started_rx.recv().expect("reader start");
                    assert!(
                        status_rx
                            .recv_timeout(std::time::Duration::from_millis(100))
                            .is_err(),
                        "consent read must wait while a writer owns the store lock"
                    );
                    Ok(handle)
                })
                .expect("store lock");
                read_handle.join().unwrap();
            });
            let status = status_rx.recv().expect("consent status after lock release");
            assert_eq!(status.effective_state, ConsentState::Granted);
        }

        #[test]
        fn store_lock_waits_beyond_the_previous_retry_budget() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let (started_tx, started_rx) = std::sync::mpsc::channel();
            let (result_tx, result_rx) = std::sync::mpsc::channel();

            std::thread::scope(|scope| {
                platform::with_store_lock(|| {
                    scope.spawn(move || {
                        started_tx.send(()).expect("send writer start");
                        result_tx
                            .send(set_consent(true, "cli"))
                            .expect("send writer result");
                    });
                    started_rx.recv().expect("writer start");
                    assert!(
                        result_rx
                            .recv_timeout(std::time::Duration::from_millis(1_100))
                            .is_err(),
                        "the waiting writer must not exhaust a retry budget"
                    );
                    Ok(())
                })
                .expect("store lock");
            });

            result_rx
                .recv()
                .expect("writer result after lock release")
                .expect("waiting writer must acquire the released lock");
            assert_eq!(get_consent(), ConsentState::Granted);
        }

        #[test]
        fn corrupt_file_is_undetermined_not_granted() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("telemetry-consent.json"), "not json at all").unwrap();
            assert_eq!(get_consent(), ConsentState::Undetermined);
        }

        #[test]
        fn oversized_file_is_rejected_without_unbounded_read() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("telemetry-consent.json"),
                vec![b'x'; 16 * 1024 + 1],
            )
            .unwrap();
            let status = get_status();
            assert_eq!(status.effective_state, ConsentState::Undetermined);
            assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
        }

        #[test]
        fn pending_withdrawal_marker_fails_closed() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            platform::begin_withdrawal().unwrap();

            let status = get_status();
            assert_eq!(status.effective_state, ConsentState::Undetermined);
            assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
        }

        #[test]
        fn pending_withdrawal_marker_metadata_errors_fail_closed() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            set_consent(true, "prompt").unwrap();

            let status =
                platform::read_status_unlocked_with_marker_for_test(Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "marker temporarily unreadable",
                )));

            assert_eq!(status.stored_state, ConsentState::Undetermined);
            assert_eq!(status.effective_state, ConsentState::Undetermined);
            assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
        }

        #[test]
        fn swallowed_store_failures_are_reported() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let reports = std::sync::Mutex::new(Vec::new());

            let status = platform::read_status_unlocked_with_reporter_for_test(
                Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "marker temporarily unreadable",
                )),
                |message| {
                    reports
                        .lock()
                        .unwrap_or_else(|error| error.into_inner())
                        .push(message);
                },
            );

            assert_eq!(status.reason, Some(ConsentStatusReason::StoreUnreadable));
            assert_eq!(
                reports
                    .lock()
                    .unwrap_or_else(|error| error.into_inner())
                    .as_slice(),
                [
                    "inspect withdrawal marker: kind=PermissionDenied, os_error=None, error=marker temporarily unreadable"
                ]
            );
        }

        #[test]
        fn malformed_store_is_reported() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("telemetry-consent.json"), "not json at all").unwrap();
            let reports = std::sync::Mutex::new(Vec::new());

            let status = platform::read_status_unlocked_with_reporter_for_test(
                Ok(platform::WithdrawalMarkerState::Absent),
                |message| {
                    reports
                        .lock()
                        .unwrap_or_else(|error| error.into_inner())
                        .push(message);
                },
            );

            assert_eq!(status.reason, Some(ConsentStatusReason::StoreMalformed));
            assert!(
                reports
                    .lock()
                    .unwrap_or_else(|error| error.into_inner())
                    .iter()
                    .any(|message| message.starts_with("parse consent record:")),
                "malformed consent must produce a diagnostic"
            );
        }

        #[test]
        fn successful_grant_repairs_a_stale_withdrawal_marker() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            platform::begin_withdrawal().unwrap();

            let outcome = request_consent(None, |_| Ok(ConsentDecision::Yes)).unwrap();

            assert_eq!(outcome.result, ConsentActionResult::Granted);
            assert_eq!(outcome.status.effective_state, ConsentState::Granted);
            assert_eq!(get_consent(), ConsentState::Granted);
        }

        #[test]
        fn stale_withdrawal_marker_recovers_to_denied() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(true, "prompt").unwrap();
            platform::begin_withdrawal().unwrap();
            age_withdrawal_marker(tmp.path());

            let status = get_status();

            assert_eq!(status.stored_state, ConsentState::Denied);
            assert_eq!(status.effective_state, ConsentState::Denied);
            assert_eq!(status.reason, None);
            assert_eq!(get_consent(), ConsentState::Denied);
            let record =
                std::fs::read_to_string(tmp.path().join("mxc").join("telemetry-consent.json"))
                    .unwrap();
            assert!(record.contains(r#""source": "withdrawal-recovery""#));
            assert!(
                !tmp.path()
                    .join("mxc")
                    .join("telemetry-consent.withdrawal-pending")
                    .exists(),
                "recovery must clear the stale withdrawal marker"
            );
        }

        #[test]
        fn stale_withdrawal_marker_on_denied_record_is_cleared() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(false, "cli").unwrap();
            platform::begin_withdrawal().unwrap();
            age_withdrawal_marker(tmp.path());

            let status = get_status();

            assert_eq!(status.stored_state, ConsentState::Denied);
            assert_eq!(status.effective_state, ConsentState::Denied);
            assert_eq!(status.reason, None);
            assert!(
                !tmp.path()
                    .join("mxc")
                    .join("telemetry-consent.withdrawal-pending")
                    .exists(),
                "recovery must eventually clear a leftover withdrawal marker"
            );
        }

        #[test]
        fn stale_withdrawal_recovery_is_serialized_with_concurrent_writers() {
            let tmp = tempfile::tempdir().unwrap();
            let env = crate::mxc_common::telemetry::test_support::TelemetryTestEnv::new(tmp.path());
            env.set_policy_value(3);
            set_consent(true, "prompt").unwrap();
            platform::begin_withdrawal().unwrap();
            age_withdrawal_marker(tmp.path());

            std::thread::scope(|scope| {
                let (reader, writer) = platform::with_store_lock(|| {
                    let (reader_started_tx, reader_started_rx) = std::sync::mpsc::channel();
                    let (writer_started_tx, writer_started_rx) = std::sync::mpsc::channel();
                    let reader = scope.spawn(move || {
                        reader_started_tx.send(()).unwrap();
                        get_status()
                    });
                    let writer = scope.spawn(move || {
                        writer_started_tx.send(()).unwrap();
                        withdraw_consent().map(|_| ())
                    });
                    reader_started_rx.recv().unwrap();
                    writer_started_rx.recv().unwrap();
                    assert!(
                        !reader.is_finished() && !writer.is_finished(),
                        "recovery and writer must wait for the store lock"
                    );
                    Ok((reader, writer))
                })
                .unwrap();

                let reader_status = reader.join().unwrap();
                writer.join().unwrap().unwrap();
                assert_eq!(reader_status.effective_state, ConsentState::Denied);
                assert_eq!(get_consent(), ConsentState::Denied);
                assert!(!tmp
                    .path()
                    .join("mxc")
                    .join("telemetry-consent.withdrawal-pending")
                    .exists());
            });
        }

        #[test]
        fn unsupported_schema_grant_is_undetermined() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("telemetry-consent.json"),
                r#"{"schemaVersion":999,"consent":"granted"}"#,
            )
            .unwrap();
            assert_eq!(get_consent(), ConsentState::Undetermined);
        }

        #[test]
        fn unsupported_schema_denial_remains_denied() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("telemetry-consent.json"),
                r#"{"schemaVersion":999,"consent":"denied"}"#,
            )
            .unwrap();

            let status = get_status();

            assert_eq!(status.stored_state, ConsentState::Denied);
            assert_eq!(status.effective_state, ConsentState::Denied);
            assert_eq!(status.reason, None);
        }

        #[test]
        fn unsupported_grant_schema_reports_a_typed_reason() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("telemetry-consent.json"),
                r#"{"schemaVersion":999,"consent":"granted","promptResourceVersion":1,"promptLocale":"en-US"}"#,
            )
            .unwrap();

            let status = get_status();

            assert_eq!(status.stored_state, ConsentState::Granted);
            assert_eq!(status.effective_state, ConsentState::Undetermined);
            assert_eq!(
                status.reason,
                Some(ConsentStatusReason::ConsentSchemaUnsupported)
            );
        }

        #[test]
        fn unsupported_prompt_version_reports_a_typed_reason() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("telemetry-consent.json"),
                r#"{"schemaVersion":2,"consent":"granted","promptResourceVersion":999,"promptLocale":"en-US"}"#,
            )
            .unwrap();

            let status = get_status();

            assert_eq!(status.stored_state, ConsentState::Granted);
            assert_eq!(status.effective_state, ConsentState::Undetermined);
            assert_eq!(
                status.reason,
                Some(ConsentStatusReason::PromptVersionUnsupported)
            );
        }

        #[test]
        fn unsupported_prompt_locale_cannot_authorize_collection() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());
            let dir = tmp.path().join("mxc");
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("telemetry-consent.json"),
                r#"{"schemaVersion":2,"consent":"granted","promptResourceVersion":1,"promptLocale":"fr-FR"}"#,
            )
            .unwrap();

            let status = get_status();

            assert_eq!(status.stored_state, ConsentState::Granted);
            assert_eq!(status.effective_state, ConsentState::Undetermined);
            assert_eq!(
                status.reason,
                Some(ConsentStatusReason::PromptVersionUnsupported)
            );
        }

        #[test]
        fn write_through_replace_handles_new_and_existing_records() {
            let tmp = tempfile::tempdir().unwrap();
            let destination = tmp.path().join("telemetry-consent.json");

            for contents in ["first", "replacement"] {
                let source = tmp.path().join(format!("{contents}.tmp"));
                std::fs::write(&source, contents).unwrap();
                platform::replace_file_write_through(&source, &destination).unwrap();
                assert_eq!(std::fs::read_to_string(&destination).unwrap(), contents);
                assert!(!source.exists());
            }
        }

        #[test]
        fn concurrent_grant_revoke_never_corrupts_the_store() {
            // Regression test for the write-race finding: many threads
            // hammering set_consent() against the same redirected store
            // concurrently (the override env var is process-global, so
            // every spawned thread inherits the same redirected path from
            // the outer guard) must never leave a torn/missing file behind;
            // the final state must be a fully-formed, parseable record.
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());

            // Every writer must *succeed*, not merely avoid corrupting the
            // file. Asserting only on the final file's parseability would
            // still pass if 15 of 16 writers lost a temp-name or rename
            // race, which is precisely the failure this fix targets.
            for iteration in 0..10 {
                let results: Vec<Result<(), String>> = std::thread::scope(|scope| {
                    let handles: Vec<_> = (0..16)
                        .map(|i| scope.spawn(move || set_consent(i % 2 == 0, "cli")))
                        .collect();
                    handles.into_iter().map(|h| h.join().unwrap()).collect()
                });
                for (writer, result) in results.iter().enumerate() {
                    assert!(
                        result.is_ok(),
                        "iteration {iteration}, concurrent writer {writer} failed: {result:?}"
                    );
                }

                // Whatever the last writer's outcome was, the store must be
                // Granted or Denied — never Undetermined (which would mean a
                // corrupt/missing file from a torn write).
                let state = get_consent();
                assert!(matches!(
                    state,
                    ConsentState::Granted | ConsentState::Denied
                ));
            }
        }

        /// Pre-versioned grants must be invalidated because they cannot prove
        /// the canonical prompt was shown. A prior denial remains denied.
        #[test]
        fn legacy_records_preserve_provenance_but_require_reconsent_for_grants() {
            for (stored, effective, reason) in [
                (
                    "granted",
                    ConsentState::Undetermined,
                    Some(ConsentStatusReason::PromptVersionMissing),
                ),
                ("denied", ConsentState::Denied, None),
            ] {
                let tmp = tempfile::tempdir().unwrap();
                let _guard = LocalAppDataGuard::set(tmp.path());
                let dir = tmp.path().join("mxc");
                std::fs::create_dir_all(&dir).unwrap();
                std::fs::write(
                    dir.join("telemetry-consent.json"),
                    format!(
                        r#"{{"schemaVersion":1,"consent":"{stored}","source":"prompt","promptedMxcVersion":"0.7.0","updatedAtUtc":"2026-01-02T03:04:05Z"}}"#
                    ),
                )
                .unwrap();
                let status = get_status();
                assert_eq!(
                    status.stored_state,
                    if stored == "granted" {
                        ConsentState::Granted
                    } else {
                        ConsentState::Denied
                    }
                );
                assert_eq!(status.effective_state, effective);
                assert_eq!(status.reason, reason);
            }
        }

        /// `with_io_retry` must ride out transient lock contention but must
        /// not sleep through a settled answer. The `NotFound` case is the
        /// startup-latency one: it is the state of every machine that has
        /// never recorded a decision, on the critical path of every launch.
        #[test]
        fn io_retry_retries_transient_errors_then_succeeds() {
            use crate::mxc_common::telemetry::consent::platform;
            let mut calls = 0;
            let result = platform::with_io_retry_for_test(|| {
                calls += 1;
                if calls < 3 {
                    Err(platform::transient_io_error_for_test())
                } else {
                    Ok(calls)
                }
            });
            assert_eq!(result.unwrap(), 3);
            assert_eq!(calls, 3);
        }

        #[test]
        fn io_retry_gives_up_after_the_attempt_budget() {
            use crate::mxc_common::telemetry::consent::platform;
            let mut calls = 0;
            let result = platform::with_io_retry_for_test(|| {
                calls += 1;
                Err::<(), _>(platform::transient_io_error_for_test())
            });
            assert!(result.is_err());
            assert_eq!(calls, platform::IO_RETRY_ATTEMPTS_FOR_TEST);
        }

        #[test]
        fn io_retry_does_not_retry_not_found() {
            use crate::mxc_common::telemetry::consent::platform;
            let mut calls = 0;
            let result = platform::with_io_retry_for_test(|| {
                calls += 1;
                Err::<(), _>(std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "no consent file",
                ))
            });
            assert!(result.is_err());
            assert_eq!(calls, 1, "NotFound must not be retried");
        }

        #[test]
        fn missing_local_app_data_resolution_falls_back_to_real_known_folder() {
            // With no debug override set, the real per-user known-folder
            // path must still resolve (it always exists on a real Windows
            // profile), so exercise that fallback without touching the real
            // file itself.
            let resolved =
                crate::mxc_common::telemetry::consent::platform::known_folder_local_app_data_for_test();
            assert!(
                resolved.is_some(),
                "known-folder API should resolve a real path"
            );
        }

        #[test]
        fn local_app_data_override_reaches_child_processes() {
            let tmp = tempfile::tempdir().unwrap();
            let _guard = LocalAppDataGuard::set(tmp.path());

            let mut command = std::process::Command::new(std::env::current_exe().unwrap());
            super::super::test_support::apply_inherited_override(&mut command, tmp.path());
            let status = command
                .arg("child_process_local_app_data_override_probe")
                .arg("--nocapture")
                .env("MXC_CHILD_OVERRIDE_PROBE", tmp.path())
                .status()
                .expect("spawn child test probe");

            assert!(status.success(), "child probe failed: {status}");
        }

        #[test]
        fn child_process_local_app_data_override_probe() {
            let Some(expected) = std::env::var_os("MXC_CHILD_OVERRIDE_PROBE") else {
                return;
            };

            assert_eq!(
                platform::local_app_data_dir_for_test(),
                Some(std::path::PathBuf::from(expected))
            );
            assert_eq!(get_status().reason, Some(ConsentStatusReason::NoRecord));
        }

        #[test]
        fn known_folder_resolution_only_caches_successful_results() {
            let cache = std::sync::OnceLock::new();
            let mut calls = 0;

            assert_eq!(
                platform::cache_successful_resolution_for_test(&cache, || {
                    calls += 1;
                    None
                }),
                None
            );
            assert_eq!(
                platform::cache_successful_resolution_for_test(&cache, || {
                    calls += 1;
                    Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Local"))
                }),
                Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Local"))
            );
            assert_eq!(
                platform::cache_successful_resolution_for_test(&cache, || {
                    calls += 1;
                    Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Roaming"))
                }),
                Some(std::path::PathBuf::from(r"C:\Users\test\AppData\Local"))
            );
            assert_eq!(calls, 2, "a failed lookup must not be cached forever");
        }
    }
}