car-secrets 0.53.0

Cross-platform secret store for Common Agent Runtime
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
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
//! Cross-platform secret store for Common Agent Runtime.
//!
//! Unifies OS-native secure storage across the three platforms CAR targets:
//!
//! - **macOS** — `/usr/bin/security` over Keychain Services
//! - **Windows** — Credential Manager (DPAPI)
//! - **Linux** — Secret Service (GNOME Keyring / KWallet / KeePassXC /
//!   anything else that speaks `org.freedesktop.secrets`)
//!
//! The API is intentionally small: `put`, `publish`, `get`, `delete`, `status`,
//! `list`. Callers choose a namespace (`service`) and a key (`account`); values
//! are UTF-8 strings. JSON helpers are provided for structured values.
//!
//! # Availability
//!
//! On headless Linux without a Secret Service daemon, `put`/`get`/`delete`
//! return [`SecretError::Unavailable`]. This is explicit: there is no silent
//! plaintext fallback. Callers should probe [`is_available`] before relying on
//! the store, or handle `Unavailable` with their own fallback.
//!
//! # Security boundary
//!
//! Secrets never enter CAR memory, state, or prompt context unless a caller
//! explicitly reads them and passes them into one of those systems. The store
//! treats a missing backend as a hard error so misconfigured environments are
//! loud, not silently insecure.

// The in-process keyring path is every platform except macOS. macOS routes
// every operation — reads, writes, status, deletes, and the availability
// probe — through `/usr/bin/security` instead, so nothing there opens an
// `Entry` (Parslee-ai/car#897).
#[cfg(not(target_os = "macos"))]
use keyring::Entry;
use serde::{Deserialize, Serialize};
use thiserror::Error;

pub mod secure_path;
pub use secure_path::{
    atomic_replace_private_file, create_private_file, create_private_file_with_failure_injector,
    ensure_private_dir, ensure_private_dir_with_failure_injector, harden_owner_only,
    harden_owner_only_fallible, harden_private_tree, open_private_append,
    open_private_append_with_failure_injector, open_private_read, open_private_truncate,
    revalidate_private_file, revalidate_private_path, PrivatePathDurabilityFailureInjector,
    PrivatePathDurabilityFailurePoint, PrivateTree, PrivateTreePolicy, PrivateTreeReport,
};

/// Default service (namespace) used when callers don't supply one.
///
/// `"car"` is the per-app namespace shared by every CAR component
/// (`car-cli`, `car-inference` model-key fallback, FFI bindings, WebSocket
/// `secret.*` methods). One shared bucket means `car secrets put OPENAI_API_KEY`
/// stores the same entry that `car-inference` reads at runtime — no namespace
/// translation in users' heads.
///
/// Pre-v0.5.2 this was `"car-runtime"`. The rename was a one-time UX change;
/// any keychain entries written before that date live under the old service
/// name and need to be migrated (or just `car secrets put` again).
pub const DEFAULT_SERVICE: &str = "car";

/// Daemon-owned connection credentials and proof metadata. The raw
/// [`SecretStore`] remains able to lease/delete these entries internally;
/// generic CLI/FFI/RPC wrappers must reject access to the root slots and any
/// platform-derived chunk entries.
pub const OPENROUTER_OAUTH_KEY: &str = "OPENROUTER_OAUTH_API_KEY";
pub const PARSLEE_ACCESS_TOKEN_KEY: &str = "PARSLEE_ACCESS_TOKEN";
pub const PARSLEE_REFRESH_TOKEN_KEY: &str = "PARSLEE_REFRESH_TOKEN";
pub const PARSLEE_EXPIRES_AT_KEY: &str = "PARSLEE_ACCESS_TOKEN_EXPIRES_AT";
pub const PARSLEE_API_BASE_KEY: &str = "PARSLEE_API_BASE";
pub const PARSLEE_ACCOUNTS_KEY: &str = "PARSLEE_ACCOUNTS";
pub const PARSLEE_TOKENS_PREFIX: &str = "PARSLEE_TOKENS_";
pub const PARSLEE_AUTH_GENERATION_KEY: &str = "PARSLEE_AUTH_GENERATION";
pub const PARSLEE_AUTH_COMPLETION_KEY: &str = "PARSLEE_AUTH_COMPLETION";
pub const PARSLEE_ACTIVE_ACCOUNT_ID_KEY: &str = "PARSLEE_ACTIVE_ACCOUNT_ID";
pub const PARSLEE_AUTH_STATE_V2_KEY: &str = "PARSLEE_AUTH_STATE_V2";

fn is_private_chunk_derivative(key: &str, root: &str) -> bool {
    key.strip_prefix(root)
        .is_some_and(|suffix| suffix.starts_with("#chunk"))
}

pub fn is_daemon_private_secret(service: &str, key: &str) -> bool {
    service == DEFAULT_SERVICE
        && (matches!(
            key,
            OPENROUTER_OAUTH_KEY
                | PARSLEE_ACCESS_TOKEN_KEY
                | PARSLEE_REFRESH_TOKEN_KEY
                | PARSLEE_EXPIRES_AT_KEY
                | PARSLEE_API_BASE_KEY
                | PARSLEE_ACCOUNTS_KEY
                | PARSLEE_AUTH_GENERATION_KEY
                | PARSLEE_AUTH_COMPLETION_KEY
                | PARSLEE_ACTIVE_ACCOUNT_ID_KEY
                | PARSLEE_AUTH_STATE_V2_KEY
        ) || key.starts_with(PARSLEE_TOKENS_PREFIX)
            || [
                OPENROUTER_OAUTH_KEY,
                PARSLEE_ACCESS_TOKEN_KEY,
                PARSLEE_REFRESH_TOKEN_KEY,
                PARSLEE_EXPIRES_AT_KEY,
                PARSLEE_API_BASE_KEY,
                PARSLEE_ACCOUNTS_KEY,
                PARSLEE_AUTH_GENERATION_KEY,
                PARSLEE_AUTH_COMPLETION_KEY,
                PARSLEE_ACTIVE_ACCOUNT_ID_KEY,
                PARSLEE_AUTH_STATE_V2_KEY,
            ]
            .iter()
            .any(|root| is_private_chunk_derivative(key, root)))
}

/// Resolve a raw key value for `env_var` from the standard CAR
/// sources, in priority order:
///
/// 1. **Process env var** — `std::env::var(env_var)`. Wins
///    everything (containers, CI, K8s pods, systemd units).
///    `~/.car/env` is loaded into the process env at server
///    startup, so file-based config flows through this path too.
/// 2. **OS keychain via [`SecretStore`]** — looked up under
///    [`DEFAULT_SERVICE`] = `"car"` with account = `env_var`.
///    Skipped silently when [`SecretStore::is_available`] is
///    false so we never wake pinentry on a locked desktop or
///    dial DBus on a headless Linux box.
/// 3. **Missing** — returns `None`.
///
/// This is the single source of truth for CAR's API-key
/// resolution. Every call site that wants "env first, then
/// keychain" should go through here so the priority can't drift
/// (`car-inference::key_pool`, `car-voice::elevenlabs_*`, and
/// any future remote backend land here, not on their own
/// re-implementation).
pub fn resolve_env_or_keychain(env_var: &str) -> Option<String> {
    if let Ok(v) = std::env::var(env_var) {
        if !v.is_empty() {
            return Some(v);
        }
    }
    let store = SecretStore::new();
    if !store.is_available() {
        return None;
    }
    let secret_ref = SecretRef::new(DEFAULT_SERVICE, env_var);
    match store.get(&secret_ref) {
        Ok(v) if !v.is_empty() => {
            tracing::debug!(env_var = %env_var, "resolved API key from OS keychain");
            Some(v)
        }
        Ok(_) => None, // empty value — treat as missing
        Err(SecretError::NotFound { .. }) => None,
        Err(e) => {
            tracing::warn!(env_var = %env_var, error = %e, "keychain lookup failed");
            None
        }
    }
}

/// Errors the secret store can produce.
#[derive(Debug, Error)]
pub enum SecretError {
    /// No OS backend is available (e.g. headless Linux with no Secret
    /// Service daemon, or a keychain that refused to unlock).
    #[error("secret store unavailable: {0}")]
    Unavailable(String),

    /// The requested entry does not exist.
    #[error("no entry for service={service:?} key={key:?}")]
    NotFound { service: String, key: String },

    /// The OS credential store refused access to an existing item.
    #[error("secret store access denied: {message}")]
    AccessDenied { message: String },

    /// The user dismissed the OS credential prompt without granting access.
    #[error("secret store access cancelled: {message}")]
    UserCancelled { message: String },

    /// The bounded OS credential helper did not complete before its deadline.
    #[error("secret store helper timed out during {operation}")]
    HelperTimedOut { operation: String },

    /// An OS-native error the store couldn't classify — usually surfaced
    /// verbatim from the underlying keychain API.
    #[error("secret store error: {0}")]
    Backend(String),

    /// A JSON helper was used but the stored value wasn't valid JSON.
    #[error("stored value is not valid JSON: {0}")]
    InvalidJson(String),
}

/// Status of an entry — no value data, safe to log.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecretStatus {
    pub service: String,
    pub key: String,
    pub exists: bool,
}

/// Result of `SecretStore::availability` — `available` mirrors what
/// `is_available` returns, and `reason` carries the platform-specific
/// detail (e.g. "no Secret Service daemon", "keychain locked") so the
/// FFI surface can report an actionable message instead of a bare
/// boolean.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AvailabilityCheck {
    pub available: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Process-lifetime counts of secret-store operation attempts.
///
/// This is deliberately aggregate-only: it contains no service, key,
/// credential identity, filesystem path, or secret value.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecretStoreActivity {
    pub get_attempts: u64,
    pub status_attempts: u64,
    pub availability_attempts: u64,
    pub write_attempts: u64,
    pub delete_attempts: u64,
}

static GET_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static STATUS_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static AVAILABILITY_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static WRITE_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static DELETE_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// Snapshot the process-lifetime aggregate secret-store counters.
pub fn secret_store_activity() -> SecretStoreActivity {
    use std::sync::atomic::Ordering;

    SecretStoreActivity {
        get_attempts: GET_ATTEMPTS.load(Ordering::Relaxed),
        status_attempts: STATUS_ATTEMPTS.load(Ordering::Relaxed),
        availability_attempts: AVAILABILITY_ATTEMPTS.load(Ordering::Relaxed),
        write_attempts: WRITE_ATTEMPTS.load(Ordering::Relaxed),
        delete_attempts: DELETE_ATTEMPTS.load(Ordering::Relaxed),
    }
}

/// Logical handle for a secret — (service, key) pair.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SecretRef {
    pub service: String,
    pub key: String,
}

impl SecretRef {
    pub fn new(service: impl Into<String>, key: impl Into<String>) -> Self {
        Self {
            service: service.into(),
            key: key.into(),
        }
    }

    pub fn with_default_service(key: impl Into<String>) -> Self {
        Self {
            service: DEFAULT_SERVICE.to_string(),
            key: key.into(),
        }
    }
}

/// Cross-platform secret store backed by the host OS keychain.
///
/// Stateless by design — it holds no cached secrets. Every call round-trips
/// to the OS. That makes concurrent usage safe and avoids any in-process
/// leak surface beyond the immediate call's return value.
#[derive(Debug, Default, Clone, Copy)]
pub struct SecretStore;

impl SecretStore {
    pub fn new() -> Self {
        Self
    }

    /// Store a UTF-8 secret under `(service, key)`. Replaces any existing
    /// value at the same ref.
    ///
    /// On macOS, writes via `/usr/bin/security add-generic-password -U -A`.
    /// Every CAR read, write, status check, and delete uses that same stable
    /// Apple-signed helper identity instead of a release- or rebuild-specific
    /// CAR binary identity. `-U` updates existing items in place, preserving
    /// their ACL, partition list, and user-approved grants; `-A` applies when a
    /// new item is created (car-0o9).
    ///
    /// Trade-off: the value transits argv during the spawn (visible to
    /// `ps` from the same user for ~milliseconds). Acceptable for the
    /// "single-user developer machine" threat model; any process that
    /// can see argv on this machine can also read the keychain
    /// directly via `security`. On other platforms, behavior is
    /// unchanged (keyring crate's native backend).
    pub fn put(&self, r: &SecretRef, value: &str) -> Result<(), SecretError> {
        WRITE_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        platform_put(self, r, value)
    }

    /// Publish one authoritative value without exposing a partially-published
    /// replacement to readers.
    ///
    /// This is deliberately separate from [`Self::put`]. Parslee auth stores
    /// its entire active credential transaction in one JSON record and uses
    /// this method as the commit point. macOS updates the existing Keychain item
    /// in place (no pre-delete gap), the debug file backend renames an
    /// owner-private staging file, and Windows stages a revision-tagged
    /// inactive chunk generation before committing the root sentinel last.
    /// Windows retains the prior generation for concurrent readers and uses
    /// deterministic A/B slots plus high-water manifests so crashes cannot
    /// grow Credential Manager entry cardinality without bound.
    ///
    /// Multiple publishers for the same ref must be serialized by the caller.
    /// Parslee auth does this with its coordinator lock; readers may run
    /// concurrently with a publisher.
    pub fn publish(&self, r: &SecretRef, value: &str) -> Result<(), SecretError> {
        WRITE_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        platform_publish(self, r, value)
    }

    /// Store a structured value serialized as JSON.
    pub fn put_json<T: Serialize>(&self, r: &SecretRef, value: &T) -> Result<(), SecretError> {
        let s = serde_json::to_string(value)
            .map_err(|e| SecretError::Backend(format!("serialize: {}", e)))?;
        self.put(r, &s)
    }

    /// Read a UTF-8 secret. Returns `NotFound` if no entry exists.
    ///
    /// On macOS, reads through `/usr/bin/security` first so repeated
    /// helper rebuilds do not churn Keychain prompts against each
    /// binary's CDHash. Backend/authorization failures are returned
    /// directly instead of falling back to an in-process read path that
    /// can trigger a second prompt.
    pub fn get(&self, r: &SecretRef) -> Result<String, SecretError> {
        GET_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        platform_get(self, r)
    }

    /// Read a structured value previously stored via `put_json`.
    pub fn get_json<T: for<'de> Deserialize<'de>>(&self, r: &SecretRef) -> Result<T, SecretError> {
        let raw = self.get(r)?;
        serde_json::from_str(&raw).map_err(|e| SecretError::InvalidJson(e.to_string()))
    }

    /// Delete an entry. Returns Ok even if the entry didn't exist — idempotent
    /// from the caller's perspective.
    ///
    /// On macOS, deletes through `/usr/bin/security` first so the
    /// Apple-signed helper, not the rebuilt caller binary, owns
    /// Keychain authorization.
    pub fn delete(&self, r: &SecretRef) -> Result<(), SecretError> {
        DELETE_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        platform_delete(self, r)
    }

    /// Existence check without returning the value. Safe to log.
    ///
    /// On macOS, checks status through `/usr/bin/security` first for
    /// the same CDHash-stable authorization behavior as `get`.
    pub fn status(&self, r: &SecretRef) -> Result<SecretStatus, SecretError> {
        STATUS_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        platform_status(self, r)
    }

    /// Reserved internal service name used for availability probing.
    /// Consumers must not write user secrets under this service. Kept
    /// in sync with `DEFAULT_SERVICE` ("car") so all CAR-owned
    /// keychain entries share the `car-` prefix and a future cleanup
    /// pass can sweep them with one wildcard.
    const PROBE_SERVICE: &'static str = "car-internal";
    const PROBE_KEY: &'static str = "__availability_probe__";
    #[cfg(target_os = "macos")]
    const PROBE_VALUE: &'static str = "car-availability-probe";

    /// Probe whether the OS secret store can persist credentials.
    ///
    /// Uses an internal-only sentinel. Platform/backend failures mean the
    /// store is unavailable; the detailed form preserves their reason.
    ///
    /// # Side effects
    ///
    /// - On macOS an existence query remains the fast reachability check, but
    ///   it can never report availability by itself. The probe must then write
    ///   the non-secret sentinel and immediately delete it. All three
    ///   `/usr/bin/security` calls inherit the bounded helper deadline and name
    ///   the reserved item if authorization blocks. This intentionally tests
    ///   write access: keychain reads can succeed in a non-interactive shell
    ///   where every credential write is refused.
    /// - Other platforms probe their native keyring backend.
    /// - Performance: macOS performs a read, write, and cleanup; other
    ///   platforms perform one round-trip. Not cached.
    pub fn is_available(&self) -> bool {
        self.availability().available
    }

    /// Detailed availability probe. Same platform probe as `is_available`,
    /// but distinguishes "no backend at all" from a specific platform
    /// failure so the FFI surface can emit a `reason` matching the
    /// pattern used by the other v0.4 capability probes
    /// (`accountsList`, `calendarList`, etc.).
    pub fn availability(&self) -> AvailabilityCheck {
        AVAILABILITY_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        // Reason is only populated when `available == false`. Reachable
        // backends never carry a reason — callers can rely on
        // `available && reason.is_none()` for happy-path branching.
        // The opt-in file backend (test/headless redirect) is always
        // "available" — it is just the local filesystem.
        if file_backend_dir().is_some() {
            return AvailabilityCheck {
                available: true,
                reason: None,
            };
        }
        platform_availability(self)
    }

    /// Not compiled on macOS — and that gate is the regression barrier here,
    /// not a test. Every macOS operation goes through `/usr/bin/security`, so
    /// re-routing one of them back through the in-process keyring path would
    /// reach for `self.entry` and fail to compile. Worth stating because a
    /// test cannot cover it: the tests below inject a fake `SecurityCli`, so
    /// they exercise the helper and say nothing about which body
    /// `platform_availability` dispatches to.
    ///
    /// `keyring` is also a target-specific non-macOS dependency, so even a
    /// fully-qualified framework call fails to compile on macOS. This makes the
    /// one-writer-identity rule structural rather than conventional (car-0o9).
    #[cfg(not(target_os = "macos"))]
    fn entry(&self, r: &SecretRef) -> Result<Entry, SecretError> {
        Entry::new(&r.service, &r.key).map_err(|e| classify(e, "entry"))
    }
}

// ---------------------------------------------------------------------------
// Platform-dispatched keychain operations.
//
// macOS: shell out to `/usr/bin/security` for reads, writes, status checks,
// deletes, and the availability probe. The Apple-signed helper keeps Keychain
// authorization stable across rebuilt CAR binaries whose CDHash changes.
// Writes update existing items in place so saved grants and partition lists
// survive; new items use `-A` through the same stable helper identity.
//
// Other platforms: pass through to keyring (its native backends behave
// correctly).
// ---------------------------------------------------------------------------

/// Test/headless redirect: when `CAR_SECRETS_FILE_DIR` names a directory, the
/// store is backed by plaintext files there instead of the OS keychain. This is
/// the SAME env-keyed-redirect idiom as `resolve_env_or_keychain`'s
/// process-env precedence — a no-op in production (the daemon never sets this
/// var), but it lets tests drive the real `put`/`get`/`delete` code path WITHOUT
/// the macOS keychain's interactive-authorization prompt (which cancels
/// unattended, `code=154`). Each secret lands at `<dir>/<service>.<key>`.
///
/// SECURITY: plaintext on disk — acceptable ONLY because this is opt-in via an
/// env var production never sets. The keychain remains the sole production
/// backing store.
///
/// Two hard guards make a production leak structurally impossible:
///
/// 1. **Release builds refuse it entirely.** The redirect is honored ONLY under
///    `cfg!(debug_assertions)` (debug/test builds). A RELEASE binary — which is
///    what production ships — returns `None` even when the env var is set, so a
///    stray `CAR_SECRETS_FILE_DIR` can never route real secrets to plaintext in
///    prod.
/// 2. **First engagement warns loudly.** The first time the redirect is honored
///    in a process, a one-time `tracing::warn!` fires so a misconfigured dev /
///    CI run is visible, not silent.
fn file_backend_dir() -> Option<std::path::PathBuf> {
    // Release builds (production) NEVER honor the redirect — secrets always go
    // to the OS keychain. The env var is a debug/test-only seam.
    if !cfg!(debug_assertions) {
        return None;
    }
    match std::env::var_os("CAR_SECRETS_FILE_DIR") {
        Some(d) if !d.is_empty() => {
            // One-time loud warning the first time the plaintext file backend
            // engages in this process.
            static WARNED: std::sync::Once = std::sync::Once::new();
            WARNED.call_once(|| {
                tracing::warn!(
                    "CAR_SECRETS_FILE_DIR set — secrets are PLAINTEXT ON DISK; \
                     test-only, never production"
                );
            });
            Some(std::path::PathBuf::from(d))
        }
        _ => None,
    }
}

fn file_backend_path(dir: &std::path::Path, r: &SecretRef) -> std::path::PathBuf {
    // Sanitize path separators so a service/key never escapes the dir.
    let sanitize = |s: &str| s.replace(['/', '\\', '.'], "_");
    dir.join(format!("{}.{}", sanitize(&r.service), sanitize(&r.key)))
}

fn file_backend_put(dir: &std::path::Path, r: &SecretRef, value: &str) -> Result<(), SecretError> {
    std::fs::create_dir_all(dir)
        .map_err(|e| SecretError::Backend(format!("file backend mkdir: {e}")))?;
    std::fs::write(file_backend_path(dir, r), value)
        .map_err(|e| SecretError::Backend(format!("file backend write: {e}")))
}

fn file_backend_publish(
    dir: &std::path::Path,
    r: &SecretRef,
    value: &str,
) -> Result<(), SecretError> {
    use std::io::Write;

    std::fs::create_dir_all(dir)
        .map_err(|e| SecretError::Backend(format!("file backend mkdir: {e}")))?;
    let destination = file_backend_path(dir, r);
    let nonce = publication_nonce();
    let staging = destination.with_extension(format!("stage-{nonce}"));
    let mut options = std::fs::OpenOptions::new();
    options.create_new(true).write(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options
        .open(&staging)
        .map_err(|e| SecretError::Backend(format!("file backend stage: {e}")))?;
    file.write_all(value.as_bytes())
        .and_then(|_| file.sync_all())
        .map_err(|e| SecretError::Backend(format!("file backend stage write: {e}")))?;
    drop(file);
    if let Err(error) = std::fs::rename(&staging, &destination) {
        let _ = std::fs::remove_file(&staging);
        return Err(SecretError::Backend(format!(
            "file backend publish rename: {error}"
        )));
    }
    Ok(())
}

/// Whether a `NotFound` from an operation under `dir` means "this entry is
/// absent" rather than "this store is unusable".
///
/// The two are the same errno on one platform and not on the other. With a
/// REGULAR FILE configured where the secrets directory should be, opening an
/// entry under it fails with `ENOTDIR` on unix — which is not `NotFound`, so it
/// surfaced as a backend error — but with `ERROR_PATH_NOT_FOUND` on Windows,
/// which Rust maps straight to `io::ErrorKind::NotFound`. The store then
/// answered "that secret does not exist" for a store it could not read at all.
///
/// The consequence was not cosmetic. `car_auth`'s credential resolution treats
/// `NotFound` as "no V2 record yet" and runs a legacy-migration sweep — five
/// further reads of the same broken store — instead of failing on the first one
/// and entering keychain cooldown (Parslee-ai/car#1014). `delete` reported
/// success on a store it never touched, and `status` reported `exists: false`
/// rather than admitting it could not tell.
///
/// The discriminator is whether the configured path is something OTHER than a
/// directory, and it is the same question on every platform.
///
/// Note the second arm: a directory that does not exist YET is not a broken
/// store. Only `put`/`publish` call `create_dir_all`, so on a first run — before
/// anything has been written — the path is legitimately absent, and a `get`
/// there means "no secret yet", exactly as it always has. Treating that as a
/// backend error would send `car_auth` into keychain cooldown on a fresh
/// install instead of reporting "not signed in".
fn file_backend_entry_is_merely_absent(dir: &std::path::Path) -> bool {
    match std::fs::metadata(dir) {
        Ok(metadata) => metadata.is_dir(),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            // A genuinely absent directory is a normal first run, but Windows
            // also reports NotFound when an ancestor is a regular file. Walk to
            // the nearest existing ancestor and require it to be a directory;
            // any other metadata error means "could not inspect", not "absent".
            for ancestor in dir.ancestors().skip(1) {
                match std::fs::metadata(ancestor) {
                    Ok(metadata) => return metadata.is_dir(),
                    Err(ancestor_error)
                        if ancestor_error.kind() == std::io::ErrorKind::NotFound => {}
                    Err(_) => return false,
                }
            }
            false
        }
        Err(_) => false,
    }
}

fn file_backend_get(dir: &std::path::Path, r: &SecretRef) -> Result<String, SecretError> {
    match std::fs::read_to_string(file_backend_path(dir, r)) {
        Ok(v) => Ok(v),
        Err(e)
            if e.kind() == std::io::ErrorKind::NotFound
                && file_backend_entry_is_merely_absent(dir) =>
        {
            Err(SecretError::NotFound {
                service: r.service.clone(),
                key: r.key.clone(),
            })
        }
        Err(e) => Err(SecretError::Backend(format!("file backend read: {e}"))),
    }
}

fn file_backend_delete(dir: &std::path::Path, r: &SecretRef) -> Result<(), SecretError> {
    match std::fs::remove_file(file_backend_path(dir, r)) {
        Ok(()) => Ok(()),
        Err(e)
            if e.kind() == std::io::ErrorKind::NotFound
                && file_backend_entry_is_merely_absent(dir) =>
        {
            Ok(())
        }
        Err(e) => Err(SecretError::Backend(format!("file backend delete: {e}"))),
    }
}

fn file_backend_status(dir: &std::path::Path, r: &SecretRef) -> SecretStatus {
    SecretStatus {
        service: r.service.clone(),
        key: r.key.clone(),
        // `SecretStatus` has no error/unknown state. Keep the historical false
        // answer for both an absent entry and an unusable debug store; get/delete
        // carry the richer error distinction above.
        exists: file_backend_path(dir, r).exists(),
    }
}

#[cfg(target_os = "macos")]
fn platform_put(_store: &SecretStore, r: &SecretRef, value: &str) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_put(&dir, r, value);
    }
    mac_put_via_security_cli(&r.service, &r.key, value)
}

#[cfg(target_os = "macos")]
fn platform_publish(_store: &SecretStore, r: &SecretRef, value: &str) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_publish(&dir, r, value);
    }
    mac_publish_via_security_cli(&r.service, &r.key, value)
}

// --- Windows Credential Manager large-secret chunking ---------------------
//
// A single Windows credential's blob is capped well below the length of a
// Parslee JWT access token — writing one fails with `set_password ... longer
// than platform limit of 2560 chars`. macOS Keychain and Linux Secret Service
// have no such tight limit, so this never surfaced until CAR was exercised on
// real Windows hardware. The workaround, standard for this platform limit, is
// to split an oversized secret across N chunk entries and leave a sentinel
// under the real key that records the chunk count. Reads reassemble
// transparently, so every reader (car-auth, car-inference via car-auth) is
// unaffected. Backward compatible: a value stored as a single entry (no
// sentinel) is returned verbatim, and only Windows takes this path.

/// Sentinel written under the real key when a secret was chunked. The trailing
/// number is the chunk count. Distinctive enough that no real token/API key
/// collides with it.
#[cfg(any(not(target_os = "macos"), test))]
const CHUNK_SENTINEL: &str = "__car_secrets_chunked_v1__:";
#[cfg(any(target_os = "windows", test))]
const CHUNK_SENTINEL_V2: &str = "__car_secrets_chunked_v2__:";
#[cfg(any(target_os = "windows", test))]
const CHUNK_SENTINEL_V3: &str = "__car_secrets_chunked_v3__:";
#[cfg(any(target_os = "windows", test))]
const CHUNK_VALUE_V3: &str = "__car_secrets_chunk_v3__:";
/// UTF-16 length above which we chunk. Comfortably under the ~2560 platform cap
/// with headroom for the credential's other attributes.
#[cfg(any(not(target_os = "macos"), test))]
const CHUNK_THRESHOLD_UTF16: usize = 2000;
/// Characters per chunk. 1000 chars ≤ 2000 UTF-16 units even for all-BMP text.
#[cfg(any(not(target_os = "macos"), test))]
const CHUNK_CHARS: usize = 1000;
/// Hard ceiling for deterministic Windows chunk slots. Publication cardinality
/// is therefore bounded at two generations of at most this many chunks, even
/// when a process repeatedly crashes before swapping the root credential.
#[cfg(any(target_os = "windows", test))]
const WINDOWS_MAX_CHUNKS: usize = 1024;
#[cfg(any(target_os = "windows", test))]
const WINDOWS_READ_ATTEMPTS: usize = 4;

/// Derived ref for chunk `i` of a chunked secret.
#[cfg(not(target_os = "macos"))]
fn chunk_ref(r: &SecretRef, i: usize) -> SecretRef {
    SecretRef::new(r.service.clone(), format!("{}#chunk{}", r.key, i))
}

#[cfg(target_os = "windows")]
fn chunk_v2_ref(r: &SecretRef, nonce: &str, i: usize) -> SecretRef {
    SecretRef::new(r.service.clone(), format!("{}#chunkv2#{nonce}#{i}", r.key))
}

#[cfg(target_os = "windows")]
fn chunk_v3_ref(r: &SecretRef, generation: ChunkGeneration, i: usize) -> SecretRef {
    SecretRef::new(
        r.service.clone(),
        format!("{}#chunkv3#{}#{i}", r.key, generation.label()),
    )
}

#[cfg(target_os = "windows")]
fn chunk_v3_manifest_ref(r: &SecretRef, generation: ChunkGeneration) -> SecretRef {
    SecretRef::new(
        r.service.clone(),
        format!("{}#chunkv3#{}#manifest", r.key, generation.label()),
    )
}

#[cfg(target_os = "windows")]
fn chunk_v3_retired_v2_ref(r: &SecretRef) -> SecretRef {
    SecretRef::new(r.service.clone(), format!("{}#chunkv3#retired-v2", r.key))
}

/// Split a string into pieces of at most `n` chars, on char boundaries.
#[cfg(any(not(target_os = "macos"), test))]
fn split_on_chars(s: &str, n: usize) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut count = 0usize;
    for ch in s.chars() {
        cur.push(ch);
        count += 1;
        if count == n {
            out.push(std::mem::take(&mut cur));
            count = 0;
        }
    }
    if !cur.is_empty() {
        out.push(cur);
    }
    out
}

fn publication_nonce() -> String {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let sequence = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or_default();
    format!("{:x}-{:x}-{:x}", std::process::id(), nanos, sequence)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(any(target_os = "windows", test))]
enum ChunkGeneration {
    A,
    B,
}

#[cfg(any(target_os = "windows", test))]
impl ChunkGeneration {
    fn label(self) -> &'static str {
        match self {
            Self::A => "a",
            Self::B => "b",
        }
    }

    fn inactive(self) -> Self {
        match self {
            Self::A => Self::B,
            Self::B => Self::A,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(any(target_os = "windows", test))]
struct ChunkPublicationPlan {
    generation: ChunkGeneration,
    revision: String,
    chunks: Vec<String>,
    root: String,
}

#[cfg(any(target_os = "windows", test))]
fn chunk_publication_plan(
    value: &str,
    generation: ChunkGeneration,
    revision: &str,
) -> Result<ChunkPublicationPlan, SecretError> {
    if revision.is_empty() || revision.contains(':') {
        return Err(SecretError::Backend(
            "invalid Windows credential publication revision".to_string(),
        ));
    }
    let mut chunks = split_on_chars(value, CHUNK_CHARS);
    if chunks.is_empty() {
        chunks.push(String::new());
    }
    if chunks.len() > WINDOWS_MAX_CHUNKS {
        return Err(SecretError::Backend(format!(
            "Windows credential publication requires {} chunks; maximum is {WINDOWS_MAX_CHUNKS}",
            chunks.len()
        )));
    }
    Ok(ChunkPublicationPlan {
        generation,
        revision: revision.to_string(),
        root: format!(
            "{CHUNK_SENTINEL_V3}{}:{revision}:{}",
            generation.label(),
            chunks.len()
        ),
        chunks,
    })
}

#[cfg(any(target_os = "windows", test))]
fn encode_v3_chunk(revision: &str, value: &str) -> String {
    format!("{CHUNK_VALUE_V3}{revision}:{value}")
}

#[cfg(any(target_os = "windows", test))]
fn decode_v3_chunk<'a>(raw: &'a str, revision: &str) -> Result<&'a str, SecretError> {
    let payload = raw.strip_prefix(CHUNK_VALUE_V3).ok_or_else(|| {
        SecretError::Backend("invalid Windows v3 credential chunk metadata".to_string())
    })?;
    let (stored_revision, value) = payload.split_once(':').ok_or_else(|| {
        SecretError::Backend("invalid Windows v3 credential chunk metadata".to_string())
    })?;
    if stored_revision != revision {
        return Err(SecretError::Backend(
            "Windows credential chunk revision changed during read".to_string(),
        ));
    }
    Ok(value)
}

#[cfg(any(target_os = "windows", test))]
fn parse_v2_sentinel(raw: &str) -> Option<(&str, usize)> {
    let payload = raw.strip_prefix(CHUNK_SENTINEL_V2)?;
    let (nonce, count) = payload.rsplit_once(':')?;
    let count = count.parse::<usize>().ok()?;
    if nonce.is_empty() || count == 0 || count > WINDOWS_MAX_CHUNKS {
        return None;
    }
    Some((nonce, count))
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(any(target_os = "windows", test))]
enum WindowsRootLayout {
    Inline,
    LegacyV1 {
        count: usize,
    },
    LegacyV2 {
        nonce: String,
        count: usize,
    },
    V3 {
        generation: ChunkGeneration,
        revision: String,
        count: usize,
    },
}

#[cfg(any(target_os = "windows", test))]
fn windows_root_layout(raw: &str) -> Result<WindowsRootLayout, SecretError> {
    if let Some(payload) = raw.strip_prefix(CHUNK_SENTINEL_V3) {
        let (publication, count) = payload.rsplit_once(':').ok_or_else(|| {
            SecretError::Backend("invalid Windows v3 credential root metadata".to_string())
        })?;
        let (generation, revision) = publication.split_once(':').ok_or_else(|| {
            SecretError::Backend("invalid Windows v3 credential root metadata".to_string())
        })?;
        let generation = match generation {
            "a" => ChunkGeneration::A,
            "b" => ChunkGeneration::B,
            _ => {
                return Err(SecretError::Backend(
                    "invalid Windows v3 credential generation".to_string(),
                ))
            }
        };
        if revision.is_empty() {
            return Err(SecretError::Backend(
                "invalid Windows v3 credential publication revision".to_string(),
            ));
        }
        let count = count
            .parse::<usize>()
            .ok()
            .filter(|count| *count > 0 && *count <= WINDOWS_MAX_CHUNKS);
        return count
            .map(|count| WindowsRootLayout::V3 {
                generation,
                revision: revision.to_string(),
                count,
            })
            .ok_or_else(|| {
                SecretError::Backend("invalid Windows v3 credential chunk count".to_string())
            });
    }

    if raw.starts_with(CHUNK_SENTINEL_V2) {
        return parse_v2_sentinel(raw)
            .map(|(nonce, count)| WindowsRootLayout::LegacyV2 {
                nonce: nonce.to_string(),
                count,
            })
            .ok_or_else(|| {
                SecretError::Backend("invalid Windows v2 credential root metadata".to_string())
            });
    }

    if let Some(count) = raw.strip_prefix(CHUNK_SENTINEL) {
        return count
            .parse::<usize>()
            .ok()
            .filter(|count| *count > 0 && *count <= WINDOWS_MAX_CHUNKS)
            .map(|count| WindowsRootLayout::LegacyV1 { count })
            .ok_or_else(|| {
                SecretError::Backend("invalid Windows v1 credential chunk count".to_string())
            });
    }

    Ok(WindowsRootLayout::Inline)
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(any(target_os = "windows", test))]
enum WindowsCredentialSlot {
    Root,
    LegacyV1Chunk(usize),
    LegacyV2Chunk {
        nonce: String,
        index: usize,
    },
    V3Chunk {
        generation: ChunkGeneration,
        index: usize,
    },
    V3Manifest(ChunkGeneration),
    RetiredV2Manifest,
}

#[cfg(any(target_os = "windows", test))]
trait WindowsCredentialBackend {
    fn read(&mut self, slot: &WindowsCredentialSlot) -> Result<Option<String>, SecretError>;
    fn write(&mut self, slot: &WindowsCredentialSlot, value: &str) -> Result<(), SecretError>;
    fn delete(&mut self, slot: &WindowsCredentialSlot) -> Result<(), SecretError>;
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg(any(target_os = "windows", test))]
struct WindowsCleanupReport {
    failures: usize,
}

#[cfg(any(target_os = "windows", test))]
fn cleanup_windows_slot(
    backend: &mut impl WindowsCredentialBackend,
    slot: WindowsCredentialSlot,
    report: &mut WindowsCleanupReport,
) {
    if backend.delete(&slot).is_err() {
        report.failures += 1;
    }
}

#[cfg(any(target_os = "windows", test))]
fn read_generation_manifest(
    backend: &mut impl WindowsCredentialBackend,
    generation: ChunkGeneration,
) -> Result<usize, SecretError> {
    let Some(raw) = backend.read(&WindowsCredentialSlot::V3Manifest(generation))? else {
        return Ok(0);
    };
    raw.parse::<usize>()
        .ok()
        .filter(|count| *count <= WINDOWS_MAX_CHUNKS)
        .ok_or_else(|| {
            SecretError::Backend("invalid Windows credential generation manifest".to_string())
        })
}

#[cfg(any(target_os = "windows", test))]
fn read_retired_v2_manifest(
    backend: &mut impl WindowsCredentialBackend,
) -> Result<Option<(String, usize)>, SecretError> {
    let Some(raw) = backend.read(&WindowsCredentialSlot::RetiredV2Manifest)? else {
        return Ok(None);
    };
    match windows_root_layout(&raw)? {
        WindowsRootLayout::LegacyV2 { nonce, count } => Ok(Some((nonce, count))),
        _ => Err(SecretError::Backend(
            "invalid retired Windows v2 credential manifest".to_string(),
        )),
    }
}

#[cfg(any(target_os = "windows", test))]
fn cleanup_retired_v2(
    backend: &mut impl WindowsCredentialBackend,
    nonce: &str,
    count: usize,
    report: &mut WindowsCleanupReport,
) {
    let failures_before = report.failures;
    for index in 0..count {
        cleanup_windows_slot(
            backend,
            WindowsCredentialSlot::LegacyV2Chunk {
                nonce: nonce.to_string(),
                index,
            },
            report,
        );
    }
    // Keep the deterministic manifest when any chunk cleanup failed so the
    // next publication/delete can resume the sweep without guessing a nonce.
    if report.failures == failures_before {
        cleanup_windows_slot(backend, WindowsCredentialSlot::RetiredV2Manifest, report);
    }
}

#[cfg(any(target_os = "windows", test))]
fn publish_windows_value(
    backend: &mut impl WindowsCredentialBackend,
    value: &str,
) -> Result<WindowsCleanupReport, SecretError> {
    let previous_root = backend.read(&WindowsCredentialSlot::Root)?;
    let previous_layout = previous_root
        .as_deref()
        .map(windows_root_layout)
        .transpose()?;
    let retired_v2_before = read_retired_v2_manifest(backend)?;
    let newly_retired_v2 = match previous_layout.as_ref() {
        Some(WindowsRootLayout::LegacyV2 { nonce, count }) => {
            let root = previous_root
                .as_deref()
                .expect("a parsed legacy root came from a present credential");
            backend.write(&WindowsCredentialSlot::RetiredV2Manifest, root)?;
            Some((nonce.clone(), *count))
        }
        _ => None,
    };
    let generation = match previous_layout {
        Some(WindowsRootLayout::V3 { generation, .. }) => generation.inactive(),
        _ => ChunkGeneration::A,
    };
    let plan = chunk_publication_plan(value, generation, &publication_nonce())?;

    // This non-secret high-water mark is persisted before any chunk mutation.
    // If the process dies while staging, the next writer knows exactly how far
    // it must sweep. Repeated crashes overwrite the same bounded slot set.
    let previous_bound = read_generation_manifest(backend, generation)?;
    let high_water = previous_bound.max(plan.chunks.len());
    backend.write(
        &WindowsCredentialSlot::V3Manifest(generation),
        &high_water.to_string(),
    )?;

    let mut staged = 0;
    for (index, chunk) in plan.chunks.iter().enumerate() {
        let slot = WindowsCredentialSlot::V3Chunk { generation, index };
        if let Err(error) = backend.write(&slot, &encode_v3_chunk(&plan.revision, chunk)) {
            let mut ignored_cleanup = WindowsCleanupReport::default();
            for staged_index in 0..staged {
                cleanup_windows_slot(
                    backend,
                    WindowsCredentialSlot::V3Chunk {
                        generation,
                        index: staged_index,
                    },
                    &mut ignored_cleanup,
                );
            }
            return Err(error);
        }
        staged += 1;
    }

    // The root write is the sole commit point. The previous active generation
    // is deliberately retained so a reader that captured its root can finish.
    if let Err(error) = backend.write(&WindowsCredentialSlot::Root, &plan.root) {
        let mut ignored_cleanup = WindowsCleanupReport::default();
        for staged_index in 0..staged {
            cleanup_windows_slot(
                backend,
                WindowsCredentialSlot::V3Chunk {
                    generation,
                    index: staged_index,
                },
                &mut ignored_cleanup,
            );
        }
        return Err(error);
    }

    let mut cleanup = WindowsCleanupReport::default();
    let tail_failures_before = cleanup.failures;
    for index in plan.chunks.len()..high_water {
        cleanup_windows_slot(
            backend,
            WindowsCredentialSlot::V3Chunk { generation, index },
            &mut cleanup,
        );
    }
    if cleanup.failures == tail_failures_before
        && backend
            .write(
                &WindowsCredentialSlot::V3Manifest(generation),
                &plan.chunks.len().to_string(),
            )
            .is_err()
    {
        cleanup.failures += 1;
    }

    // A v2 generation retired by this commit survives at least one full v3
    // publication. That lets a reader which captured the old nonce finish.
    // A later commit reclaims it through the deterministic manifest; failures
    // leave the manifest in place for the next recovery sweep.
    if let Some((nonce, count)) = retired_v2_before {
        if newly_retired_v2.as_ref() != Some(&(nonce.clone(), count)) {
            cleanup_retired_v2(backend, &nonce, count, &mut cleanup);
        }
    }

    Ok(cleanup)
}

/// Best-effort delete of any chunk entries `#chunk0..` for `r`, stopping at the
/// first that doesn't exist. Used before a rewrite and on delete so stale
/// chunks from a previous large value never linger.
#[cfg(not(target_os = "macos"))]
fn clear_chunks(store: &SecretStore, r: &SecretRef) {
    for i in 0..1024 {
        let cr = chunk_ref(r, i);
        let Ok(entry) = store.entry(&cr) else { break };
        match entry.delete_credential() {
            Ok(_) => {}
            Err(keyring::Error::NoEntry) => break,
            Err(_) => break,
        }
    }
}

#[cfg(any(target_os = "windows", test))]
fn read_windows_value(
    backend: &mut impl WindowsCredentialBackend,
) -> Result<Option<String>, SecretError> {
    for attempt in 0..WINDOWS_READ_ATTEMPTS {
        let Some(root) = backend.read(&WindowsCredentialSlot::Root)? else {
            return Ok(None);
        };
        let (slots, expected_revision) = match windows_root_layout(&root)? {
            WindowsRootLayout::Inline => return Ok(Some(root)),
            WindowsRootLayout::LegacyV1 { count } => (
                (0..count)
                    .map(WindowsCredentialSlot::LegacyV1Chunk)
                    .collect::<Vec<_>>(),
                None,
            ),
            WindowsRootLayout::LegacyV2 { nonce, count } => (
                (0..count)
                    .map(|index| WindowsCredentialSlot::LegacyV2Chunk {
                        nonce: nonce.clone(),
                        index,
                    })
                    .collect::<Vec<_>>(),
                None,
            ),
            WindowsRootLayout::V3 {
                generation,
                revision,
                count,
            } => (
                (0..count)
                    .map(|index| WindowsCredentialSlot::V3Chunk { generation, index })
                    .collect::<Vec<_>>(),
                Some(revision),
            ),
        };

        let mut value = String::new();
        let mut chunk_error = None;
        for slot in slots {
            match backend.read(&slot) {
                Ok(Some(chunk)) => {
                    if let Some(revision) = expected_revision.as_deref() {
                        match decode_v3_chunk(&chunk, revision) {
                            Ok(chunk) => value.push_str(chunk),
                            Err(error) => {
                                chunk_error = Some(error);
                                break;
                            }
                        }
                    } else {
                        value.push_str(&chunk);
                    }
                }
                Ok(None) => {
                    chunk_error = Some(SecretError::Backend(
                        "Windows credential publication is incomplete".to_string(),
                    ));
                    break;
                }
                Err(error) => {
                    chunk_error = Some(error);
                    break;
                }
            }
        }

        let root_after = backend.read(&WindowsCredentialSlot::Root);
        if matches!(&root_after, Ok(Some(current)) if current != &root) {
            if chunk_error.is_none() {
                // Every chunk carried the captured revision (or was a retained
                // legacy generation), so this complete old value is safe.
                return Ok(Some(value));
            }
            if attempt + 1 < WINDOWS_READ_ATTEMPTS {
                continue;
            }
            return Err(SecretError::Backend(
                "Windows credential root changed during every read attempt".to_string(),
            ));
        }
        if let Some(error) = chunk_error {
            return Err(error);
        }
        match root_after {
            Ok(Some(current)) if current == root => return Ok(Some(value)),
            Ok(_) if attempt + 1 < WINDOWS_READ_ATTEMPTS => continue,
            Ok(_) => {
                return Err(SecretError::Backend(
                    "Windows credential root changed during every read attempt".to_string(),
                ))
            }
            Err(error) => return Err(error),
        }
    }
    Err(SecretError::Backend(
        "Windows credential read retry limit reached".to_string(),
    ))
}

#[cfg(any(target_os = "windows", test))]
fn delete_windows_value(
    backend: &mut impl WindowsCredentialBackend,
) -> Result<WindowsCleanupReport, SecretError> {
    let root = backend.read(&WindowsCredentialSlot::Root)?;
    let layout = root.as_deref().map(windows_root_layout).transpose()?;
    let retired_v2 = read_retired_v2_manifest(backend)?;

    // Resolve every cleanup bound before deleting the root. A metadata/backend
    // error therefore leaves the only authoritative generation untouched.
    let mut generation_bounds = [
        (
            ChunkGeneration::A,
            read_generation_manifest(backend, ChunkGeneration::A)?,
        ),
        (
            ChunkGeneration::B,
            read_generation_manifest(backend, ChunkGeneration::B)?,
        ),
    ];
    if let Some(WindowsRootLayout::V3 {
        generation, count, ..
    }) = layout.as_ref()
    {
        let (_, bound) = generation_bounds
            .iter_mut()
            .find(|(candidate, _)| candidate == generation)
            .expect("both deterministic generations are present");
        *bound = (*bound).max(*count);
    }

    backend.delete(&WindowsCredentialSlot::Root)?;

    let mut cleanup = WindowsCleanupReport::default();
    for (generation, bound) in generation_bounds {
        let failures_before = cleanup.failures;
        for index in 0..bound {
            cleanup_windows_slot(
                backend,
                WindowsCredentialSlot::V3Chunk { generation, index },
                &mut cleanup,
            );
        }
        if cleanup.failures == failures_before {
            cleanup_windows_slot(
                backend,
                WindowsCredentialSlot::V3Manifest(generation),
                &mut cleanup,
            );
        }
    }
    match layout {
        Some(WindowsRootLayout::LegacyV1 { count }) => {
            for index in 0..count {
                cleanup_windows_slot(
                    backend,
                    WindowsCredentialSlot::LegacyV1Chunk(index),
                    &mut cleanup,
                );
            }
        }
        Some(WindowsRootLayout::LegacyV2 { nonce, count }) => {
            for index in 0..count {
                cleanup_windows_slot(
                    backend,
                    WindowsCredentialSlot::LegacyV2Chunk {
                        nonce: nonce.clone(),
                        index,
                    },
                    &mut cleanup,
                );
            }
        }
        _ => {}
    }
    if let Some((nonce, count)) = retired_v2 {
        cleanup_retired_v2(backend, &nonce, count, &mut cleanup);
    }
    Ok(cleanup)
}

#[cfg(not(target_os = "macos"))]
fn platform_put(store: &SecretStore, r: &SecretRef, value: &str) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_put(&dir, r, value);
    }
    // Windows-only: chunk an oversized secret. Runtime-gated so Linux Secret
    // Service (no size limit) keeps its exact single-entry behavior.
    if cfg!(windows) {
        // Always clear stale chunks first so a shrink (large → small) can't
        // leave orphans behind.
        clear_chunks(store, r);
        if value.encode_utf16().count() > CHUNK_THRESHOLD_UTF16 {
            let parts = split_on_chars(value, CHUNK_CHARS);
            for (i, part) in parts.iter().enumerate() {
                let cr = chunk_ref(r, i);
                store
                    .entry(&cr)?
                    .set_password(part)
                    .map_err(|e| classify(e, "set_password(chunk)"))?;
            }
            // The sentinel goes last so a reader never sees it before its
            // chunks exist.
            let sentinel = format!("{CHUNK_SENTINEL}{}", parts.len());
            return store
                .entry(r)?
                .set_password(&sentinel)
                .map_err(|e| classify(e, "set_password(sentinel)"));
        }
    }
    let entry = store.entry(r)?;
    entry
        .set_password(value)
        .map_err(|e| classify(e, "set_password"))
}

#[cfg(target_os = "windows")]
struct KeyringWindowsBackend<'a> {
    store: &'a SecretStore,
    root: &'a SecretRef,
}

#[cfg(target_os = "windows")]
impl KeyringWindowsBackend<'_> {
    fn secret_ref(&self, slot: &WindowsCredentialSlot) -> SecretRef {
        match slot {
            WindowsCredentialSlot::Root => self.root.clone(),
            WindowsCredentialSlot::LegacyV1Chunk(index) => chunk_ref(self.root, *index),
            WindowsCredentialSlot::LegacyV2Chunk { nonce, index } => {
                chunk_v2_ref(self.root, nonce, *index)
            }
            WindowsCredentialSlot::V3Chunk { generation, index } => {
                chunk_v3_ref(self.root, *generation, *index)
            }
            WindowsCredentialSlot::V3Manifest(generation) => {
                chunk_v3_manifest_ref(self.root, *generation)
            }
            WindowsCredentialSlot::RetiredV2Manifest => chunk_v3_retired_v2_ref(self.root),
        }
    }
}

#[cfg(target_os = "windows")]
impl WindowsCredentialBackend for KeyringWindowsBackend<'_> {
    fn read(&mut self, slot: &WindowsCredentialSlot) -> Result<Option<String>, SecretError> {
        match self.store.entry(&self.secret_ref(slot))?.get_password() {
            Ok(value) => Ok(Some(value)),
            Err(keyring::Error::NoEntry) => Ok(None),
            Err(error) => Err(classify(error, "get_password(windows-publish)")),
        }
    }

    fn write(&mut self, slot: &WindowsCredentialSlot, value: &str) -> Result<(), SecretError> {
        self.store
            .entry(&self.secret_ref(slot))?
            .set_password(value)
            .map_err(|error| classify(error, "set_password(windows-publish)"))
    }

    fn delete(&mut self, slot: &WindowsCredentialSlot) -> Result<(), SecretError> {
        match self
            .store
            .entry(&self.secret_ref(slot))?
            .delete_credential()
        {
            Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
            Err(error) => Err(classify(error, "delete_credential(windows-publish)")),
        }
    }
}

#[cfg(target_os = "windows")]
fn platform_publish(store: &SecretStore, r: &SecretRef, value: &str) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_publish(&dir, r, value);
    }
    let mut backend = KeyringWindowsBackend { store, root: r };
    let cleanup = publish_windows_value(&mut backend, value)?;
    if cleanup.failures > 0 {
        tracing::warn!(
            cleanup_failures = cleanup.failures,
            "Windows credential publication committed; bounded cleanup deferred"
        );
    }
    Ok(())
}

#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
fn platform_publish(store: &SecretStore, r: &SecretRef, value: &str) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_publish(&dir, r, value);
    }
    store
        .entry(r)?
        .set_password(value)
        .map_err(|error| classify(error, "publish_password"))
}

#[cfg(target_os = "macos")]
fn platform_get(_store: &SecretStore, r: &SecretRef) -> Result<String, SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_get(&dir, r);
    }
    mac_get_via_security_cli(r)
}

#[cfg(target_os = "windows")]
fn platform_get(store: &SecretStore, r: &SecretRef) -> Result<String, SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_get(&dir, r);
    }
    let mut backend = KeyringWindowsBackend { store, root: r };
    match read_windows_value(&mut backend)? {
        Some(value) => Ok(value),
        None => Err(SecretError::NotFound {
            service: r.service.clone(),
            key: r.key.clone(),
        }),
    }
}

#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
fn platform_get(store: &SecretStore, r: &SecretRef) -> Result<String, SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_get(&dir, r);
    }
    match store.entry(r)?.get_password() {
        Ok(value) => Ok(value),
        Err(keyring::Error::NoEntry) => Err(SecretError::NotFound {
            service: r.service.clone(),
            key: r.key.clone(),
        }),
        Err(error) => Err(classify(error, "get_password")),
    }
}

#[cfg(target_os = "macos")]
fn platform_delete(_store: &SecretStore, r: &SecretRef) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_delete(&dir, r);
    }
    mac_delete_via_security_cli(r)
}

#[cfg(target_os = "windows")]
fn platform_delete(store: &SecretStore, r: &SecretRef) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_delete(&dir, r);
    }
    let mut backend = KeyringWindowsBackend { store, root: r };
    let cleanup = delete_windows_value(&mut backend)?;
    if cleanup.failures > 0 {
        tracing::warn!(
            cleanup_failures = cleanup.failures,
            "Windows credential root deleted; bounded cleanup deferred"
        );
    }
    Ok(())
}

#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
fn platform_delete(store: &SecretStore, r: &SecretRef) -> Result<(), SecretError> {
    if let Some(dir) = file_backend_dir() {
        return file_backend_delete(&dir, r);
    }
    match store.entry(r)?.delete_credential() {
        Ok(_) | Err(keyring::Error::NoEntry) => Ok(()),
        Err(error) => Err(classify(error, "delete_credential")),
    }
}

#[cfg(target_os = "macos")]
fn platform_status(_store: &SecretStore, r: &SecretRef) -> Result<SecretStatus, SecretError> {
    if let Some(dir) = file_backend_dir() {
        return Ok(file_backend_status(&dir, r));
    }
    mac_status_via_security_cli(r)
}

#[cfg(not(target_os = "macos"))]
fn platform_status(store: &SecretStore, r: &SecretRef) -> Result<SecretStatus, SecretError> {
    if let Some(dir) = file_backend_dir() {
        return Ok(file_backend_status(&dir, r));
    }
    let entry = store.entry(r)?;
    let exists = match entry.get_password() {
        Ok(_) => true,
        Err(keyring::Error::NoEntry) => false,
        Err(other) => return Err(classify(other, "status")),
    };
    Ok(SecretStatus {
        service: r.service.clone(),
        key: r.key.clone(),
        exists,
    })
}

/// Usability probe on macOS: after a fast existence check, write and then
/// delete CAR's reserved non-secret sentinel through the same bounded,
/// Apple-signed helper as every other macOS operation.
///
/// An existence query is insufficient here: macOS can allow reads while
/// refusing every write from a non-interactive process. That made
/// [`SecretStore::is_available`] report true and sent tests and callers into
/// operations that could only fail (Parslee-ai/car#1158). The read remains a
/// fast failure path, but availability now requires the read, write, and
/// cleanup to succeed. Any failure reports unavailable with the helper's
/// original reason. The fixed value is not a credential, and the reserved
/// `(service, key)` prevents collision with user secrets.
///
/// The calls remain under `bounded_command_output`, so authorization cannot
/// hang the process indefinitely and [`keychain_prompt_notice`] names
/// `car-internal/__availability_probe__` if either operation blocks. This also
/// preserves the stable `/usr/bin/security` authorization identity introduced
/// for the probe by Parslee-ai/car#897.
#[cfg(target_os = "macos")]
fn platform_availability(_store: &SecretStore) -> AvailabilityCheck {
    mac_availability_via_security_cli_with(&SystemSecurityCli)
}

#[cfg(target_os = "macos")]
fn mac_availability_via_security_cli_with(cli: &impl SecurityCli) -> AvailabilityCheck {
    let probe = SecretRef::new(SecretStore::PROBE_SERVICE, SecretStore::PROBE_KEY);
    let result = mac_exists_via_security_cli_with(&probe, cli).and_then(|_| {
        mac_put_via_security_cli_with(&probe.service, &probe.key, SecretStore::PROBE_VALUE, cli)
            .and_then(|()| mac_delete_via_security_cli_with(&probe, cli))
    });

    match result {
        Ok(()) => AvailabilityCheck {
            available: true,
            reason: None,
        },
        Err(error) => AvailabilityCheck {
            available: false,
            reason: Some(error.to_string()),
        },
    }
}

#[cfg(not(target_os = "macos"))]
fn platform_availability(store: &SecretStore) -> AvailabilityCheck {
    let probe = SecretRef::new(SecretStore::PROBE_SERVICE, SecretStore::PROBE_KEY);
    match store.entry(&probe) {
        Ok(entry) => match entry.get_password() {
            Ok(_) | Err(keyring::Error::NoEntry) => AvailabilityCheck {
                available: true,
                reason: None,
            },
            Err(keyring::Error::PlatformFailure(e)) => AvailabilityCheck {
                available: false,
                reason: Some(format!("platform failure: {e}")),
            },
            Err(keyring::Error::NoStorageAccess(e)) => AvailabilityCheck {
                available: false,
                reason: Some(format!("no storage access: {e}")),
            },
            // Other keyring errors (BadEncoding etc.) on the
            // probe key indicate the backend responded but
            // returned something unexpected. Treat as available
            // so the caller can still try real ops; the failure
            // mode shows up at the next put/get with proper
            // typed error.
            Err(_) => AvailabilityCheck {
                available: true,
                reason: None,
            },
        },
        Err(SecretError::Unavailable(reason)) => AvailabilityCheck {
            available: false,
            reason: Some(reason),
        },
        Err(other) => AvailabilityCheck {
            available: false,
            reason: Some(other.to_string()),
        },
    }
}

/// Shell-out write with the `-A` flag (any-app ACL).
///
/// `service`/`account` are passed as separate argv tokens so shell
/// metacharacters in either are inert. The value is the only argv slot
/// that's a secret; document the trade-off at the call site.
///
/// `-U` updates an existing item in place, preserving every authorization and
/// partition grant already attached to it. CAR never delete-recreates an item
/// as part of a write or a prompted-read repair. On a genuine create, `-A`
/// gives the stable Apple-signed helper access (car-0o9).
#[cfg(target_os = "macos")]
fn mac_put_via_security_cli(service: &str, account: &str, value: &str) -> Result<(), SecretError> {
    mac_put_via_security_cli_with(service, account, value, &SystemSecurityCli)
}

#[cfg(target_os = "macos")]
fn mac_publish_via_security_cli(
    service: &str,
    account: &str,
    value: &str,
) -> Result<(), SecretError> {
    mac_publish_via_security_cli_with(service, account, value, &SystemSecurityCli)
}

#[cfg(target_os = "macos")]
fn mac_publish_via_security_cli_with(
    service: &str,
    account: &str,
    value: &str,
    cli: &impl SecurityCli,
) -> Result<(), SecretError> {
    mac_write_via_security_cli(service, account, value, cli)
}

#[cfg(target_os = "macos")]
fn mac_put_via_security_cli_with(
    service: &str,
    account: &str,
    value: &str,
    cli: &impl SecurityCli,
) -> Result<(), SecretError> {
    mac_write_via_security_cli(service, account, value, cli)
}

/// Write or update a secret without replacing its ACL or partition list.
///
/// `add-generic-password -U` updates an existing item in place. On a create,
/// `-A` grants the stable Apple-signed `/usr/bin/security` helper access. CAR
/// never delete-recreates an item as a repair: doing so discards the partition
/// grants macOS persisted when the user approved a prior read and starts the
/// password-prompt cycle over (car-0o9).
#[cfg(target_os = "macos")]
fn mac_write_via_security_cli(
    service: &str,
    account: &str,
    value: &str,
    cli: &impl SecurityCli,
) -> Result<(), SecretError> {
    let output = cli
        .output(&[
            "add-generic-password",
            "-U", // update in place when the item is still there
            "-A", // permissive ACL — honoured only on a create
            "-s",
            service,
            "-a",
            account,
            "-w",
            value,
        ])
        .map_err(|e| security_cli_spawn_error("add-generic-password", e))?;
    if output.success {
        return Ok(());
    }
    Err(security_cli_backend_error("add-generic-password", output))
}

#[cfg(target_os = "macos")]
const SECURITY_ERR_SEC_ITEM_NOT_FOUND: i32 = 44;

#[cfg(target_os = "macos")]
#[derive(Debug)]
struct SecurityCliOutput {
    success: bool,
    code: Option<i32>,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    /// Whether *this* call is the one macOS drew a keychain dialog for.
    ///
    /// The signal is produced inside `bounded_command_output`, where it extends
    /// the deadline and emits the item-specific waiting notice. It is carried
    /// through here only so a completed prompted read can be logged. Prompt
    /// attribution never authorizes an ACL, partition, or item rewrite.
    ///
    /// Narrower than "a dialog was on screen": see
    /// [`dialog_is_evidence_for_this_read`]. `SecurityAgent` is machine-wide, so
    /// a bare sighting is not attributable to this read.
    prompted: bool,
    /// Whether CAR killed the helper after its bounded deadline.
    timed_out: bool,
}

#[cfg(target_os = "macos")]
trait SecurityCli {
    fn output(&self, args: &[&str]) -> std::io::Result<SecurityCliOutput>;
}

#[cfg(target_os = "macos")]
struct SystemSecurityCli;

#[cfg(target_os = "macos")]
impl SecurityCli for SystemSecurityCli {
    fn output(&self, args: &[&str]) -> std::io::Result<SecurityCliOutput> {
        let mut command = std::process::Command::new("/usr/bin/security");
        command.args(args);
        if let Some(keychain_path) = selected_keychain_path()? {
            command.arg(keychain_path);
        }
        let run = bounded_command_output(&mut command, SECURITY_CLI_TIMEOUT, &describe_item(args))?;
        Ok(SecurityCliOutput {
            success: run.output.status.success(),
            code: run.output.status.code(),
            stdout: run.output.stdout,
            stderr: run.output.stderr,
            prompted: run.prompted,
            timed_out: run.timed_out,
        })
    }
}

#[cfg(target_os = "macos")]
const KEYCHAIN_PATH_ENV: &str = "CAR_KEYCHAIN_PATH";

#[cfg(target_os = "macos")]
const KEYCHAIN_PROOF_ROOT_ENV: &str = "CAR_KEYCHAIN_PROOF_ROOT";

/// Resolve the optional release-proof Keychain selector. Production behavior
/// is unchanged when `CAR_KEYCHAIN_PATH` is absent.
#[cfg(target_os = "macos")]
fn selected_keychain_path() -> std::io::Result<Option<std::path::PathBuf>> {
    let Some(path) = std::env::var_os(KEYCHAIN_PATH_ENV).filter(|value| !value.is_empty()) else {
        return Ok(None);
    };
    let proof_root = std::env::var_os(KEYCHAIN_PROOF_ROOT_ENV)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("{KEYCHAIN_PATH_ENV} requires {KEYCHAIN_PROOF_ROOT_ENV}"),
            )
        })?;
    validate_keychain_path(
        std::path::Path::new(&path),
        std::path::Path::new(&proof_root),
    )
    .map(Some)
}

#[cfg(target_os = "macos")]
fn validate_keychain_path(
    path: &std::path::Path,
    proof_root: &std::path::Path,
) -> std::io::Result<std::path::PathBuf> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    if !path.is_absolute() || !proof_root.is_absolute() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "isolated Keychain path and proof root must be absolute",
        ));
    }

    let expected_uid = current_effective_uid();
    let root_metadata = std::fs::symlink_metadata(proof_root)?;
    if root_metadata.file_type().is_symlink()
        || !root_metadata.is_dir()
        || root_metadata.uid() != expected_uid
        || root_metadata.permissions().mode() & 0o077 != 0
    {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "Keychain proof root must be an owner-private, non-symlink directory owned by the current user",
        ));
    }

    let path_metadata = std::fs::symlink_metadata(path)?;
    if path_metadata.file_type().is_symlink()
        || !path_metadata.is_file()
        || path_metadata.uid() != expected_uid
        || path_metadata.permissions().mode() & 0o077 != 0
    {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "isolated Keychain must be an owner-private, non-symlink regular file owned by the current user",
        ));
    }

    let canonical_root = std::fs::canonicalize(proof_root)?;
    let canonical_path = std::fs::canonicalize(path)?;
    if !canonical_path.starts_with(&canonical_root) || canonical_path == canonical_root {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "isolated Keychain must be canonically contained by its proof root",
        ));
    }
    Ok(canonical_path)
}

#[cfg(target_os = "macos")]
fn current_effective_uid() -> u32 {
    unsafe extern "C" {
        fn geteuid() -> u32;
    }
    // SAFETY: `geteuid` takes no arguments and has no preconditions.
    unsafe { geteuid() }
}

#[cfg(target_os = "macos")]
const SECURITY_CLI_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);

/// Deadline used instead of [`SECURITY_CLI_TIMEOUT`] while macOS is showing a
/// keychain dialog. Generous on purpose: it is a bound on *human* response, not
/// on a hung process, and the cost of being too tight is that the credential
/// becomes permanently unreachable (see `bounded_command_output`).
#[cfg(target_os = "macos")]
const SECURITY_CLI_INTERACTIVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(180);

/// Is macOS currently drawing a keychain prompt?
///
/// `SecurityAgent` is the process that renders the unlock / "allow access"
/// dialogs. Its presence is the difference between "the helper is hung" and
/// "the helper is waiting for the user" — a distinction the bare deadline
/// cannot make, and getting it wrong kills the dialog mid-typing.
///
/// Deliberately fail-CLOSED to the short deadline: if this cannot be
/// determined, treat the helper as non-interactive, so a lookup failure can
/// never extend a genuinely hung child to three minutes.
#[cfg(target_os = "macos")]
fn security_agent_is_prompting() -> bool {
    std::process::Command::new("/usr/bin/pgrep")
        .arg("-x")
        .arg("SecurityAgent")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// How long a `security` call must still be running, with a dialog on screen,
/// before that dialog counts as evidence that *this* call is the one being
/// authorized.
///
/// `SecurityAgent` is machine-wide. It is up whenever anything on the Mac is
/// asking for authorization — an installer, a `sudo` GUI prompt, a browser
/// saving a password, or a *different* CAR process blocked on its own keychain
/// dialog. None of those say anything about the item this call is reading.
///
/// The duration is what makes the sighting attributable: a `security
/// find-generic-password -g` that nobody has to authorize returns in tens of
/// milliseconds (the v0.47.0 notes derive ~14ms per credential probe), and this
/// loop has already broken out on `try_wait` long before the
/// threshold. A call that genuinely drew a dialog is still running, because it
/// is blocked until a human answers.
///
/// Duration, rather than "SecurityAgent was absent at spawn and appeared
/// later": during the prompt storm this exists to cure, a dialog is *already*
/// up when the next read spawns, so a transition rule would go blind exactly
/// when it matters most.
///
/// **This is a heuristic with real margins, not a proof.** Half a second is
/// ~35× that derived per-probe cost, but a cold first read on a busy machine can
/// be far slower than that, so a false positive is still reachable. Attribution
/// now controls only the waiting notice and the longer human-response deadline;
/// it never authorizes an item mutation. A locked-keychain dialog may therefore
/// be described as an item approval, but CAR still leaves the item untouched.
#[cfg(target_os = "macos")]
const PROMPT_EVIDENCE_MIN: std::time::Duration = std::time::Duration::from_millis(500);

/// Does a dialog seen at `elapsed` into a still-running call belong to *this*
/// call?
///
/// Split out from the poll loop so the rule is testable without a real keychain
/// or a real dialog. See [`PROMPT_EVIDENCE_MIN`] for why both terms are needed.
#[cfg(target_os = "macos")]
fn dialog_is_evidence_for_this_read(dialog_on_screen: bool, elapsed: std::time::Duration) -> bool {
    dialog_on_screen && elapsed >= PROMPT_EVIDENCE_MIN
}

/// A finished helper run, plus whether the dialog macOS drew was this run's.
#[cfg(target_os = "macos")]
#[derive(Debug)]
struct BoundedRun {
    output: std::process::Output,
    prompted: bool,
    timed_out: bool,
}

/// Name the keychain item a `security` invocation is acting on, for the notice
/// below. `service/account` when both are present, else whichever is, else the
/// subcommand.
///
/// **Which item** is the datum that turns a repeat-prompt report into a
/// diagnosis, and it is the one thing the log never carried: the macOS dialog
/// names the item, but reading it requires being at the screen when it appears.
/// The reported scenario is precisely the one where nobody is — an operator
/// stepped away and came back to a stack of ~18 prompts, by which point the
/// only question that matters ("which item keeps asking?") is unanswerable
/// (Parslee-ai/car#897).
///
/// Reads only `-s`/`-a`, which are a service name and an account name. The
/// secret itself arrives on the child's stdout and is never touched here.
#[cfg(target_os = "macos")]
fn describe_item(args: &[&str]) -> String {
    let flag = |name: &str| {
        args.iter()
            .position(|a| *a == name)
            .and_then(|i| args.get(i + 1))
            .copied()
    };
    match (flag("-s"), flag("-a")) {
        (Some(service), Some(account)) => format!("{service}/{account}"),
        (Some(service), None) => service.to_string(),
        (None, Some(account)) => account.to_string(),
        // Not an item-scoped call (`unlock-keychain`, `list-keychains`, …).
        // Naming the subcommand still beats naming nothing.
        (None, None) => args.first().copied().unwrap_or("security").to_string(),
    }
}

/// The line emitted the moment a keychain dialog is attributed to this read.
///
/// Split out so a test can assert the wording without a real dialog, and so the
/// promptly-emitted notice and the on-expiry message stay coherent — they
/// describe the same condition three minutes apart and must not drift into
/// giving different remedies.
#[cfg(target_os = "macos")]
fn keychain_prompt_notice(item: &str) -> String {
    format!(
        "waiting on a macOS keychain prompt for \"{item}\" (up to {}s) — CAR is not \
         hung. Click \"Always Allow\" on the dialog (it may be behind another \
         window), or grant the \"car\" service access in Keychain Access.",
        SECURITY_CLI_INTERACTIVE_TIMEOUT.as_secs()
    )
}

#[cfg(target_os = "macos")]
fn bounded_command_output(
    command: &mut std::process::Command,
    timeout: std::time::Duration,
    item: &str,
) -> std::io::Result<BoundedRun> {
    bounded_command_output_with(command, timeout, security_agent_is_prompting, || {
        // `tracing`, not `eprintln!`, and it reaches both audiences that matter
        // here: `car-cli` installs a stderr `fmt` layer defaulting to `info`
        // (`car_telemetry::init_tracing`), so a person at a terminal sees the
        // line; and a daemon blocked the same way gets it in its log, which is
        // the second half of what Parslee-ai/car#878 asked for — and the only
        // channel that survives an operator who has walked away (#897).
        tracing::warn!("{}", keychain_prompt_notice(item));
    })
}

/// `bounded_command_output` with the dialog probe and the notice sink injected.
///
/// The probe is a parameter so a test can hold "a dialog is on screen" true for
/// the whole run. Without that, every assertion about attribution is decided by
/// whether the machine running the tests happens to have an authorization
/// dialog up — which on CI it never does, so the test would pass whatever the
/// attribution rule said, including no rule at all.
///
/// `on_waiting_for_user` is injected for the same reason one step further on:
/// the property worth testing is that it fires **exactly once** per blocked
/// read, and a counter is the only honest way to assert that.
#[cfg(target_os = "macos")]
fn bounded_command_output_with(
    command: &mut std::process::Command,
    timeout: std::time::Duration,
    dialog_probe: impl Fn() -> bool,
    on_waiting_for_user: impl Fn(),
) -> std::io::Result<BoundedRun> {
    use std::io::Read;
    use std::process::Stdio;
    use std::time::Instant;

    command.stdout(Stdio::piped()).stderr(Stdio::piped());
    let mut child = command.spawn()?;
    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| std::io::Error::other("keychain helper stdout was not piped"))?;
    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| std::io::Error::other("keychain helper stderr was not piped"))?;
    let stdout_reader = std::thread::spawn(move || {
        let mut bytes = Vec::new();
        let mut stdout = stdout;
        stdout.read_to_end(&mut bytes)?;
        Ok::<_, std::io::Error>(bytes)
    });
    let stderr_reader = std::thread::spawn(move || {
        let mut bytes = Vec::new();
        let mut stderr = stderr;
        stderr.read_to_end(&mut bytes)?;
        Ok::<_, std::io::Error>(bytes)
    });
    let started = Instant::now();
    // Sticky: once a dialog is attributed to this run it stays attributed, and
    // SecurityAgent exits as soon as the user answers.
    let mut prompted = false;
    let (status, timed_out) = loop {
        if let Some(status) = child.try_wait()? {
            break (status, false);
        }
        // The deadline exists to bound a HUNG helper. A helper waiting on the
        // user is not hung, and killing it there is actively harmful: macOS
        // shows the unlock/authorize dialog, the person starts typing, the
        // deadline fires, and the dialog is torn down before the unlock can
        // commit. The next request opens a fresh dialog, so entering the
        // correct password over and over never succeeds — the timeout makes the
        // prompt UNSATISFIABLE rather than merely noisy. Nobody reliably finds a
        // window, types a password and submits inside 15s, let alone repeatedly.
        //
        // So while SecurityAgent (the process that draws those dialogs) is up,
        // extend to `SECURITY_CLI_INTERACTIVE_TIMEOUT`. A genuinely hung helper
        // has no dialog and still dies at the short deadline.
        let dialog_on_screen = dialog_probe();
        // Extending the deadline on any sighting is the right call — waiting
        // longer is cheap and reversible, and the cost of being wrong the other
        // way is a torn-down dialog nobody can satisfy.
        //
        // Attribution controls the immediate notice only. Before car-0o9 it
        // also triggered delete + recreate after a successful read, discarding
        // the grant the user had just approved. Reads no longer mutate items.
        if !prompted && dialog_is_evidence_for_this_read(dialog_on_screen, started.elapsed()) {
            prompted = true;
            // Say so NOW, not on expiry (Parslee-ai/car#878). Everything needed
            // to explain the wait is true at this instant, and the on-expiry
            // message below only prints if the user waits out the full 180s —
            // so an operator who kills the "hung" command at two minutes, or a
            // wrapper/CI step with a shorter timeout, never saw it at all. That
            // is the reported experience exactly: three runs killed, three
            // fresh dialogs raised, and the explanation the code was ready to
            // give never reached anyone.
            //
            // Fires on the ATTRIBUTED predicate rather than a bare sighting.
            // `SecurityAgent` is machine-wide (Parslee-ai/car#897), so a bare
            // sighting can belong to another process's dialog; requiring that
            // this read has also been blocked for `PROMPT_EVIDENCE_MIN` keeps
            // the notice off fast reads that merely coincided with someone
            // else's prompt. Reusing `prompted` as the latch is deliberate —
            // one blocked read, one line, and no second piece of state that
            // could disagree with it.
            on_waiting_for_user();
        }
        let deadline = if dialog_on_screen {
            SECURITY_CLI_INTERACTIVE_TIMEOUT
        } else {
            timeout
        };
        if started.elapsed() >= deadline {
            let _ = child.kill();
            break (child.wait()?, true);
        }
        std::thread::sleep(std::time::Duration::from_millis(10));
    };
    let join_reader = |reader: std::thread::JoinHandle<std::io::Result<Vec<u8>>>,
                       stream: &str|
     -> std::io::Result<Vec<u8>> {
        reader.join().map_err(|_| {
            std::io::Error::other(format!("keychain helper {stream} reader panicked"))
        })?
    };
    let stdout = join_reader(stdout_reader, "stdout")?;
    let mut stderr = join_reader(stderr_reader, "stderr")?;
    if timed_out {
        // Name the cause. `security` blocks here when macOS is showing a
        // keychain authorization dialog, so the deadline is nearly always "a
        // prompt nobody clicked" rather than a hung helper. Without saying so,
        // this surfaces to the user as `no inference backend is available` —
        // which points at models and accounts, i.e. everywhere except the
        // dialog actually waiting on screen.
        stderr.extend_from_slice(
            format!(
                "\nCAR killed the keychain helper after {}ms. This usually means a macOS \
                 keychain prompt is open and waiting: click \"Always Allow\" (or grant access \
                 to the \"car\" service in Keychain Access). Until it is answered, CAR cannot \
                 read your saved credentials and will report that no account is signed in.",
                timeout.as_millis()
            )
            .as_bytes(),
        );
    }
    Ok(BoundedRun {
        output: std::process::Output {
            status,
            stdout,
            stderr,
        },
        prompted,
        timed_out,
    })
}

/// Primary macOS value read:
/// `/usr/bin/security find-generic-password -s SVC -a KEY -g`.
/// `-g` prints the password metadata line to stderr and preserves the
/// password bytes as hex when the value contains non-printable UTF-8
/// bytes. Service/key are passed as separate argv values, never
/// interpolated into a shell, so there's no injection surface even if a
/// key contains shell metacharacters.
#[cfg(target_os = "macos")]
fn mac_get_via_security_cli(r: &SecretRef) -> Result<String, SecretError> {
    mac_get_via_security_cli_with(r, &SystemSecurityCli)
}

/// CAR deliberately performs no automatic ACL or partition repair after a read.
///
/// A successful Keychain prompt is itself the user's persisted grant. Rewriting
/// or recreating the item here would discard that grant, and a partition-list
/// reconciliation through `security set-generic-password-partition-list` can
/// itself require another password prompt in an unattended daemon. The safe
/// persistence rule is therefore: read only, leave every existing item intact,
/// and let all future writes update it in place (car-0o9).
#[cfg(target_os = "macos")]
fn mac_get_via_security_cli_with(
    r: &SecretRef,
    cli: &impl SecurityCli,
) -> Result<String, SecretError> {
    let output = cli
        .output(&[
            "find-generic-password",
            "-s",
            &r.service,
            "-a",
            &r.key,
            "-g",
        ])
        .map_err(|e| security_cli_spawn_error("find-generic-password", e))?;
    if !output.success {
        return security_cli_not_found_or_backend("find-generic-password", r, output);
    }
    if output.prompted {
        tracing::debug!(
            service = %r.service,
            key = %r.key,
            "keychain read completed after user approval; preserving the item and its persisted grant"
        );
    }
    mac_parse_security_cli_password(&output)
}

#[cfg(target_os = "macos")]
fn mac_parse_security_cli_password(output: &SecurityCliOutput) -> Result<String, SecretError> {
    let line = mac_security_cli_text(&output.stderr, "stderr")?
        .lines()
        .find(|line| line.starts_with("password:"))
        .or_else(|| {
            mac_security_cli_text(&output.stdout, "stdout")
                .ok()
                .and_then(|stdout| stdout.lines().find(|line| line.starts_with("password:")))
        })
        .ok_or_else(|| {
            SecretError::Backend(
                "/usr/bin/security find-generic-password -g did not print a password line"
                    .to_string(),
            )
        })?;

    let payload = line
        .strip_prefix("password:")
        .expect("password line prefix was checked")
        .trim_start();

    if payload.is_empty() {
        return Ok(String::new());
    }

    let bytes = if let Some(hex_and_preview) = payload.strip_prefix("0x") {
        mac_decode_security_cli_hex_password(hex_and_preview)?
    } else {
        mac_decode_security_cli_quoted_password(payload)?
    };

    String::from_utf8(bytes).map_err(|e| {
        SecretError::Backend(format!(
            "/usr/bin/security find-generic-password password was not valid utf-8: {}",
            e
        ))
    })
}

#[cfg(target_os = "macos")]
fn mac_security_cli_text<'a>(bytes: &'a [u8], stream: &str) -> Result<&'a str, SecretError> {
    std::str::from_utf8(bytes).map_err(|e| {
        SecretError::Backend(format!(
            "/usr/bin/security find-generic-password {stream} was not valid utf-8: {e}"
        ))
    })
}

#[cfg(target_os = "macos")]
fn mac_decode_security_cli_hex_password(hex_and_preview: &str) -> Result<Vec<u8>, SecretError> {
    let hex: String = hex_and_preview
        .chars()
        .take_while(|c| c.is_ascii_hexdigit())
        .collect();
    if hex.is_empty() || !hex.len().is_multiple_of(2) {
        return Err(SecretError::Backend(format!(
            "/usr/bin/security find-generic-password printed invalid password hex: {hex:?}"
        )));
    }

    (0..hex.len())
        .step_by(2)
        .map(|i| {
            u8::from_str_radix(&hex[i..i + 2], 16).map_err(|e| {
                SecretError::Backend(format!(
                    "/usr/bin/security find-generic-password printed invalid password hex: {e}"
                ))
            })
        })
        .collect()
}

#[cfg(target_os = "macos")]
fn mac_decode_security_cli_quoted_password(payload: &str) -> Result<Vec<u8>, SecretError> {
    let quoted = payload.strip_prefix('"').and_then(|s| s.strip_suffix('"'));
    match quoted {
        Some(value) => Ok(value.as_bytes().to_vec()),
        None => Err(SecretError::Backend(
            "/usr/bin/security find-generic-password printed an unrecognized password line"
                .to_string(),
        )),
    }
}

#[cfg(target_os = "macos")]
fn mac_status_via_security_cli(r: &SecretRef) -> Result<SecretStatus, SecretError> {
    mac_status_via_security_cli_with(r, &SystemSecurityCli)
}

#[cfg(target_os = "macos")]
fn mac_status_via_security_cli_with(
    r: &SecretRef,
    cli: &impl SecurityCli,
) -> Result<SecretStatus, SecretError> {
    let exists = mac_exists_via_security_cli_with(r, cli)?;
    Ok(SecretStatus {
        service: r.service.clone(),
        key: r.key.clone(),
        exists,
    })
}

/// Existence-only shell-out: `security find-generic-password -s SVC -a KEY`
/// (no `-w`). Exit 0 means found, exit 44 means absent. Other non-zero
/// exits are backend/authorization errors and must not fall through to
/// an in-process API that can prompt again under the caller binary's CDHash.
#[cfg(target_os = "macos")]
fn mac_exists_via_security_cli_with(
    r: &SecretRef,
    cli: &impl SecurityCli,
) -> Result<bool, SecretError> {
    let output = cli
        .output(&["find-generic-password", "-s", &r.service, "-a", &r.key])
        .map_err(|e| security_cli_spawn_error("find-generic-password", e))?;
    if output.success {
        return Ok(true);
    }
    if output.code == Some(SECURITY_ERR_SEC_ITEM_NOT_FOUND) {
        return Ok(false);
    }
    Err(security_cli_backend_error("find-generic-password", output))
}

#[cfg(target_os = "macos")]
fn mac_delete_via_security_cli(r: &SecretRef) -> Result<(), SecretError> {
    mac_delete_via_security_cli_with(r, &SystemSecurityCli)
}

/// Primary macOS delete. Treats "no such item" as success to preserve
/// the public idempotent delete contract.
#[cfg(target_os = "macos")]
fn mac_delete_via_security_cli_with(
    r: &SecretRef,
    cli: &impl SecurityCli,
) -> Result<(), SecretError> {
    let output = cli
        .output(&["delete-generic-password", "-s", &r.service, "-a", &r.key])
        .map_err(|e| security_cli_spawn_error("delete-generic-password", e))?;
    if output.success || output.code == Some(SECURITY_ERR_SEC_ITEM_NOT_FOUND) {
        return Ok(());
    }
    Err(security_cli_backend_error(
        "delete-generic-password",
        output,
    ))
}

#[cfg(target_os = "macos")]
fn security_cli_not_found_or_backend<T>(
    command: &str,
    r: &SecretRef,
    output: SecurityCliOutput,
) -> Result<T, SecretError> {
    if output.code == Some(SECURITY_ERR_SEC_ITEM_NOT_FOUND) {
        return Err(SecretError::NotFound {
            service: r.service.clone(),
            key: r.key.clone(),
        });
    }
    Err(security_cli_backend_error(command, output))
}

#[cfg(target_os = "macos")]
fn security_cli_spawn_error(command: &str, e: std::io::Error) -> SecretError {
    SecretError::Backend(format!("/usr/bin/security {command} spawn: {e}"))
}

#[cfg(target_os = "macos")]
fn security_cli_backend_error(command: &str, output: SecurityCliOutput) -> SecretError {
    let stderr = String::from_utf8_lossy(&output.stderr);
    if output.timed_out {
        return classify_helper_timeout(command);
    }
    let code = output.code.unwrap_or(-1);
    match classify_security_error(code, stderr.trim()) {
        SecretError::Backend(_) => SecretError::Backend(format!(
            "/usr/bin/security {command} failed: code={code} {}",
            stderr.trim()
        )),
        typed => typed,
    }
}

#[cfg(target_os = "macos")]
fn classify_security_error(code: i32, detail: &str) -> SecretError {
    let normalized = detail.to_ascii_lowercase();
    if code == -128 || (code == 128 && normalized.contains("cancel")) {
        return SecretError::UserCancelled {
            message: detail.to_string(),
        };
    }
    if code == -25293
        || code == 51
        || normalized.contains("authorization denied")
        || normalized.contains("auth denied")
        || normalized.contains("interaction is not allowed")
    {
        return SecretError::AccessDenied {
            message: detail.to_string(),
        };
    }
    SecretError::Backend(format!("macOS security error: code={code} {detail}"))
}

#[cfg(target_os = "macos")]
fn classify_helper_timeout(operation: &str) -> SecretError {
    SecretError::HelperTimedOut {
        operation: operation.to_string(),
    }
}

/// Map keyring crate errors into our typed error set.
///
/// Not compiled on macOS: nothing there reaches the keyring crate, so there
/// are no keyring errors to classify. The macOS equivalents are
/// `security_cli_backend_error` and `security_cli_not_found_or_backend`.
#[cfg(not(target_os = "macos"))]
fn classify(e: keyring::Error, op: &str) -> SecretError {
    use keyring::Error as K;
    match e {
        K::NoEntry => SecretError::NotFound {
            service: String::new(),
            key: String::new(),
        },
        K::PlatformFailure(inner) => SecretError::Unavailable(format!("{}: {}", op, inner)),
        K::NoStorageAccess(inner) => SecretError::Unavailable(format!("{}: {}", op, inner)),
        K::BadEncoding(_) => SecretError::Backend(format!("{}: value encoding", op)),
        other => SecretError::Backend(format!("{}: {}", op, other)),
    }
}

#[cfg(test)]
mod chunk_tests {
    use super::*;
    use std::collections::BTreeMap;

    #[test]
    fn split_on_chars_covers_boundaries() {
        assert_eq!(split_on_chars("", 3), Vec::<String>::new());
        assert_eq!(split_on_chars("abc", 3), vec!["abc"]);
        assert_eq!(split_on_chars("abcd", 3), vec!["abc", "d"]);
        assert_eq!(split_on_chars("abcdef", 2), vec!["ab", "cd", "ef"]);
        // Reassembly is lossless for a value well past the Windows blob cap.
        let big: String = "x".repeat(4000);
        let joined: String = split_on_chars(&big, CHUNK_CHARS).concat();
        assert_eq!(joined, big);
    }

    #[test]
    fn sentinel_round_trips_the_chunk_count() {
        let n = split_on_chars(&"y".repeat(3300), CHUNK_CHARS).len();
        let sentinel = format!("{CHUNK_SENTINEL}{n}");
        let parsed = sentinel
            .strip_prefix(CHUNK_SENTINEL)
            .and_then(|s| s.parse::<usize>().ok());
        assert_eq!(parsed, Some(4)); // 3300 / 1000 -> 4 chunks
                                     // A real (non-chunked) value is never mistaken for a sentinel.
        assert!("eyJhbGciOi.reallongjwt"
            .strip_prefix(CHUNK_SENTINEL)
            .is_none());
    }

    #[test]
    fn threshold_leaves_small_values_inline() {
        // A value at/under the threshold must NOT be chunked (single entry,
        // backward compatible with pre-existing secrets).
        assert!("short-api-key".encode_utf16().count() <= CHUNK_THRESHOLD_UTF16);
        assert!("z".repeat(2001).encode_utf16().count() > CHUNK_THRESHOLD_UTF16);
    }

    #[derive(Debug, Clone)]
    struct FailureRule {
        slot: WindowsCredentialSlot,
        matches_to_skip: usize,
    }

    #[derive(Debug, Clone, Default)]
    struct MemoryWindowsBackend {
        entries: BTreeMap<WindowsCredentialSlot, String>,
        mutation_calls: usize,
        crash_after_mutation: Option<usize>,
        fail_write: Option<FailureRule>,
        fail_delete: Option<FailureRule>,
    }

    impl MemoryWindowsBackend {
        fn after_mutation(&mut self) {
            self.mutation_calls += 1;
            if self.crash_after_mutation == Some(self.mutation_calls) {
                panic!("injected Windows credential process crash");
            }
        }

        fn should_fail(rule: &mut Option<FailureRule>, slot: &WindowsCredentialSlot) -> bool {
            let Some(candidate) = rule.as_mut() else {
                return false;
            };
            if &candidate.slot != slot {
                return false;
            }
            if candidate.matches_to_skip > 0 {
                candidate.matches_to_skip -= 1;
                return false;
            }
            *rule = None;
            true
        }

        fn reset_faults(&mut self) {
            self.mutation_calls = 0;
            self.crash_after_mutation = None;
            self.fail_write = None;
            self.fail_delete = None;
        }

        fn root(&self) -> String {
            self.entries
                .get(&WindowsCredentialSlot::Root)
                .expect("root credential")
                .clone()
        }
    }

    impl WindowsCredentialBackend for MemoryWindowsBackend {
        fn read(&mut self, slot: &WindowsCredentialSlot) -> Result<Option<String>, SecretError> {
            Ok(self.entries.get(slot).cloned())
        }

        fn write(&mut self, slot: &WindowsCredentialSlot, value: &str) -> Result<(), SecretError> {
            if Self::should_fail(&mut self.fail_write, slot) {
                return Err(SecretError::Backend(
                    "injected Windows credential write failure".to_string(),
                ));
            }
            self.entries.insert(slot.clone(), value.to_string());
            self.after_mutation();
            Ok(())
        }

        fn delete(&mut self, slot: &WindowsCredentialSlot) -> Result<(), SecretError> {
            if Self::should_fail(&mut self.fail_delete, slot) {
                return Err(SecretError::Backend(
                    "injected Windows credential cleanup failure".to_string(),
                ));
            }
            self.entries.remove(slot);
            self.after_mutation();
            Ok(())
        }
    }

    fn publish(backend: &mut MemoryWindowsBackend, value: &str) -> WindowsCleanupReport {
        publish_windows_value(backend, value).expect("publication")
    }

    fn read(backend: &mut impl WindowsCredentialBackend) -> String {
        read_windows_value(backend)
            .expect("read succeeds")
            .expect("root exists")
    }

    fn legacy_v2(value: &str, nonce: &str) -> MemoryWindowsBackend {
        let mut backend = MemoryWindowsBackend::default();
        let chunks = split_on_chars(value, CHUNK_CHARS);
        backend.entries.insert(
            WindowsCredentialSlot::Root,
            format!("{CHUNK_SENTINEL_V2}{nonce}:{}", chunks.len()),
        );
        for (index, chunk) in chunks.into_iter().enumerate() {
            backend.entries.insert(
                WindowsCredentialSlot::LegacyV2Chunk {
                    nonce: nonce.to_string(),
                    index,
                },
                chunk,
            );
        }
        backend
    }

    fn assert_backend_error(error: SecretError, needle: &str) {
        match error {
            SecretError::Backend(message) => assert!(message.contains(needle), "{message}"),
            other => panic!("expected backend error, got {other:?}"),
        }
    }

    #[test]
    fn v3_publication_uses_revisioned_dual_generation_roots() {
        let value = "v".repeat(3300);
        let plan = chunk_publication_plan(&value, ChunkGeneration::B, "revision-7").unwrap();

        assert_eq!(plan.generation, ChunkGeneration::B);
        assert_eq!(plan.chunks.concat(), value);
        assert_eq!(
            windows_root_layout(&plan.root).unwrap(),
            WindowsRootLayout::V3 {
                generation: ChunkGeneration::B,
                revision: "revision-7".to_string(),
                count: 4,
            }
        );
        assert!(
            plan.chunks
                .iter()
                .all(|chunk| chunk.encode_utf16().count() <= CHUNK_CHARS),
            "every staged credential must remain below the platform cap"
        );
    }

    #[test]
    fn reader_capturing_old_root_finishes_after_writer_swaps_root() {
        let old = "old-".repeat(900);
        let new = "new-".repeat(900);
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &old);

        let mut reader = InterleavingReader::new(backend, vec![new.as_str()]);
        assert_eq!(read(&mut reader), old);
        assert_eq!(read(&mut reader.inner), new);
    }

    #[test]
    fn reader_detects_generation_aba_and_retries_latest_root() {
        let old = "old-".repeat(900);
        let middle = "mid-".repeat(1100);
        let latest = "latest-".repeat(700);
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &old);

        let mut reader = InterleavingReader::new(backend, vec![middle.as_str(), latest.as_str()]);
        assert_eq!(read(&mut reader), latest);
        assert!(reader.root_reads >= 4, "the ABA path must consume a retry");
    }

    #[test]
    fn legacy_nonce_chunks_survive_the_first_v3_root_swap_then_recover() {
        let old = "legacy-".repeat(700);
        let replacement = "replacement-".repeat(500);
        let followup = "followup-".repeat(500);
        let backend = legacy_v2(&old, "legacy-nonce");

        let mut reader = InterleavingReader::new(backend, vec![replacement.as_str()]);
        assert_eq!(read(&mut reader), old);
        assert!(reader
            .inner
            .entries
            .contains_key(&WindowsCredentialSlot::RetiredV2Manifest));
        assert!(reader
            .inner
            .entries
            .contains_key(&WindowsCredentialSlot::LegacyV2Chunk {
                nonce: "legacy-nonce".to_string(),
                index: 0,
            }));

        publish(&mut reader.inner, &followup);
        assert!(!reader
            .inner
            .entries
            .contains_key(&WindowsCredentialSlot::RetiredV2Manifest));
        assert!(!reader.inner.entries.keys().any(|slot| matches!(
            slot,
            WindowsCredentialSlot::LegacyV2Chunk { nonce, .. } if nonce == "legacy-nonce"
        )));
    }

    #[test]
    fn crash_after_every_publish_mutation_preserves_a_readable_generation() {
        let old = "old-".repeat(1200);
        let current = "current-".repeat(900);
        let replacement = "replacement-".repeat(300);
        let mut base = MemoryWindowsBackend::default();
        publish(&mut base, &old);
        publish(&mut base, &current);
        base.reset_faults();

        let mut successful = base.clone();
        publish(&mut successful, &replacement);
        let mutation_count = successful.mutation_calls;
        assert!(mutation_count >= 7, "exercise stage, commit, and cleanup");

        for crash_after in 1..=mutation_count {
            let mut crashed = base.clone();
            crashed.crash_after_mutation = Some(crash_after);
            let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let _ = publish_windows_value(&mut crashed, &replacement);
            }));
            assert!(unwind.is_err(), "mutation {crash_after} must crash");
            crashed.reset_faults();

            let observed = read(&mut crashed);
            assert!(
                observed == current || observed == replacement,
                "crash {crash_after} exposed neither committed generation"
            );

            publish(&mut crashed, &replacement);
            publish(&mut crashed, "recovery-pass");
            publish(&mut crashed, &replacement);
            assert_eq!(read(&mut crashed), replacement);
            assert!(
                crashed.entries.len() <= 20,
                "crash {crash_after} leaked unbounded entries: {:?}",
                crashed.entries.keys().collect::<Vec<_>>()
            );
        }
    }

    #[test]
    fn repeated_precommit_crashes_have_bounded_cardinality_and_recover_cleanup() {
        let old = "old-".repeat(900);
        let attempted = "attempted-".repeat(900);
        let recovered = "ok-".repeat(600);
        let attempted_chunks = split_on_chars(&attempted, CHUNK_CHARS).len();
        let old_chunks = split_on_chars(&old, CHUNK_CHARS).len();
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &old);

        for crash_index in 0..64 {
            backend.reset_faults();
            backend.crash_after_mutation = Some(1 + crash_index % attempted_chunks);
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let _ = publish_windows_value(&mut backend, &attempted);
            }));
            assert!(
                backend.entries.len() <= 1 + 2 + old_chunks + attempted_chunks,
                "attempt {crash_index} grew deterministic storage"
            );
        }

        backend.reset_faults();
        publish(&mut backend, &recovered);
        assert_eq!(read(&mut backend), recovered);
        let recovered_chunks = split_on_chars(&recovered, CHUNK_CHARS).len();
        assert!(!backend.entries.keys().any(|slot| matches!(
            slot,
            WindowsCredentialSlot::V3Chunk {
                generation: ChunkGeneration::B,
                index,
            } if *index >= recovered_chunks
        )));
        assert_eq!(
            backend
                .entries
                .get(&WindowsCredentialSlot::V3Manifest(ChunkGeneration::B)),
            Some(&recovered_chunks.to_string())
        );
    }

    #[test]
    fn staging_and_root_failures_leave_the_only_good_generation_readable() {
        let old = "old-".repeat(900);
        let replacement = "replacement-".repeat(500);
        for failed_slot in [
            WindowsCredentialSlot::V3Chunk {
                generation: ChunkGeneration::B,
                index: 1,
            },
            WindowsCredentialSlot::Root,
        ] {
            let mut backend = MemoryWindowsBackend::default();
            publish(&mut backend, &old);
            backend.fail_write = Some(FailureRule {
                slot: failed_slot,
                matches_to_skip: 0,
            });

            let error = publish_windows_value(&mut backend, &replacement).unwrap_err();
            assert_backend_error(error, "injected");
            assert_eq!(read(&mut backend), old);
        }
    }

    #[test]
    fn postcommit_cleanup_errors_report_deferred_success_and_recover_later() {
        let old = "old-".repeat(1400);
        let current = "current-".repeat(900);
        let replacement = "replacement-".repeat(200);
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &old);
        publish(&mut backend, &current);
        backend.fail_delete = Some(FailureRule {
            slot: WindowsCredentialSlot::V3Chunk {
                generation: ChunkGeneration::A,
                index: 4,
            },
            matches_to_skip: 0,
        });

        let cleanup = publish_windows_value(&mut backend, &replacement).unwrap();
        assert_eq!(cleanup.failures, 1);
        assert_eq!(read(&mut backend), replacement);
        assert_eq!(
            backend
                .entries
                .get(&WindowsCredentialSlot::V3Manifest(ChunkGeneration::A)),
            Some(&split_on_chars(&old, CHUNK_CHARS).len().to_string()),
            "failed cleanup keeps the crash high-water for a later sweep"
        );

        publish(&mut backend, "rotate-once");
        publish(&mut backend, &replacement);
        assert!(!backend.entries.keys().any(|slot| matches!(
            slot,
            WindowsCredentialSlot::V3Chunk {
                generation: ChunkGeneration::A,
                index,
            } if *index >= split_on_chars(&replacement, CHUNK_CHARS).len()
        )));
    }

    #[test]
    fn postcommit_manifest_shrink_failure_keeps_recovery_high_water() {
        let old = "old-".repeat(1400);
        let current = "current-".repeat(900);
        let replacement = "replacement-".repeat(200);
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &old);
        publish(&mut backend, &current);
        backend.fail_write = Some(FailureRule {
            slot: WindowsCredentialSlot::V3Manifest(ChunkGeneration::A),
            matches_to_skip: 1,
        });

        let cleanup = publish_windows_value(&mut backend, &replacement).unwrap();
        assert_eq!(cleanup.failures, 1);
        assert_eq!(read(&mut backend), replacement);
        assert_eq!(
            backend
                .entries
                .get(&WindowsCredentialSlot::V3Manifest(ChunkGeneration::A)),
            Some(&split_on_chars(&old, CHUNK_CHARS).len().to_string())
        );
    }

    #[test]
    fn delete_cleanup_failure_retains_manifest_for_idempotent_recovery() {
        let value = "secret-".repeat(700);
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &value);
        backend.fail_delete = Some(FailureRule {
            slot: WindowsCredentialSlot::V3Chunk {
                generation: ChunkGeneration::A,
                index: 0,
            },
            matches_to_skip: 0,
        });

        let cleanup = delete_windows_value(&mut backend).unwrap();
        assert_eq!(cleanup.failures, 1);
        assert!(!backend.entries.contains_key(&WindowsCredentialSlot::Root));
        assert!(backend
            .entries
            .contains_key(&WindowsCredentialSlot::V3Manifest(ChunkGeneration::A)));

        backend.reset_faults();
        assert_eq!(delete_windows_value(&mut backend).unwrap().failures, 0);
        assert!(backend.entries.is_empty());
    }

    #[test]
    fn corrupt_cleanup_metadata_fails_before_root_or_chunks_are_deleted() {
        let old = "old-".repeat(900);
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &old);
        let root_before = backend.root();
        backend.entries.insert(
            WindowsCredentialSlot::V3Manifest(ChunkGeneration::B),
            "not-a-count".to_string(),
        );

        let error = publish_windows_value(&mut backend, "replacement").unwrap_err();
        assert_backend_error(error, "manifest");
        assert_eq!(backend.root(), root_before);
        assert_eq!(read(&mut backend), old);

        let error = delete_windows_value(&mut backend).unwrap_err();
        assert_backend_error(error, "manifest");
        assert_eq!(backend.root(), root_before);
        assert_eq!(read(&mut backend), old);
    }

    #[test]
    fn reader_retry_is_bounded_when_root_never_stabilizes() {
        let value_a = "a".repeat(2500);
        let value_b = "b".repeat(2500);
        let mut backend = MemoryWindowsBackend::default();
        publish(&mut backend, &value_a);
        let root_a = backend.root();
        publish(&mut backend, &value_b);
        let root_b = backend.root();
        backend.entries.remove(&WindowsCredentialSlot::V3Chunk {
            generation: ChunkGeneration::A,
            index: 0,
        });
        let mut churning = AlternatingRootBackend {
            inner: backend,
            roots: [root_a, root_b],
            root_reads: 0,
        };

        let error = read_windows_value(&mut churning).unwrap_err();
        assert_backend_error(error, "changed during every read attempt");
        assert_eq!(churning.root_reads, WINDOWS_READ_ATTEMPTS * 2);
    }

    struct InterleavingReader<'a> {
        inner: MemoryWindowsBackend,
        publications: Vec<&'a str>,
        root_reads: usize,
    }

    impl<'a> InterleavingReader<'a> {
        fn new(inner: MemoryWindowsBackend, publications: Vec<&'a str>) -> Self {
            Self {
                inner,
                publications,
                root_reads: 0,
            }
        }
    }

    impl WindowsCredentialBackend for InterleavingReader<'_> {
        fn read(&mut self, slot: &WindowsCredentialSlot) -> Result<Option<String>, SecretError> {
            let captured = self.inner.read(slot)?;
            if slot == &WindowsCredentialSlot::Root && self.root_reads == 0 {
                for value in self.publications.drain(..) {
                    publish_windows_value(&mut self.inner, value)?;
                }
            }
            if slot == &WindowsCredentialSlot::Root {
                self.root_reads += 1;
            }
            Ok(captured)
        }

        fn write(&mut self, slot: &WindowsCredentialSlot, value: &str) -> Result<(), SecretError> {
            self.inner.write(slot, value)
        }

        fn delete(&mut self, slot: &WindowsCredentialSlot) -> Result<(), SecretError> {
            self.inner.delete(slot)
        }
    }

    struct AlternatingRootBackend {
        inner: MemoryWindowsBackend,
        roots: [String; 2],
        root_reads: usize,
    }

    impl WindowsCredentialBackend for AlternatingRootBackend {
        fn read(&mut self, slot: &WindowsCredentialSlot) -> Result<Option<String>, SecretError> {
            if slot == &WindowsCredentialSlot::Root {
                let root = self.roots[self.root_reads % self.roots.len()].clone();
                self.root_reads += 1;
                return Ok(Some(root));
            }
            self.inner.read(slot)
        }

        fn write(&mut self, slot: &WindowsCredentialSlot, value: &str) -> Result<(), SecretError> {
            self.inner.write(slot, value)
        }

        fn delete(&mut self, slot: &WindowsCredentialSlot) -> Result<(), SecretError> {
            self.inner.delete(slot)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    /// An unusable store must not answer "that secret is absent".
    ///
    /// These three take no env lock: they call the file-backend helpers with an
    /// explicit `dir`, so they touch no process-global state.
    ///
    /// The distinction is invisible on unix, where an entry under a regular file
    /// fails with `ENOTDIR`, and load-bearing on Windows, where the same open
    /// returns `ERROR_PATH_NOT_FOUND` and Rust maps it to `NotFound`. Asserting
    /// it here keeps both platforms honest without needing a Windows runner to
    /// notice the regression.
    #[test]
    fn a_store_that_is_not_a_directory_is_a_backend_error_not_a_missing_secret() {
        let parent = tempfile::tempdir().unwrap();
        let not_a_dir = parent.path().join("blocked");
        std::fs::write(&not_a_dir, b"a regular file where the store should be").unwrap();
        let reference = SecretRef::with_default_service("SOME_KEY");

        assert!(
            !file_backend_entry_is_merely_absent(&not_a_dir),
            "the platform-neutral discriminator must reject a regular-file store root"
        );

        match file_backend_get(&not_a_dir, &reference) {
            Err(SecretError::Backend(_)) => {}
            other => panic!("unusable store must report a backend error, got {other:?}"),
        }
        match file_backend_delete(&not_a_dir, &reference) {
            Err(SecretError::Backend(_)) => {}
            other => panic!("unusable store must not report a successful delete, got {other:?}"),
        }
        assert!(
            !file_backend_status(&not_a_dir, &reference).exists,
            "status on an unusable store must not claim knowledge of the entry"
        );
    }

    /// A store directory that has not been created yet is a first run, not a
    /// broken store: only `put`/`publish` create it.
    #[test]
    fn a_store_directory_that_does_not_exist_yet_is_still_not_found() {
        let parent = tempfile::tempdir().unwrap();
        let never_created = parent.path().join("not-created-yet");
        assert!(!never_created.exists());
        assert!(
            file_backend_entry_is_merely_absent(&never_created),
            "a missing directory beneath an existing directory is a normal first run"
        );
        let reference = SecretRef::with_default_service("SOME_KEY");

        match file_backend_get(&never_created, &reference) {
            Err(SecretError::NotFound { .. }) => {}
            other => panic!("a first-run store has no secrets, it is not broken: {other:?}"),
        }
        assert!(
            file_backend_delete(&never_created, &reference).is_ok(),
            "deleting from a store that was never written is a no-op success"
        );
        assert!(!file_backend_status(&never_created, &reference).exists);
    }

    #[test]
    fn a_missing_entry_in_a_real_directory_is_still_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let reference = SecretRef::with_default_service("ABSENT_KEY");

        match file_backend_get(dir.path(), &reference) {
            Err(SecretError::NotFound { .. }) => {}
            other => panic!("an absent entry in a usable store is NotFound, got {other:?}"),
        }
        assert!(
            file_backend_delete(dir.path(), &reference).is_ok(),
            "deleting an absent entry from a usable store is a no-op success"
        );
        assert!(!file_backend_status(dir.path(), &reference).exists);
    }

    /// Process-wide serialization lock for every test that touches the secret
    /// store. `CAR_SECRETS_FILE_DIR` is process-global, so an isolated-backend
    /// fixture must not change it while another store test is running.
    /// `unwrap_or_else(into_inner)` keeps the suite running if one test panics
    /// while holding it.
    static STORE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn lock_store() -> std::sync::MutexGuard<'static, ()> {
        STORE_LOCK.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Parallel-suite-safe fixture for public `SecretStore` contract tests.
    /// The lock makes the process environment transition atomic, while each
    /// fixture gets a fresh directory. `Drop` restores an inherited redirect
    /// rather than assuming the caller had none.
    struct IsolatedStoreFixture {
        _guard: std::sync::MutexGuard<'static, ()>,
        _dir: tempfile::TempDir,
        previous_dir: Option<std::ffi::OsString>,
    }

    impl IsolatedStoreFixture {
        fn new() -> Self {
            let guard = lock_store();
            let dir = tempfile::tempdir().expect("isolated secret-store directory");
            let previous_dir = std::env::var_os("CAR_SECRETS_FILE_DIR");
            std::env::set_var("CAR_SECRETS_FILE_DIR", dir.path());
            assert_eq!(
                file_backend_dir().as_deref(),
                Some(dir.path()),
                "contract test must use the isolated file backend"
            );
            Self {
                _guard: guard,
                _dir: dir,
                previous_dir,
            }
        }

        fn store(&self) -> SecretStore {
            SecretStore::new()
        }
    }

    impl Drop for IsolatedStoreFixture {
        fn drop(&mut self) {
            match self.previous_dir.take() {
                Some(value) => std::env::set_var("CAR_SECRETS_FILE_DIR", value),
                None => std::env::remove_var("CAR_SECRETS_FILE_DIR"),
            }
        }
    }

    // Provisioned native-keychain runs use a unique service name to avoid
    // colliding with real credentials a developer has in their keychain.
    #[cfg(target_os = "macos")]
    fn test_service() -> String {
        format!(
            "car-secrets-tests-{}-{}",
            std::process::id(),
            // Nanos since startup — good enough to isolate tests running
            // in parallel inside one process.
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        )
    }

    #[cfg(target_os = "macos")]
    const NATIVE_KEYCHAIN_LANE: &str = "CAR_TEST_NATIVE_KEYCHAIN";

    #[cfg(target_os = "macos")]
    fn run_native_keychain_lane() {
        assert!(
            std::env::var_os("CAR_SECRETS_FILE_DIR").is_none(),
            "native lane refuses CAR_SECRETS_FILE_DIR; run it against the provisioned keychain"
        );
        let store = SecretStore::new();
        let availability = store.availability();
        assert!(
            availability.available,
            "native keychain unavailable: {}",
            availability
                .reason
                .unwrap_or_else(|| "no reason reported".to_string())
        );

        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Session {
            cookies: Vec<String>,
            expires_at: i64,
        }

        let reference = SecretRef::new(test_service(), "provisioned-native-contracts");
        store
            .delete(&reference)
            .expect("clean native fixture before run");
        assert!(matches!(
            store.get(&reference),
            Err(SecretError::NotFound { .. })
        ));
        store.put(&reference, "abc\n").expect("write native secret");
        assert_eq!(store.get(&reference).unwrap(), "abc\n");
        let status = store.status(&reference).unwrap();
        assert!(status.exists);
        assert!(!serde_json::to_string(&status).unwrap().contains("abc"));
        let session = Session {
            cookies: vec!["a=1".into(), "b=2".into()],
            expires_at: 1_700_000_000,
        };
        store.put_json(&reference, &session).unwrap();
        assert_eq!(store.get_json::<Session>(&reference).unwrap(), session);
        store
            .delete(&reference)
            .expect("clean native fixture after run");
        store
            .delete(&reference)
            .expect("native delete is idempotent");
        assert!(!store.status(&reference).unwrap().exists);
    }

    /// S2 — the opt-in file backend is honored in a debug/test build, drives a
    /// real `put`/`get`/`delete` round-trip through the plaintext file path, and
    /// `availability` still reports healthy (it's just the local filesystem).
    ///
    /// `cargo test` builds with `debug_assertions` on, so `file_backend_dir()`
    /// honors `CAR_SECRETS_FILE_DIR` here. A RELEASE binary returns `None` from
    /// `file_backend_dir()` regardless — production can never reach this path.
    ///
    /// The env var is process-global; this test sets it, runs, then removes it.
    /// `STORE_LOCK` serializes that transition against the focused contract
    /// fixtures below.
    /// A `MakeWriter` that appends every emitted log line into a shared buffer
    /// so the test can assert the one-time file-backend warning actually fired.
    #[derive(Clone)]
    struct BufWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

    impl std::io::Write for BufWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for BufWriter {
        type Writer = BufWriter;
        fn make_writer(&'a self) -> Self::Writer {
            self.clone()
        }
    }

    #[test]
    fn file_backend_roundtrip_and_warn_under_debug() {
        const CHILD: &str = "CAR_TEST_FILE_BACKEND_WARNING_CHILD";
        if std::env::var_os(CHILD).is_none() {
            let output =
                std::process::Command::new(std::env::current_exe().expect("test executable"))
                    .args([
                        "--exact",
                        "tests::file_backend_roundtrip_and_warn_under_debug",
                        "--nocapture",
                    ])
                    .env(CHILD, "1")
                    .env_remove("CAR_SECRETS_FILE_DIR")
                    .env_remove("CAR_TEST_PRECONSUME_FILE_BACKEND_WARNING")
                    .env_remove("CAR_KEYCHAIN_PROOF_ROOT")
                    .env_remove("CAR_KEYCHAIN_PATH")
                    .output()
                    .expect("spawn isolated file-backend warning test");
            assert!(
                output.status.success(),
                "isolated file-backend warning test failed\nstdout:\n{}\nstderr:\n{}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr),
            );
            return;
        }

        // Test hook for the isolation regression: model another parallel test
        // engaging the process-wide file backend before this test installs its
        // tracing subscriber.
        if std::env::var_os("CAR_TEST_PRECONSUME_FILE_BACKEND_WARNING").is_some() {
            let _ = file_backend_dir();
        }
        // Hold the store lock for the WHOLE test: while the global redirect env
        // var is set, no parallel keychain test may run.
        let _guard = lock_store();
        // Sanity: this whole seam only exists in debug builds. The asserted
        // value is a compile-time constant on purpose — it documents the
        // debug-build dependency, so silence the constant-assertion lint.
        #[allow(clippy::assertions_on_constants)]
        {
            assert!(
                cfg!(debug_assertions),
                "the crate test suite runs in debug; the file backend depends on it"
            );
        }

        let dir = std::env::temp_dir().join(format!(
            "car-secrets-filebackend-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        std::fs::create_dir_all(&dir).unwrap();
        std::env::set_var("CAR_SECRETS_FILE_DIR", &dir);

        // Capture logs so we can assert the one-time warning fires the first
        // time the redirect engages in this process.
        let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
        let subscriber = tracing_subscriber::fmt()
            .with_writer(BufWriter(buf.clone()))
            .with_max_level(tracing::Level::WARN)
            .finish();
        tracing::subscriber::with_default(subscriber, || {
            // The redirect is honored (Some) — and fires the one-time warn the
            // first time it engages in this process.
            assert_eq!(
                file_backend_dir().as_deref(),
                Some(dir.as_path()),
                "CAR_SECRETS_FILE_DIR must be honored under debug_assertions"
            );
        });
        let logged = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
        assert!(
            logged.contains("PLAINTEXT ON DISK"),
            "the file backend must emit the one-time PLAINTEXT warning, got logs: {logged:?}"
        );

        let store = SecretStore::new();
        // availability_check still reports healthy on the file backend.
        let check = store.availability();
        assert!(check.available, "file backend must report available");
        assert!(check.reason.is_none());

        // Real put/get/delete round-trip through the plaintext file path.
        let r = SecretRef::new("svc", "key");
        store.put(&r, "xoxb-plaintext-value").unwrap();
        assert_eq!(store.get(&r).unwrap(), "xoxb-plaintext-value");
        // The value really is plaintext on disk (the documented trade-off).
        let on_disk = std::fs::read_to_string(file_backend_path(&dir, &r)).unwrap();
        assert_eq!(on_disk, "xoxb-plaintext-value");
        store.delete(&r).unwrap();
        match store.get(&r) {
            Err(SecretError::NotFound { .. }) => {}
            other => panic!("expected NotFound after delete, got {other:?}"),
        }

        // The reserved-slot guard lives in generic wrappers, not SecretStore:
        // Daemon-owned code must still be able to lease and delete every exact
        // internal slot directly even though generic wrappers reject them.
        for key in [
            OPENROUTER_OAUTH_KEY,
            PARSLEE_ACCESS_TOKEN_KEY,
            PARSLEE_REFRESH_TOKEN_KEY,
            PARSLEE_EXPIRES_AT_KEY,
            PARSLEE_API_BASE_KEY,
            PARSLEE_ACCOUNTS_KEY,
            "PARSLEE_TOKENS_account-1",
            PARSLEE_AUTH_GENERATION_KEY,
            PARSLEE_AUTH_COMPLETION_KEY,
            PARSLEE_ACTIVE_ACCOUNT_ID_KEY,
            PARSLEE_AUTH_STATE_V2_KEY,
        ] {
            let private = SecretRef::new(DEFAULT_SERVICE, key);
            assert!(is_daemon_private_secret(&private.service, &private.key));
            store.put(&private, "internal-test-value").unwrap();
            assert_eq!(store.get(&private).unwrap(), "internal-test-value");
            store.delete(&private).unwrap();
            assert!(matches!(
                store.get(&private),
                Err(SecretError::NotFound { .. })
            ));
        }

        // Restore process state so no parallel/later test inherits the redirect.
        std::env::remove_var("CAR_SECRETS_FILE_DIR");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn every_parslee_auth_slot_is_private_to_the_dedicated_auth_surface() {
        for key in [
            PARSLEE_ACCESS_TOKEN_KEY,
            PARSLEE_REFRESH_TOKEN_KEY,
            PARSLEE_EXPIRES_AT_KEY,
            PARSLEE_API_BASE_KEY,
            PARSLEE_ACCOUNTS_KEY,
            "PARSLEE_TOKENS_account-1",
            PARSLEE_ACTIVE_ACCOUNT_ID_KEY,
            PARSLEE_AUTH_GENERATION_KEY,
            PARSLEE_AUTH_COMPLETION_KEY,
            PARSLEE_AUTH_STATE_V2_KEY,
        ] {
            assert!(
                is_daemon_private_secret(DEFAULT_SERVICE, key),
                "{key} must be unreachable through generic secret surfaces"
            );
            assert!(
                !is_daemon_private_secret("other-service", key),
                "reservation must remain scoped to the CAR service"
            );
        }

        assert!(!is_daemon_private_secret(
            DEFAULT_SERVICE,
            "OPENROUTER_API_KEY"
        ));
        for key in [
            format!("{PARSLEE_AUTH_STATE_V2_KEY}#chunk0"),
            format!("{PARSLEE_AUTH_STATE_V2_KEY}#chunkv2#nonce-1#0"),
            format!("{OPENROUTER_OAUTH_KEY}#chunk17"),
            format!("{OPENROUTER_OAUTH_KEY}#chunkv2#nonce-2#3"),
        ] {
            assert!(
                is_daemon_private_secret(DEFAULT_SERVICE, &key),
                "{key} is derived from a daemon-private root"
            );
            assert!(!is_daemon_private_secret("other-service", &key));
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn bounded_command_output_large_helper() {
        if std::env::var_os("CAR_SECURITY_OUTPUT_HELPER").is_none() {
            return;
        }
        use std::io::Write;
        let payload = vec![b'x'; 128 * 1024];
        std::io::stdout().write_all(&payload).unwrap();
        std::io::stdout().flush().unwrap();
        std::io::stderr().write_all(&payload).unwrap();
        std::io::stderr().flush().unwrap();
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn bounded_command_output_drains_large_stdout_and_stderr() {
        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
        command
            .args([
                "--exact",
                "tests::bounded_command_output_large_helper",
                "--nocapture",
            ])
            .env("CAR_SECURITY_OUTPUT_HELPER", "1");

        let output =
            bounded_command_output(&mut command, std::time::Duration::from_secs(5), "test")
                .unwrap();

        assert!(output.output.status.success(), "{output:?}");
        assert!(output.output.stdout.len() >= 128 * 1024);
        assert!(output.output.stderr.len() >= 128 * 1024);
    }

    #[cfg(target_os = "macos")]
    pub(super) struct FakeSecurityCli {
        outputs: std::cell::RefCell<std::collections::VecDeque<std::io::Result<SecurityCliOutput>>>,
        calls: std::cell::RefCell<Vec<Vec<String>>>,
    }

    #[cfg(target_os = "macos")]
    impl FakeSecurityCli {
        pub(super) fn new(outputs: Vec<std::io::Result<SecurityCliOutput>>) -> Self {
            Self {
                outputs: std::cell::RefCell::new(outputs.into()),
                calls: std::cell::RefCell::new(Vec::new()),
            }
        }

        pub(super) fn calls(&self) -> Vec<Vec<String>> {
            self.calls.borrow().clone()
        }
    }

    #[cfg(target_os = "macos")]
    impl SecurityCli for FakeSecurityCli {
        fn output(&self, args: &[&str]) -> std::io::Result<SecurityCliOutput> {
            self.calls
                .borrow_mut()
                .push(args.iter().map(|arg| (*arg).to_string()).collect());
            self.outputs
                .borrow_mut()
                .pop_front()
                .expect("missing fake security output")
        }
    }

    #[cfg(target_os = "macos")]
    pub(super) fn security_output(
        code: i32,
        stdout: impl Into<Vec<u8>>,
        stderr: impl Into<Vec<u8>>,
    ) -> std::io::Result<SecurityCliOutput> {
        Ok(SecurityCliOutput {
            success: code == 0,
            code: Some(code),
            stdout: stdout.into(),
            stderr: stderr.into(),
            prompted: false,
            timed_out: false,
        })
    }

    /// A successful read that macOS had to draw a dialog for — the evidence of
    /// a stale, hash-bound ACL.
    #[cfg(target_os = "macos")]
    pub(super) fn security_output_prompted(
        code: i32,
        stdout: impl Into<Vec<u8>>,
        stderr: impl Into<Vec<u8>>,
    ) -> std::io::Result<SecurityCliOutput> {
        let mut out = security_output(code, stdout, stderr)?;
        out.prompted = true;
        Ok(out)
    }

    #[cfg(target_os = "macos")]
    fn args(values: &[&str]) -> Vec<String> {
        values.iter().map(|value| (*value).to_string()).collect()
    }

    /// The probe runs in front of credential resolution, so its exact argv is
    /// the contract: check reachability, write the reserved non-secret sentinel
    /// through the Apple-signed helper, then remove it (Parslee-ai/car#1158).
    #[cfg(target_os = "macos")]
    #[test]
    fn availability_probe_goes_through_the_security_helper() {
        let cli = FakeSecurityCli::new(vec![
            security_output(0, "", ""),
            security_output(0, "", ""),
            security_output(0, "", ""),
        ]);
        let check = mac_availability_via_security_cli_with(&cli);

        assert!(check.available);
        assert_eq!(
            cli.calls(),
            vec![
                args(&[
                    "find-generic-password",
                    "-s",
                    "car-internal",
                    "-a",
                    "__availability_probe__",
                ]),
                args(&[
                    "add-generic-password",
                    "-U",
                    "-A",
                    "-s",
                    "car-internal",
                    "-a",
                    "__availability_probe__",
                    "-w",
                    "car-availability-probe",
                ]),
                args(&[
                    "delete-generic-password",
                    "-s",
                    "car-internal",
                    "-a",
                    "__availability_probe__",
                ]),
            ]
        );
    }

    /// Cleanup preserves the public delete contract: a probe item that is
    /// already absent does not turn a successful write check into a failure.
    #[cfg(target_os = "macos")]
    #[test]
    fn availability_probe_absent_cleanup_is_still_available() {
        let cli = FakeSecurityCli::new(vec![
            security_output(SECURITY_ERR_SEC_ITEM_NOT_FOUND, "", ""),
            security_output(0, "", ""),
            security_output(SECURITY_ERR_SEC_ITEM_NOT_FOUND, "", ""),
        ]);
        let check = mac_availability_via_security_cli_with(&cli);

        assert!(check.available);
        assert!(check.reason.is_none(), "{:?}", check.reason);
    }

    /// Reads do not prove that the caller can store credentials. A developer
    /// shell can read the macOS keychain while every write is denied, which is
    /// the failure mode the availability contract must expose (car#1158).
    #[cfg(target_os = "macos")]
    #[test]
    fn availability_probe_reports_unavailable_when_reads_succeed_but_writes_are_denied() {
        struct ReadableButWriteDeniedCli;

        impl SecurityCli for ReadableButWriteDeniedCli {
            fn output(&self, args: &[&str]) -> std::io::Result<SecurityCliOutput> {
                match args.first().copied() {
                    Some("find-generic-password") => security_output(0, "", ""),
                    Some("add-generic-password") => security_output(
                        152,
                        "",
                        "security: SecKeychainItemCreateFromContent: User interaction is not allowed.",
                    ),
                    other => panic!("unexpected security command: {other:?}"),
                }
            }
        }

        let check = mac_availability_via_security_cli_with(&ReadableButWriteDeniedCli);

        assert!(!check.available);
        let reason = check
            .reason
            .expect("write-denied probe must carry a reason");
        assert!(
            reason.contains("User interaction is not allowed"),
            "reason should carry the write error, got {reason:?}"
        );
    }

    /// A non-zero exit that is not "no such item" is a backend/authorization
    /// failure, and the caller gets the helper's own words for it rather than
    /// a bare `false`.
    #[cfg(target_os = "macos")]
    #[test]
    fn availability_probe_backend_error_reports_unavailable() {
        let cli = FakeSecurityCli::new(vec![security_output(
            51,
            "",
            "security: SecKeychainSearchCopyNext: User interaction is not allowed.",
        )]);
        let check = mac_availability_via_security_cli_with(&cli);

        assert!(!check.available);
        let reason = check.reason.expect("unavailable must carry a reason");
        assert!(
            reason.contains("User interaction is not allowed"),
            "reason should carry the helper's stderr, got {reason:?}"
        );
    }

    /// A successful write is not enough when CAR cannot remove its internal
    /// sentinel. Availability promises usable write/delete operations and
    /// preserves the cleanup error for callers.
    #[cfg(target_os = "macos")]
    #[test]
    fn availability_probe_cleanup_error_reports_unavailable() {
        let cli = FakeSecurityCli::new(vec![
            security_output(0, "", ""),
            security_output(0, "", ""),
            security_output(
                51,
                "",
                "security: SecKeychainItemDelete: User interaction is not allowed.",
            ),
        ]);
        let check = mac_availability_via_security_cli_with(&cli);

        assert!(!check.available);
        let reason = check.reason.expect("cleanup failure must carry a reason");
        assert!(
            reason.contains("User interaction is not allowed"),
            "reason should carry the cleanup error, got {reason:?}"
        );
    }

    /// The property that makes a blocked probe recoverable from `~/.car/logs`
    /// by an operator who was not at the screen (Parslee-ai/car#878, #897):
    /// the notice names the item, and the probe's argv is item-scoped so it
    /// gets a real name instead of a bare subcommand.
    #[cfg(target_os = "macos")]
    #[test]
    fn availability_probe_names_itself_in_the_prompt_notice() {
        let cli = FakeSecurityCli::new(vec![security_output(
            51,
            "",
            "security: SecKeychainSearchCopyNext: User interaction is not allowed.",
        )]);
        let _ = mac_availability_via_security_cli_with(&cli);

        // Derived from the argv the probe ACTUALLY sent, never a hand-typed
        // copy of it. `describe_item` falls back to naming the bare subcommand
        // when a call is not item-scoped, so asserting a literal here would
        // pass even if the probe stopped carrying `-s`/`-a` — which is exactly
        // the regression that would put an unnameable item back in the log.
        let sent = cli.calls().remove(0);
        let sent: Vec<&str> = sent.iter().map(String::as_str).collect();
        let item = describe_item(&sent);

        assert_eq!(item, "car-internal/__availability_probe__");
        assert!(
            keychain_prompt_notice(&item).contains(&item),
            "notice must name the blocking item: {}",
            keychain_prompt_notice(&item)
        );
    }

    #[cfg(target_os = "macos")]
    fn assert_access_denied_contains(err: SecretError, expected: &str) {
        match err {
            SecretError::AccessDenied { message } => assert!(
                message.contains(expected),
                "expected access-denied error to contain {expected:?}, got {message:?}"
            ),
            other => panic!("expected AccessDenied, got {:?}", other),
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_security_errors_are_typed_for_recovery() {
        assert!(matches!(
            classify_security_error(-128, "user canceled"),
            SecretError::UserCancelled { .. }
        ));
        assert!(matches!(
            classify_security_error(-25293, "authorization denied"),
            SecretError::AccessDenied { .. }
        ));
        assert!(matches!(
            classify_helper_timeout("car/PARSLEE_AUTH_STATE_V2"),
            SecretError::HelperTimedOut { .. }
        ));

        let mut timed_out = security_output(9, b"", b"helper killed").unwrap();
        timed_out.timed_out = true;
        let cli = FakeSecurityCli::new(vec![Ok(timed_out)]);
        let secret = SecretRef::new("svc", "key");
        assert!(matches!(
            mac_get_via_security_cli_with(&secret, &cli),
            Err(SecretError::HelperTimedOut { .. })
        ));
    }

    #[cfg(target_os = "macos")]
    struct IsolatedKeychainFixture {
        _temp: tempfile::TempDir,
        proof_root: std::path::PathBuf,
        valid_path: std::path::PathBuf,
        symlink_path: std::path::PathBuf,
        outside_path: std::path::PathBuf,
        public_path: std::path::PathBuf,
        directory_path: std::path::PathBuf,
        public_root: std::path::PathBuf,
    }

    #[cfg(target_os = "macos")]
    impl IsolatedKeychainFixture {
        fn new() -> Self {
            use std::os::unix::fs::{symlink, PermissionsExt};

            let temp = tempfile::tempdir().unwrap();
            let proof_root = temp.path().join("proof");
            std::fs::create_dir(&proof_root).unwrap();
            std::fs::set_permissions(&proof_root, std::fs::Permissions::from_mode(0o700)).unwrap();

            let valid_path = proof_root.join("valid.keychain-db");
            std::fs::write(&valid_path, b"keychain fixture").unwrap();
            std::fs::set_permissions(&valid_path, std::fs::Permissions::from_mode(0o600)).unwrap();

            let symlink_path = proof_root.join("linked.keychain-db");
            symlink(&valid_path, &symlink_path).unwrap();

            let outside_path = temp.path().join("outside.keychain-db");
            std::fs::write(&outside_path, b"outside fixture").unwrap();
            std::fs::set_permissions(&outside_path, std::fs::Permissions::from_mode(0o600))
                .unwrap();

            let public_path = proof_root.join("public.keychain-db");
            std::fs::write(&public_path, b"public fixture").unwrap();
            std::fs::set_permissions(&public_path, std::fs::Permissions::from_mode(0o644)).unwrap();

            let directory_path = proof_root.join("directory.keychain-db");
            std::fs::create_dir(&directory_path).unwrap();

            let public_root = temp.path().join("public-proof");
            std::fs::create_dir(&public_root).unwrap();
            std::fs::set_permissions(&public_root, std::fs::Permissions::from_mode(0o755)).unwrap();

            Self {
                _temp: temp,
                proof_root,
                valid_path,
                symlink_path,
                outside_path,
                public_path,
                directory_path,
                public_root,
            }
        }

        fn proof_root(&self) -> &std::path::Path {
            &self.proof_root
        }

        fn valid_path(&self) -> &std::path::Path {
            &self.valid_path
        }

        fn symlink_path(&self) -> &std::path::Path {
            &self.symlink_path
        }

        fn outside_path(&self) -> &std::path::Path {
            &self.outside_path
        }

        fn public_path(&self) -> &std::path::Path {
            &self.public_path
        }

        fn directory_path(&self) -> &std::path::Path {
            &self.directory_path
        }

        fn public_root(&self) -> &std::path::Path {
            &self.public_root
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn isolated_keychain_must_be_absolute_private_regular_owned_and_under_proof_root() {
        let fixture = IsolatedKeychainFixture::new();
        assert!(validate_keychain_path(fixture.valid_path(), fixture.proof_root()).is_ok());
        assert!(validate_keychain_path(
            std::path::Path::new("relative.keychain-db"),
            fixture.proof_root()
        )
        .is_err());
        assert!(validate_keychain_path(fixture.symlink_path(), fixture.proof_root()).is_err());
        assert!(validate_keychain_path(fixture.outside_path(), fixture.proof_root()).is_err());
        assert!(validate_keychain_path(fixture.public_path(), fixture.proof_root()).is_err());
        assert!(validate_keychain_path(fixture.directory_path(), fixture.proof_root()).is_err());
        assert!(validate_keychain_path(fixture.valid_path(), fixture.public_root()).is_err());
    }

    #[test]
    fn secret_store_activity_counts_only_aggregate_public_operation_attempts() {
        let _guard = lock_store();
        let dir = tempfile::tempdir().unwrap();
        std::env::set_var("CAR_SECRETS_FILE_DIR", dir.path());
        let before = secret_store_activity();
        let store = SecretStore::new();
        let secret = SecretRef::new("activity-test", "credential");

        assert!(store.availability().available);
        store.put(&secret, "sensitive-value").unwrap();
        let _ = store.get(&secret).unwrap();
        let _ = store.status(&secret).unwrap();
        store.publish(&secret, "replacement-value").unwrap();
        store.delete(&secret).unwrap();

        let after = secret_store_activity();
        assert_eq!(after.get_attempts - before.get_attempts, 1);
        assert_eq!(after.status_attempts - before.status_attempts, 1);
        assert_eq!(
            after.availability_attempts - before.availability_attempts,
            1
        );
        assert_eq!(after.write_attempts - before.write_attempts, 2);
        assert_eq!(after.delete_attempts - before.delete_attempts, 1);

        let encoded = serde_json::to_string(&after).unwrap();
        assert!(!encoded.contains("activity-test"));
        assert!(!encoded.contains("credential"));
        assert!(!encoded.contains("sensitive-value"));
        assert!(!encoded.contains(dir.path().to_string_lossy().as_ref()));
        std::env::remove_var("CAR_SECRETS_FILE_DIR");
    }

    /// The default run uses only the isolated backend. Provisioned native
    /// Keychain coverage is explicit and serial:
    ///
    /// `env -u CAR_SECRETS_FILE_DIR CAR_TEST_NATIVE_KEYCHAIN=1 cargo test -p car-secrets tests::roundtrip_string -- --exact --nocapture --test-threads=1`
    ///
    /// That lane fails loudly when the Keychain probe is unavailable, uses a
    /// unique service, and asserts cleanup. Native helper calls retain their
    /// production deadlines.
    #[test]
    fn roundtrip_string() {
        #[cfg(target_os = "macos")]
        if std::env::var_os(NATIVE_KEYCHAIN_LANE).is_some() {
            run_native_keychain_lane();
            return;
        }

        let fixture = IsolatedStoreFixture::new();
        let store = fixture.store();
        let r = SecretRef::new("isolated-contract", "roundtrip");
        store.put(&r, "hello world").unwrap();
        assert_eq!(store.get(&r).unwrap(), "hello world");
        assert!(store.status(&r).unwrap().exists);
        store.delete(&r).unwrap();
        assert!(!store.status(&r).unwrap().exists);
    }

    #[test]
    fn roundtrip_string_with_trailing_newline() {
        let fixture = IsolatedStoreFixture::new();
        let store = fixture.store();
        let r = SecretRef::new("isolated-contract", "roundtrip-newline");
        let value = "abc\n";
        store.put(&r, value).unwrap();
        assert_eq!(store.get(&r).unwrap(), value);
        store.delete(&r).unwrap();
    }

    #[test]
    fn get_missing_returns_not_found() {
        let fixture = IsolatedStoreFixture::new();
        let store = fixture.store();
        let r = SecretRef::new("isolated-contract", "never-written");
        match store.get(&r) {
            Err(SecretError::NotFound { .. }) => (),
            other => panic!("expected NotFound, got {:?}", other),
        }
    }

    #[test]
    fn delete_missing_is_idempotent() {
        let fixture = IsolatedStoreFixture::new();
        let store = fixture.store();
        let r = SecretRef::new("isolated-contract", "missing");
        store.delete(&r).unwrap();
        store.delete(&r).unwrap();
    }

    #[test]
    fn json_roundtrip() {
        let fixture = IsolatedStoreFixture::new();
        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Session {
            cookies: Vec<String>,
            expires_at: i64,
        }
        let store = fixture.store();
        let r = SecretRef::new("isolated-contract", "session");
        let s = Session {
            cookies: vec!["a=1".into(), "b=2".into()],
            expires_at: 1_700_000_000,
        };
        store.put_json(&r, &s).unwrap();
        let back: Session = store.get_json(&r).unwrap();
        assert_eq!(back, s);
        store.delete(&r).unwrap();
    }

    #[test]
    fn status_no_leak() {
        let fixture = IsolatedStoreFixture::new();
        let store = fixture.store();
        let r = SecretRef::new("isolated-contract", "status");
        store.put(&r, "secret-payload").unwrap();
        let st = store.status(&r).unwrap();
        let encoded = serde_json::to_string(&st).unwrap();
        assert!(!encoded.contains("secret-payload"));
        store.delete(&r).unwrap();
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_get_uses_security_cli_and_maps_success() {
        let cli = FakeSecurityCli::new(vec![security_output(
            0,
            b"keychain: \"/Users/example/Library/Keychains/login.keychain-db\"\n",
            b"password: \"secret\"\n",
        )]);
        let r = SecretRef::new("svc", "key");

        assert_eq!(mac_get_via_security_cli_with(&r, &cli).unwrap(), "secret");
        assert_eq!(
            cli.calls(),
            vec![args(&[
                "find-generic-password",
                "-s",
                "svc",
                "-a",
                "key",
                "-g"
            ])]
        );
    }

    /// The measured prompt path used to run automatic ACL repair, which issued
    /// delete + add after the user approved a read. That recreation
    /// discarded the approval and guaranteed another prompt. A prompted read
    /// is now read-only: one find call, no delete, write, or partition rewrite.
    #[cfg(target_os = "macos")]
    #[test]
    fn prompted_read_preserves_the_item_and_persisted_grant() {
        let cli = FakeSecurityCli::new(vec![security_output_prompted(
            0,
            b"keychain: isolated-test.keychain-db\n",
            b"password: \"secret\"\n",
        )]);
        let r = SecretRef::new("car-test-0o9-prompt-persistence", "credential");

        assert_eq!(mac_get_via_security_cli_with(&r, &cli).unwrap(), "secret");
        assert_eq!(
            cli.calls(),
            vec![args(&[
                "find-generic-password",
                "-s",
                "car-test-0o9-prompt-persistence",
                "-a",
                "credential",
                "-g",
            ])],
            "an approved read must never rewrite or recreate the item"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_get_decodes_hex_password_output_with_trailing_newline() {
        let cli = FakeSecurityCli::new(vec![security_output(
            0,
            b"keychain: \"/Users/example/Library/Keychains/login.keychain-db\"\n",
            b"password: 0x6162630A  \"abc\\012\"\n",
        )]);
        let r = SecretRef::new("svc", "key");

        assert_eq!(mac_get_via_security_cli_with(&r, &cli).unwrap(), "abc\n");
        assert_eq!(
            cli.calls(),
            vec![args(&[
                "find-generic-password",
                "-s",
                "svc",
                "-a",
                "key",
                "-g"
            ])]
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_get_maps_not_found_and_access_denied_without_fallback() {
        let r = SecretRef::new("svc", "missing");
        let cli = FakeSecurityCli::new(vec![security_output(
            SECURITY_ERR_SEC_ITEM_NOT_FOUND,
            b"",
            b"The specified item could not be found in the keychain.\n",
        )]);

        match mac_get_via_security_cli_with(&r, &cli) {
            Err(SecretError::NotFound { service, key }) => {
                assert_eq!(service, "svc");
                assert_eq!(key, "missing");
            }
            other => panic!("expected NotFound, got {:?}", other),
        }
        assert_eq!(cli.calls().len(), 1);

        let cli = FakeSecurityCli::new(vec![security_output(
            51,
            b"",
            b"User interaction is not allowed.\n",
        )]);
        let err = mac_get_via_security_cli_with(&r, &cli).unwrap_err();
        assert_access_denied_contains(err, "User interaction is not allowed.");
        assert_eq!(cli.calls().len(), 1);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_status_uses_security_cli_and_maps_results() {
        let r = SecretRef::new("svc", "key");
        let cli = FakeSecurityCli::new(vec![security_output(0, b"", b"")]);

        let status = mac_status_via_security_cli_with(&r, &cli).unwrap();
        assert!(status.exists);
        assert_eq!(
            cli.calls(),
            vec![args(&["find-generic-password", "-s", "svc", "-a", "key"])]
        );

        let cli = FakeSecurityCli::new(vec![security_output(
            SECURITY_ERR_SEC_ITEM_NOT_FOUND,
            b"",
            b"The specified item could not be found in the keychain.\n",
        )]);
        assert!(!mac_status_via_security_cli_with(&r, &cli).unwrap().exists);

        let cli = FakeSecurityCli::new(vec![security_output(128, b"", b"auth denied\n")]);
        let err = mac_status_via_security_cli_with(&r, &cli).unwrap_err();
        assert_access_denied_contains(err, "auth denied");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_put_surfaces_add_failure_as_access_denied() {
        let cli = FakeSecurityCli::new(vec![security_output(
            51,
            b"",
            b"User interaction is not allowed.\n",
        )]);

        let err =
            mac_write_via_security_cli("car-test-0o9-write", "key", "secret", &cli).unwrap_err();
        assert_access_denied_contains(err, "User interaction is not allowed.");
        assert_eq!(
            cli.calls().len(),
            1,
            "a failed write must not trigger a delete"
        );
    }

    /// The regression in `Parslee-ai/car#1274`: an ordinary write must not
    /// delete first. A delete needs the user's authorization even though `-A`
    /// already granted every application read access, so an unconditional
    /// pre-delete drew a dialog on every token refresh — every ~15 minutes,
    /// forever, and on an unattended run nobody to answer it.
    #[cfg(target_os = "macos")]
    #[test]
    fn mac_put_does_not_pre_delete_and_therefore_cannot_prompt() {
        let cli = FakeSecurityCli::new(vec![security_output(0, b"", b"")]);

        mac_put_via_security_cli_with("car-test-0o9-update-persistence", "key", "secret", &cli)
            .unwrap();

        assert_eq!(
            cli.calls(),
            vec![args(&[
                "add-generic-password",
                "-U",
                "-A",
                "-s",
                "car-test-0o9-update-persistence",
                "-a",
                "key",
                "-w",
                "secret",
            ])],
            "an ordinary write must issue exactly one call, and not a delete"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_publish_updates_in_place_without_a_pre_delete_gap() {
        let cli = FakeSecurityCli::new(vec![security_output(0, b"", b"")]);

        mac_publish_via_security_cli_with("svc", "key", "secret", &cli).unwrap();

        assert_eq!(
            cli.calls(),
            vec![args(&[
                "add-generic-password",
                "-U",
                "-A",
                "-s",
                "svc",
                "-a",
                "key",
                "-w",
                "secret",
            ])]
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_security_child_is_killed_and_reaped_at_its_deadline() {
        let mut command = std::process::Command::new("/bin/sh");
        command.args(["-c", "sleep 5"]);
        let started = std::time::Instant::now();

        let output = bounded_command_output_with(
            &mut command,
            std::time::Duration::from_millis(40),
            || false,
            || {},
        )
        .unwrap();

        assert!(!output.output.status.success());
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "bounded helper must not wait for the child command's natural exit"
        );
        let stderr = String::from_utf8_lossy(&output.output.stderr);
        assert!(stderr.contains("CAR killed the keychain helper"));
        // The deadline is nearly always an unanswered macOS keychain dialog.
        // Saying only "helper killed" sends the user looking at models and
        // accounts, because that is what the downstream error mentions
        // ("no inference backend is available") — the one thing it never named
        // was the prompt sitting on screen.
        assert!(
            stderr.contains("keychain prompt"),
            "the timeout must name a pending keychain prompt as the likely cause"
        );
        assert!(
            stderr.contains("Always Allow"),
            "the timeout must tell the user what action clears it"
        );
    }

    /// A hung helper with NO dialog on screen must still die at the short
    /// deadline. This is the half that keeps the extension honest: if
    /// `security_agent_is_prompting()` were ever wrong in the permissive
    /// direction, a genuinely stuck child would block for three minutes.
    ///
    /// The interactive half cannot be unit-tested without a real SecurityAgent,
    /// so `security_agent_is_prompting` fails CLOSED — any error determining it
    /// yields the short deadline, never the long one.
    #[cfg(target_os = "macos")]
    #[test]
    fn a_hung_helper_with_no_dialog_still_dies_at_the_short_deadline() {
        // Nothing here opens a keychain dialog, so the deadline must be the
        // short one regardless of what else is running on the machine.
        assert!(
            SECURITY_CLI_INTERACTIVE_TIMEOUT > SECURITY_CLI_TIMEOUT,
            "the interactive allowance must be longer than the hang deadline"
        );
        assert!(
            SECURITY_CLI_INTERACTIVE_TIMEOUT >= std::time::Duration::from_secs(60),
            "a human needs to find a window, type a password and submit — 15s \
             is why entering the correct password repeatedly never worked"
        );

        let mut command = std::process::Command::new("/bin/sh");
        command.args(["-c", "sleep 5"]);
        let started = std::time::Instant::now();
        let output = bounded_command_output_with(
            &mut command,
            std::time::Duration::from_millis(40),
            || false,
            || {},
        )
        .unwrap();
        assert!(!output.output.status.success());
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "a helper with no dialog must not inherit the interactive allowance"
        );
    }

    /// A dialog belonging to something else must not be read as proof that
    /// *this* read was authorized.
    ///
    /// `SecurityAgent` is machine-wide, so the bare sighting is true whenever
    /// anything on the Mac is asking for authorization — including another CAR
    /// process blocked on its own prompt. Misattributing that dialog would name
    /// the wrong item in the notice and unnecessarily extend this helper's
    /// deadline, but never mutates either item.
    #[cfg(target_os = "macos")]
    #[test]
    fn a_dialog_is_not_attributed_to_a_read_that_did_not_wait_for_it() {
        let instant = std::time::Duration::from_millis(0);
        let quick = std::time::Duration::from_millis(20);

        assert!(
            !dialog_is_evidence_for_this_read(true, instant),
            "a dialog already on screen at spawn belongs to whatever opened it"
        );
        assert!(
            !dialog_is_evidence_for_this_read(true, quick),
            "a read that returned in 20ms was never blocked on a human"
        );
        assert!(
            !dialog_is_evidence_for_this_read(false, std::time::Duration::from_secs(60)),
            "no dialog is no evidence, however long the helper took"
        );
        assert!(
            dialog_is_evidence_for_this_read(true, PROMPT_EVIDENCE_MIN),
            "a call still blocked with a dialog up is the one being authorized"
        );
    }

    /// The threshold has to sit in the gap between the two populations it
    /// separates, and stay well clear of the deadline that ends the call.
    #[cfg(target_os = "macos")]
    #[test]
    fn the_prompt_evidence_threshold_sits_between_a_silent_read_and_a_human() {
        assert!(
            PROMPT_EVIDENCE_MIN >= std::time::Duration::from_millis(200),
            "must be an order of magnitude above a silent `security -g` read, \
             which returns in tens of milliseconds"
        );
        assert!(
            PROMPT_EVIDENCE_MIN <= std::time::Duration::from_secs(2),
            "must stay below the fastest a human can answer a dialog, or the \
             blocking read finishes before CAR can explain what is waiting"
        );
        assert!(
            PROMPT_EVIDENCE_MIN < SECURITY_CLI_TIMEOUT,
            "a prompted read must be attributable before any deadline can end it"
        );
    }

    /// End-to-end over the real poll loop, with a dialog held on screen for the
    /// whole run: a helper that exits in milliseconds must still come back
    /// unattributed.
    ///
    /// The probe is injected precisely so this cannot pass by accident. Probing
    /// the real `SecurityAgent` would make the assertion depend on whether the
    /// machine happens to have a dialog up — false on every CI runner, which
    /// would let the test pass with no attribution rule at all.
    #[cfg(target_os = "macos")]
    #[test]
    fn a_fast_helper_is_not_attributed_a_dialog_that_is_on_screen_throughout() {
        let mut command = std::process::Command::new("/bin/echo");
        command.arg("hi");
        let notices = std::sync::atomic::AtomicUsize::new(0);
        let run = bounded_command_output_with(
            &mut command,
            SECURITY_CLI_TIMEOUT,
            || true,
            || {
                notices.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            },
        )
        .unwrap();
        assert!(run.output.status.success());
        assert!(
            !run.prompted,
            "a helper that exited in milliseconds was not the one being authorized, \
             however many dialogs the machine is showing"
        );
        assert_eq!(
            notices.load(std::sync::atomic::Ordering::Relaxed),
            0,
            "and it must not tell the user to go answer a dialog it never waited on \
             (Parslee-ai/car#878 rides on the same attribution rule as #897)"
        );
    }

    /// The other half: a helper that really is blocked past the threshold with a
    /// dialog up *is* attributed one. Without this, the rule could satisfy the
    /// test above by never attributing anything.
    #[cfg(target_os = "macos")]
    #[test]
    fn a_helper_still_blocked_past_the_threshold_is_attributed_the_dialog() {
        // Exits on its own well after PROMPT_EVIDENCE_MIN, so the run ends by
        // natural exit rather than by a deadline — the deadline is extended to
        // the interactive allowance while the probe says a dialog is up.
        let mut command = std::process::Command::new("/bin/sh");
        command.args(["-c", "sleep 1"]);
        let notices = std::sync::atomic::AtomicUsize::new(0);
        let run = bounded_command_output_with(
            &mut command,
            SECURITY_CLI_TIMEOUT,
            || true,
            || {
                notices.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            },
        )
        .unwrap();
        assert!(run.output.status.success(), "the child must exit naturally");
        assert!(
            run.prompted,
            "a call still running past PROMPT_EVIDENCE_MIN with a dialog up is \
             the call that dialog belongs to"
        );
        // Parslee-ai/car#878: exactly one line, and it arrived while the read
        // was still blocked rather than on expiry — this child exits naturally
        // at ~1s, so the run never reaches a deadline and the on-timeout
        // message is never appended. Only the prompt notice can have fired.
        //
        // ONE, not one-per-poll: the loop ticks every 10ms, so a notice keyed
        // on the condition rather than on the transition would emit ~50 lines
        // here and bury the daemon log it is supposed to make readable.
        assert_eq!(
            notices.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "a blocked read must explain itself exactly once, promptly"
        );
    }

    /// The notice and the on-expiry message describe the same condition three
    /// minutes apart, so they must not drift into giving different remedies.
    #[cfg(target_os = "macos")]
    #[test]
    fn the_prompt_notice_names_the_wait_and_both_remedies() {
        let notice = keychain_prompt_notice("car/parslee_access_token");
        assert!(
            notice.contains("car/parslee_access_token"),
            "must name WHICH item is being asked for — the operator who walked away \
             and came back to a stack of prompts cannot read the dialog after the \
             fact, and the log is the only record (Parslee-ai/car#897): {notice}"
        );
        assert!(
            notice.contains(&SECURITY_CLI_INTERACTIVE_TIMEOUT.as_secs().to_string()),
            "must state how long CAR will wait, or it reads as an indefinite hang: {notice}"
        );
        assert!(
            notice.contains("Always Allow"),
            "must name the one click that also prevents the NEXT prompt: {notice}"
        );
        assert!(
            notice.contains("Keychain Access"),
            "must name the remedy for someone who already dismissed the dialog: {notice}"
        );
        assert!(
            notice.contains("not hung"),
            "the reported failure was reading the silence as a hang and killing it: {notice}"
        );
    }

    /// The item label is built from the `security` argv, so it has to survive
    /// every shape that argv takes — including the calls that name no item.
    #[cfg(target_os = "macos")]
    #[test]
    fn describe_item_names_the_keychain_item_from_the_argv() {
        assert_eq!(
            describe_item(&["find-generic-password", "-s", "car", "-a", "token", "-w"]),
            "car/token"
        );
        assert_eq!(
            describe_item(&["delete-generic-password", "-s", "car"]),
            "car"
        );
        assert_eq!(
            describe_item(&["find-generic-password", "-a", "token"]),
            "token"
        );
        // Not item-scoped: naming the subcommand still beats naming nothing.
        assert_eq!(describe_item(&["unlock-keychain"]), "unlock-keychain");
        assert_eq!(describe_item(&[]), "security");
        // A flag in final position has no value after it — must not panic.
        assert_eq!(
            describe_item(&["find-generic-password", "-s"]),
            "find-generic-password"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn mac_delete_uses_security_cli_and_maps_results() {
        let r = SecretRef::new("svc", "key");
        let cli = FakeSecurityCli::new(vec![security_output(0, b"", b"")]);

        mac_delete_via_security_cli_with(&r, &cli).unwrap();
        assert_eq!(
            cli.calls(),
            vec![args(&["delete-generic-password", "-s", "svc", "-a", "key"])]
        );

        let cli = FakeSecurityCli::new(vec![security_output(
            SECURITY_ERR_SEC_ITEM_NOT_FOUND,
            b"",
            b"The specified item could not be found in the keychain.\n",
        )]);
        mac_delete_via_security_cli_with(&r, &cli).unwrap();

        let cli = FakeSecurityCli::new(vec![security_output(128, b"", b"auth denied\n")]);
        let err = mac_delete_via_security_cli_with(&r, &cli).unwrap_err();
        assert_access_denied_contains(err, "auth denied");
    }
}