cpa-server 0.4.1

Part of cliproxy: HTTP routes, client auth, credential selection and the management API
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
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
//! Axum-independent runtime: config snapshot, credential store, selection, credential
//! preparation and attempt outcomes.
//!
//! Every attempt is a [`Lease`]: an owned guard that reports exactly one [`Outcome`],
//! either explicitly or as `Cancelled` when dropped (client gone mid-execute, stream
//! dropped). Streams wrap their lease in [`Completing`].

use std::collections::HashMap;
use std::io::Write;
use std::panic::AssertUnwindSafe;
use std::path::Path;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::task::{Context, Poll, ready};
use std::time::{Duration, Instant};

use bytes::Bytes;
use cpa_common::gostr::GoStr;
use cpa_core::config::Config;
use cpa_core::credential::{Credential, MetadataPatch, Source};
use cpa_core::exec::{ExecError, ExecStream, FailureScope};
use cpa_exec::{Executors, Readiness};
use futures_util::{FutureExt, Stream, StreamExt};
use serde_json::{Map, Value};

use crate::refresh::RefreshState;
use crate::registry::Registry;
use crate::scheduler::{Policy, Scheduler};

/// The config snapshot and credential epoch a registry was built from.
type RegistryCache = (Arc<Config>, (u64, u64, u64), Arc<Registry>);

pub struct Runtime {
    config: RwLock<Arc<Config>>,
    store: Arc<CredentialStore>,
    pub executors: Executors,
    refresh_task: Mutex<Option<tokio::task::AbortHandle>>,
    refresh_state: Mutex<RefreshState>,
    /// The registry derived from the current config and credential generation.
    registry: Mutex<Option<RegistryCache>>,
    oauth_sink: RwLock<Option<OAuthCallbackSink>>,
    /// Go `modelPoolOffsets`: rotation cursors for OpenAI-compatible alias pools.
    pool_offsets: Mutex<HashMap<String, usize>>,
    /// Usage records for `GET /observability/usage/queue` (management configures it).
    usage: Arc<crate::usage::UsageQueue>,
    /// `--local-model`: embedded model catalogs only, no remote catalog refresh.
    local_model: std::sync::atomic::AtomicBool,
    /// The native plugin host, synced with each published config (see [`crate::plugins`]).
    plugins: crate::plugins::PluginRuntime,
    /// The remote dispatcher that replaces local selection (Go Home mode).
    remote: RwLock<Option<Arc<dyn crate::remote::RemoteDispatch>>>,
    /// Set only by [`crate::testing::runtime`]: executor calls get credentials that
    /// cannot leave the machine.
    pub(crate) deny_external: std::sync::atomic::AtomicBool,
    /// Marked on every config publish, so background loops sleep until it changes.
    config_changed: tokio::sync::watch::Sender<()>,
    /// Marked whenever a background refresh job ends, so the refresh loop looks again
    /// (a job may end after the loop stopped waiting for it).
    refresh_done: tokio::sync::watch::Sender<()>,
    /// Codex refresh transactions in flight ([`Runtime::shutdown_codex_refreshes`]).
    codex_refreshes: CodexRefreshes,
    /// The model catalog updaters' policy, once started (`model_updater::start`).
    catalogs: Mutex<Option<crate::model_updater::Session>>,
    /// Serializes config commits through their catalog reconfigure.
    config_commit: Mutex<()>,
}

/// The Codex refresh transactions under a credential file's lock: shutdown stops the
/// ones still waiting for the lock and waits for the ones that hold it, whose grant may
/// have spent a refresh token.
#[derive(Clone, Default)]
struct CodexRefreshes {
    shutdown: tokio_util::sync::CancellationToken,
    tasks: tokio_util::task::TaskTracker,
}

/// An OAuth provider redirect received on the main listener.
#[derive(Debug, Clone)]
pub struct OAuthCallback {
    /// `anthropic`, `codex`, `antigravity` or `devin`.
    pub provider: &'static str,
    pub state: String,
    pub code: String,
    pub error: String,
}

/// What became of a provider callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthDelivery {
    Delivered,
    /// No login with that state is pending, or the callback could not be recorded.
    NotPending,
    /// The state belongs to a Sign in with ChatGPT binding, which takes its callback
    /// only through the v8 Management API (Go `ErrSIWCCallbackRequiresV8`).
    RequiresV8,
}

/// Hands a callback to a pending management login (Go
/// `WriteOAuthCallbackFileForPendingSession`).
pub type OAuthCallbackSink = Arc<dyn Fn(&OAuthCallback) -> OAuthDelivery + Send + Sync>;

impl Runtime {
    /// The scheduler policy is derived from the config (`routing` plus the OAuth
    /// provider rules), as on every publish.
    pub fn new(config: Config, credentials: Vec<Credential>, executors: Executors) -> Self {
        let mut policy = crate::management::policy(&config);
        policy.compat_disable_cooling = crate::scheduler::compat_cooling(&config);
        let cooldown_dir = cooldown_dir(&config, &policy);
        let (enabled, strict) = signature_cache_config(&config);
        cpa_translate::set_antigravity_signature_cache_config(enabled, strict);
        let rt = Self {
            config: RwLock::new(Arc::new(config)),
            store: CredentialStore::new(credentials),
            executors,
            refresh_task: Mutex::default(),
            refresh_state: Mutex::default(),
            registry: Mutex::default(),
            oauth_sink: RwLock::default(),
            pool_offsets: Mutex::default(),
            usage: Arc::default(),
            local_model: Default::default(),
            plugins: Default::default(),
            remote: RwLock::default(),
            deny_external: Default::default(),
            config_changed: tokio::sync::watch::Sender::new(()),
            refresh_done: tokio::sync::watch::Sender::new(()),
            codex_refreshes: CodexRefreshes::default(),
            catalogs: Mutex::default(),
            config_commit: Mutex::default(),
        };
        rt.publish_policy(policy);
        rt.store.configure_cooldown_store(cooldown_dir);
        // Failed attempts publish Go's error events on the RESP `errors` channel.
        let _ = rt.store.error_events.set(rt.usage.clone());
        let _ = rt
            .store
            .session_closer
            .set(Box::new(rt.executors.credential_session_closer()));
        rt
    }

    /// The usage queue: the request path calls `enqueue` with one serialized Go
    /// `queuedUsageDetail` per upstream request when `accepts()` (additive API).
    pub fn usage_queue(&self) -> &crate::usage::UsageQueue {
        &self.usage
    }

    /// Records `--local-model` (Go `modelCatalogUpdaterPlan`'s `localModel`): remote
    /// model catalog updaters must not start when set (additive API).
    pub fn set_local_model(&self, on: bool) {
        self.local_model.store(on, std::sync::atomic::Ordering::Relaxed);
    }

    /// Persists cooldowns to `backend` instead of `.cds` files (PGSTORE's cooldown
    /// table; additive API). Call before serving.
    pub fn set_cooldown_backend(&self, backend: Arc<dyn crate::cooldown_store::Backend>) {
        self.store.set_cooldown_backend(backend);
    }

    /// Whether `--local-model` was given.
    pub fn local_model(&self) -> bool {
        self.local_model.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Serves with `host`, a plugin host that already runs (Go hands the host that
    /// registered plugin command-line flags to the service; additive API). Call before
    /// [`crate::plugins::start`].
    pub fn with_plugin_host(mut self, host: cpa_plugin::Host) -> Self {
        self.plugins = crate::plugins::PluginRuntime::with_host(host);
        self
    }

    /// The plugin host (additive API). [`crate::plugins::start`] syncs it with the
    /// config.
    pub fn plugins(&self) -> &cpa_plugin::Host {
        self.plugins.host()
    }

    pub(crate) fn plugin_runtime(&self) -> &crate::plugins::PluginRuntime {
        &self.plugins
    }

    /// The config snapshot to use for one whole request.
    pub fn config(&self) -> Arc<Config> {
        self.config.read().unwrap_or_else(PoisonError::into_inner).clone()
    }

    /// Starts the model catalog updaters for this runtime's lifetime under the commit
    /// mutex, so no commit is configured before or skipped by the startup configure.
    pub(crate) fn start_catalogs(&self, session: crate::model_updater::Session) {
        let commit = self.config_commit.lock().unwrap_or_else(PoisonError::into_inner);
        session.configure(&self.config(), true);
        let previous = self
            .catalogs
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .replace(session);
        drop(commit);
        drop(previous);
    }

    /// Whether [`Runtime::publish_config_and_policy`] would commit `config`: Go
    /// `commitConfigUpdate` rejects the whole update over invalid catalog sources.
    /// Callers that apply other state before publishing check this first.
    pub(crate) fn accepts_config(config: &Config) -> bool {
        match cpa_core::config::validate_catalog_sources(config.document.get("models")) {
            Ok(()) => true,
            Err(error) => {
                tracing::warn!("rejected invalid model catalog sources: {error}");
                false
            }
        }
    }

    /// Resolves after the next config publish.
    pub fn subscribe_config(&self) -> tokio::sync::watch::Receiver<()> {
        self.config_changed.subscribe()
    }

    /// Replaces the config and the scheduler policy derived from it. Requests already
    /// running keep their snapshot. False when the config was rejected and nothing
    /// changed ([`Runtime::accepts_config`]).
    pub fn publish_config(&self, config: Config) -> bool {
        let policy = crate::management::policy(&config);
        self.publish_config_and_policy(config, policy)
    }

    /// Integration should use this when publishing parsed routing settings too. False
    /// when the config was rejected and nothing changed.
    pub fn publish_config_and_policy(&self, config: Config, mut policy: Policy) -> bool {
        if !Self::accepts_config(&config) {
            return false;
        }
        policy.compat_disable_cooling = crate::scheduler::compat_cooling(&config);
        let (enabled, strict) = signature_cache_config(&config);
        cpa_translate::set_antigravity_signature_cache_config(enabled, strict);
        let dir = cooldown_dir(&config, &policy);
        let ws_auth = crate::relay::ws_auth(&config);
        let config = Arc::new(config);
        // Commits are serialized, so the catalogs are configured in commit order; the
        // config lock itself is released first, as Go releases cfgMu before
        // `UpdateModelCatalogSources`, so readers never wait on a catalog publish.
        let commit = self.config_commit.lock().unwrap_or_else(PoisonError::into_inner);
        let previous = {
            // The plugin worker is told under the same lock, so concurrent publishes
            // reach it in the order they replaced the config.
            let mut current = self.config.write().unwrap_or_else(PoisonError::into_inner);
            let previous = std::mem::replace(&mut *current, config.clone());
            self.plugins.config_published(config.clone());
            previous
        };
        // Go `UpdateModelCatalogSources`; the reads stay async.
        if let Some(catalogs) = self.catalogs.lock().unwrap_or_else(PoisonError::into_inner).as_ref() {
            catalogs.configure(&config, false);
        }
        drop(commit);
        // Go's websocket auth change handler: turning ws-auth on ends the relay sessions
        // that connected without a key.
        if ws_auth && !crate::relay::ws_auth(&previous) {
            self.executors.google.aistudio.relay.stop();
        }
        self.publish_policy(policy);
        self.store.configure_cooldown_store(dir);
        self.config_changed.send_replace(());
        true
    }

    /// A coherent config/policy pair for the entire route attempt loop.
    pub fn request_snapshot(&self) -> (Arc<Config>, Arc<Policy>) {
        let config = self.config.read().unwrap_or_else(PoisonError::into_inner);
        (config.clone(), self.policy())
    }

    pub fn store(&self) -> &Arc<CredentialStore> {
        &self.store
    }

    /// Go `nextModelPoolOffset`: the start index for the next pass over a pool.
    pub fn next_pool_offset(&self, key: &str, size: usize) -> usize {
        if size <= 1 || key.trim().is_empty() {
            return 0;
        }
        let key = key.trim();
        let mut offsets = self.pool_offsets.lock().unwrap_or_else(PoisonError::into_inner);
        // ponytail: Go never prunes, so keys of removed credentials would accumulate
        // forever. Past 4096 keys the map is cleared, which restarts rotation for every
        // pool from offset 0. Upgrade path: drop a pool's key when its credential set
        // changes in reconcile.
        if offsets.len() >= 4096 && !offsets.contains_key(key) {
            offsets.clear();
        }
        let slot = offsets.entry(key.to_owned()).or_default();
        let offset = if *slot >= 2_147_483_640 { 0 } else { *slot };
        *slot = offset + 1;
        offset % size
    }

    /// One credential's projected state for one registered model (Go
    /// `clientModelProjectionForAuth`), for listings and `auto`.
    pub fn suspension(&self, credential_id: &str, model: &str) -> crate::registry::Suspension {
        use crate::registry::Suspension;
        let Some(credential) = self.store.get(credential_id) else {
            return Suspension::None;
        };
        let aliases = crate::registry::global_aliases(&self.config());
        let key = crate::registry::selection_model(&aliases, &credential, model);
        self.store.suspension(&credential, &key)
    }

    /// Wires OAuth callback delivery (management owns pending login sessions).
    pub fn set_oauth_callback_sink(&self, sink: Option<OAuthCallbackSink>) {
        *self.oauth_sink.write().unwrap_or_else(PoisonError::into_inner) = sink;
    }

    pub fn deliver_oauth_callback(&self, callback: &OAuthCallback) -> OAuthDelivery {
        let sink = self.oauth_sink.read().unwrap_or_else(PoisonError::into_inner).clone();
        sink.map_or(OAuthDelivery::NotPending, |sink| sink(callback))
    }

    /// The credential an executor call receives: the stored one, or in a test runtime
    /// ([`crate::testing`]) a copy that cannot leave the machine.
    pub(crate) fn for_executor(&self, credential: &Arc<Credential>) -> Arc<Credential> {
        if self.deny_external.load(std::sync::atomic::Ordering::Relaxed) {
            crate::testing::guarded(credential, &self.config())
        } else {
            credential.clone()
        }
    }

    /// The model registry for the current config and credential set. Rebuilt only when
    /// either changed, so it is always derived, never separately maintained.
    pub fn registry(&self) -> Arc<Registry> {
        let config = self.config();
        // A refreshed static catalog re-registers every credential (Go's model refresh
        // callback), so the catalog generation is part of the key.
        // Capability probes (Antigravity web search) refine registered models later.
        let generation = (
            self.store.epoch(),
            cpa_core::registry::catalog_generation(),
            cpa_core::registry::dynamic::capabilities_generation(),
        );
        let mut cache = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some((cfg, g, registry)) = cache.as_ref()
            && Arc::ptr_eq(cfg, &config)
            && *g == generation
        {
            return registry.clone();
        }
        let snapshot = self.store.snapshot();
        let registry = Arc::new(Registry::build(&config, &snapshot));
        let credentials: Vec<_> = snapshot.iter().map(|c| self.for_executor(c)).collect();
        self.executors.models_registered(&credentials, &config);
        *cache = Some((config, generation, registry.clone()));
        registry
    }

    pub fn policy(&self) -> Arc<Policy> {
        self.store.policy.read().unwrap_or_else(PoisonError::into_inner).clone()
    }

    pub fn publish_policy(&self, policy: Policy) {
        {
            let mut current = self.store.policy.write().unwrap_or_else(PoisonError::into_inner);
            self.store
                .scheduler
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .configure(&current, &policy);
            *current = Arc::new(policy);
        }
        self.store.clear_disabled_cooldowns();
    }

    /// Selects a credential that registered the route model. Waits for preparation only
    /// when the executor reports [`Readiness::PrepareNow`] (single-flighted per
    /// credential); token refreshes stay with the background loop. The returned lease
    /// holds the committed snapshot.
    pub async fn acquire(
        &self,
        selection: Selection,
        cfg: &Config,
        policy: Arc<Policy>,
        registry: &Registry,
    ) -> Result<Lease, AcquireError> {
        let aliases = crate::registry::global_aliases(cfg);
        let scope = selection.clone();
        let admit = admission(registry, &aliases, &scope, &self.executors, self.plugin_runtime());
        // `soonest-reset` ranks by the quota windows the executors last observed.
        let now = std::time::SystemTime::now();
        let ranks = |c: &Credential| {
            let provider = c.provider.trim().to_ascii_lowercase();
            let snapshot = match provider.as_str() {
                "claude" => self.executors.claude.quota().snapshot(&c.id),
                "codex" => self.executors.codex.quota().snapshot(&c.id),
                _ => None,
            };
            snapshot.map_or_else(crate::scheduler::Windows::default, |s| {
                crate::scheduler::Windows::observed(&provider, &s.signals, s.observed_at, now)
            })
        };
        let request = crate::plugins::scheduler_request(self, &selection, &policy, &admit)?;
        let pick = crate::plugins::scheduler_pick(self, request).await?;
        let mut lease = self.store.select_picked(selection, policy, &admit, &ranks, pick)?;
        if self.executors.readiness(&lease.credential, cfg) != Readiness::PrepareNow {
            return Ok(lease);
        }
        let id = lease.credential.id.clone();
        match self.prepare_credential(&id, cfg, None).await {
            Ok(current) => {
                lease.credential = current;
                // Go stamps the dispatch after preparing the credential.
                lease.redispatch();
            }
            Err(error) => {
                lease.complete(Outcome::Failure(error.clone()));
                return Err(AcquireError::Prepare { id, error });
            }
        }
        Ok(lease)
    }

    /// A lease on credential `id` outside selection, prepared like [`Self::acquire`]
    /// (Go's credits fallback, `findAllAntigravityCreditsCandidateAuths` then
    /// `prepareRequestAuth`). `None` when the credential is gone or preparation fails;
    /// Go records no result for either.
    pub(crate) async fn lease_credential(
        &self,
        id: &str,
        selection: Selection,
        cfg: &Config,
        prepare: impl FnOnce(&Credential) -> Credential,
    ) -> Option<Lease> {
        let mut credential = self.store.get(id)?;
        if self.executors.readiness(&credential, cfg) == Readiness::PrepareNow {
            credential = self.prepare_credential(id, cfg, None).await.ok()?;
        }
        // Outside selection: the lease answers no bounded window or probe reservation.
        let (picked, seq) = {
            let mut scheduler = self.store.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
            (scheduler.outside_selection_generation(), scheduler.dispatch())
        };
        Some(Lease {
            store: self.store.clone(),
            credential: Arc::new(prepare(&credential)),
            execution_model: selection.model.clone(),
            selection,
            attempt: self.store.attempts.fetch_add(1, Ordering::Relaxed),
            policy: self.policy(),
            reported: false,
            picked,
            seq,
            remote: None,
            lcp: None,
        })
    }

    /// The installed remote dispatcher (Go Home mode), if any.
    pub fn remote_dispatch(&self) -> Option<Arc<dyn crate::remote::RemoteDispatch>> {
        self.remote.read().unwrap_or_else(PoisonError::into_inner).clone()
    }

    /// Routes every request through `dispatch` (Go Home mode) or back to the local
    /// scheduler with `None` (additive API).
    pub fn set_remote_dispatch(&self, dispatch: Option<Arc<dyn crate::remote::RemoteDispatch>>) {
        *self.remote.write().unwrap_or_else(PoisonError::into_inner) = dispatch;
    }

    /// One remote pick (Go `pickHomeDispatchSelection`): the lease ends through the
    /// dispatcher, and its release joins `releases`. Also returns Home's request-retry
    /// limit and the client key Home authenticated (empty when it sent none).
    pub(crate) async fn acquire_remote(
        &self,
        dispatch: &dyn crate::remote::RemoteDispatch,
        selection: Selection,
        request: crate::remote::RemoteRequest,
        releases: &crate::remote::PendingReleases,
    ) -> Result<(Lease, Option<i64>, String), crate::remote::RemoteError> {
        let grant = dispatch.dispatch(request).await?;
        let lease = Lease {
            store: self.store.clone(),
            credential: Arc::new(grant.credential),
            execution_model: selection.model.clone(),
            selection,
            attempt: self.store.attempts.fetch_add(1, Ordering::Relaxed),
            policy: self.policy(),
            reported: false,
            picked: 0,
            seq: 0,
            remote: Some(crate::remote::RemoteEnd {
                end: Some(grant.end),
                releases: releases.clone(),
                cancel: grant.cancel,
                private: grant.private,
            }),
            // ponytail: Go's Home dispatch keys its own session aliases on LCP matches
            // (home_session_alias.go); remote picks here carry no LCP binding.
            lcp: None,
        };
        Ok((lease, grant.request_retry, grant.user_api_key))
    }

    /// Go `prepareHomeRequestAuth`: a dispatched credential that requests must wait for
    /// (a Claude identity, a Meta mint) is prepared on this attempt's copy only,
    /// serialized per credential ID. Home owns the stored credential, so nothing is
    /// committed locally.
    pub(crate) async fn prepare_remote(&self, lease: &mut Lease, cfg: &Config) -> Result<(), ExecError> {
        if self.executors.readiness(&lease.credential, cfg) != Readiness::PrepareNow {
            return Ok(());
        }
        let lock = self.store.prepare_lock(&lease.credential.id);
        let _guard = lock.lock().await;
        let patch = self
            .executors
            .prepare(&self.for_executor(&lease.credential), cfg)
            .await?;
        let mut prepared = (*lease.credential).clone();
        patch.apply(&mut prepared.metadata);
        lease.credential = Arc::new(prepared);
        Ok(())
    }

    /// At shutdown: Codex refreshes still waiting for a credential file's lock (another
    /// process holds it) give up, and those that hold it finish, so new tokens a grant
    /// returned are written before the process exits. Later refreshes fail.
    pub async fn shutdown_codex_refreshes(&self) {
        self.codex_refreshes.shutdown.cancel();
        self.codex_refreshes.tasks.close();
        self.codex_refreshes.tasks.wait().await;
    }

    /// The credential lock of the Codex file at `path`, for a write that is not a refresh
    /// (a management save), waited for as a refresh waits: shutdown stops the wait.
    pub(crate) async fn lock_codex_file(&self, path: &Path) -> Result<std::fs::File, String> {
        wait_codex_lock(path, &self.codex_refreshes.shutdown).await
    }

    /// Prepares and commits one credential. `failed` is the revision whose token an
    /// upstream rejected: preparation then runs even when not due, unless another task
    /// already replaced that revision (Go `refreshAuthForRequest`).
    async fn prepare_credential(
        &self,
        id: &str,
        cfg: &Config,
        failed: Option<u64>,
    ) -> Result<Arc<Credential>, ExecError> {
        self.prepare_credential_with(id, cfg, failed, false).await
    }

    /// [`Self::prepare_credential`]; `management` marks a management refresh, which
    /// refreshes every Codex token partition (Go `IsForceRefreshContext`).
    async fn prepare_credential_with(
        &self,
        id: &str,
        cfg: &Config,
        failed: Option<u64>,
        management: bool,
    ) -> Result<Arc<Credential>, ExecError> {
        test_hook("prepare", id);
        // Owned: the commit below moves it into its blocking job, which a cancelled caller
        // cannot stop, so the lock covers the read through the commit either way.
        let guard = self.store.prepare_lock(id).lock_owned().await;
        // Another request may have prepared it while we waited. The registration it is
        // current under is what a plugin refresh records its outcome for.
        let (current, registered) = self
            .store
            .get_registered(id)
            .filter(|(c, _)| !c.disabled)
            .ok_or_else(|| {
                ExecError::local(
                    409,
                    FailureScope::Request,
                    "credential removed or disabled during preparation",
                )
            })?;
        match failed {
            Some(revision) if current.revision != revision => return Ok(current),
            Some(_) => {}
            None if self.readiness(&current, cfg) == Readiness::Ready => return Ok(current),
            None => {}
        }
        let view = self.for_executor(&current);
        let plugin = crate::plugins::refresh::route(self, &current, cfg);
        // Go `CodexExecutor.Refresh` on a Codex credential file: one transaction, under
        // the file's credential lock, owned apart from the caller. A plugin-virtual one
        // refreshes in memory and leaves the plugin's file alone (DIFFERENCES-FROM-GO.md).
        if let Source::File(path) = &current.source
            && plugin.is_none()
            && current.provider == "codex"
            && !marked(&current, "plugin_virtual")
            && path.exists()
        {
            let mode = match failed {
                Some(_) if management => cpa_exec::codex_refresh::RefreshMode::Management,
                Some(_) => cpa_exec::codex_refresh::RefreshMode::Rejected,
                None => cpa_exec::codex_refresh::RefreshMode::Due,
            };
            let refresher = self.executors.codex.refresher(&view, cfg);
            let file = path.clone();
            return refresh_codex_file(
                &self.codex_refreshes,
                self.store.clone(),
                refresher,
                guard,
                current,
                registered,
                view,
                file,
                mode,
            )
            .await;
        }
        // A plugin answer also publishes the committed document's proxy URL (the merged
        // one, or a concurrent edit's when that wins the merge) as the credential's.
        let (patch, publish_proxy) = match (&plugin, failed) {
            (Some(route), _) => {
                let refreshed =
                    crate::plugins::refresh::refresh(self, route, &view, &current, registered.registration).await?;
                (refreshed.patch, refreshed.answered)
            }
            (None, Some(_)) if management => (self.executors.prepare_management(&view, cfg).await?, false),
            (None, Some(_)) => (self.executors.prepare_forced(&view, cfg).await?, false),
            (None, None) => (self.executors.prepare(&view, cfg).await?, false),
        };
        let publish_proxy = move |c: &mut Credential| {
            if publish_proxy {
                publish_metadata_proxy(c);
            }
        };
        let store = self.store.clone();
        let fence = RefreshFence {
            registered,
            plugin: plugin.is_some(),
        };
        let committed = tokio::task::spawn_blocking({
            let id = id.to_owned();
            move || {
                let _guard = guard;
                commit_refresh(&store, &id, &current, fence, &patch, publish_proxy)
            }
        })
        .await
        .map_err(|e| PatchError::Io(e.to_string()))
        .and_then(|r| r)
        .map_err(|e| {
            // The plugin refreshed but nothing was saved: back off as for a failed refresh.
            if plugin.is_some() {
                crate::plugins::refresh::failed(&self.store, id, registered.registration, chrono::Utc::now());
            }
            ExecError::local(
                500,
                FailureScope::Request,
                format!("committing prepared credential: {e:?}"),
            )
        })?;
        Ok(committed)
    }

    /// [`Executors::readiness`], plus the schedule of credentials a plugin refreshes
    /// ([`crate::plugins::refresh`]), which never holds a request. Built-in providers
    /// read their executor alone.
    fn readiness(&self, c: &Credential, cfg: &Config) -> Readiness {
        match self.executors.readiness(c, cfg) {
            Readiness::Ready if self.plugin_refresh_due(c, cfg, chrono::Utc::now()) => Readiness::RefreshSoon,
            readiness => readiness,
        }
    }

    fn plugin_refresh_due(&self, c: &Credential, cfg: &Config, now: chrono::DateTime<chrono::Utc>) -> bool {
        crate::plugins::refresh::due_at(self, c, cfg).is_some_and(|at| at <= now)
    }

    /// Go `tryRefreshAfterUnauthorized`: after an upstream 401 on a credential whose
    /// executor reports a refresh credential, prepare it once (due or not) and return the
    /// committed replacement to retry with.
    // ponytail: refresh goes through `Executors::prepare_forced`: Codex refreshes when not
    // due, and Claude's prepare already refreshed on demand before 50d5fe18. A provider
    // whose prepare refreshes only inside its lead cannot recover a revoked token here.
    pub async fn refresh_after_unauthorized(&self, credential: &Credential, cfg: &Config) -> Option<Arc<Credential>> {
        if !self.executors.has_refresh_credential(credential) {
            return None;
        }
        let refreshed = match self
            .prepare_credential(&credential.id, cfg, Some(credential.revision))
            .await
        {
            Ok(refreshed) => refreshed,
            Err(error) => {
                // The background loop's schedule is the next attempt, unless another 401
                // comes first.
                let next = self
                    .refresh_state
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .retry_at(credential)
                    .map(|at| at.saturating_duration_since(Instant::now()));
                warn_refresh_failed(credential, " after an upstream 401", &error, next);
                return None;
            }
        };
        (refreshed.revision != credential.revision).then(|| {
            tracing::info!(
                "credential refreshed for {} ({}) after an upstream 401",
                credential.provider,
                credential.id
            );
            refreshed
        })
    }

    /// One replaceable refresh loop. Uses the same preparation lock and atomic
    /// revision-checked commit as request acquisition; executors never persist files.
    /// ponytail: needs_prepare controls eligibility. Unauthorized lifecycle gating
    /// and end-to-end token rotation await executor/lifecycle integration (M4-0027).
    pub fn start_auto_refresh(self: &Arc<Self>) {
        let mut task = self.refresh_task.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(previous) = task.take() {
            previous.abort();
        }
        let weak = Arc::downgrade(self);
        // Only shutdown (the runtime dropped) or an abort ends the loop: a panic anywhere
        // in it is logged and the loop starts again, with fresh subscriptions.
        let handle = tokio::spawn(async move {
            loop {
                match AssertUnwindSafe(refresh_loop(weak.clone())).catch_unwind().await {
                    Ok(()) => break,
                    Err(panic) => {
                        tracing::error!(
                            "credential auto-refresh loop panicked ({}); restarting it in {}s",
                            panic_text(&*panic),
                            REFRESH_LOOP_RESTART.as_secs()
                        );
                        tokio::time::sleep(REFRESH_LOOP_RESTART).await;
                    }
                }
            }
        });
        *task = Some(handle.abort_handle());
    }

    pub fn stop_auto_refresh(&self) {
        if let Some(task) = self.refresh_task.lock().unwrap_or_else(PoisonError::into_inner).take() {
            task.abort();
        }
    }
}

/// The body of [`Runtime::start_auto_refresh`]'s task. Returns when the runtime is gone.
async fn refresh_loop(weak: std::sync::Weak<Runtime>) {
    // Wakes at the next deadline, or at the latest after `HORIZON` of awake time while
    // a credential can ever come due, to catch wall-clock jumps such as a resumed
    // laptop (monotonic time stops during suspend). Credentials that never need
    // preparation (API keys, Gemini CLI tokens) set no timer.
    const HORIZON: Duration = Duration::from_secs(600);
    // Store changes (each committed refresh is one) are coalesced over this delay.
    const COALESCE: Duration = Duration::from_secs(1);
    let Some(rt) = weak.upgrade() else {
        return;
    };
    let mut store_changes = rt.store.subscribe();
    let mut config_changes = rt.subscribe_config();
    let mut unauthorized = rt.store.subscribe_unauthorized();
    let mut jobs_ended = rt.refresh_done.subscribe();
    // The worker bound (`oauth.auth-auto-refresh-workers`), taken inside each job.
    let mut workers = (0, Arc::new(tokio::sync::Semaphore::new(0)));
    drop(rt);
    loop {
        let Some(rt) = weak.upgrade() else {
            break;
        };
        // Everything published so far is in this scan, including the commits of
        // the previous batch.
        store_changes.borrow_and_update();
        config_changes.borrow_and_update();
        unauthorized.borrow_and_update();
        jobs_ended.borrow_and_update();
        let cfg = rt.config();
        // A soft bound while the setting changes: jobs holding the old semaphore's
        // permits run beside the new one's.
        if workers.0 != refresh_workers(&cfg) {
            workers = (
                refresh_workers(&cfg),
                Arc::new(tokio::sync::Semaphore::new(refresh_workers(&cfg))),
            );
        }
        // Each reservation is handed to its spawned job at once, so whatever ends this
        // loop (an abort, a panic later in the scan), the job ends the reservation.
        let spawn = |c: &Arc<Credential>, rejected: bool| {
            let job = run_refresh_job(rt.clone(), cfg.clone(), workers.1.clone(), c.clone(), rejected);
            tokio::spawn(job)
        };
        // Before the snapshot, so a 401 on a revision newer than it stays.
        let rejected = rt.store.unauthorized();
        let snapshot = rt.store.snapshot();
        let (now, wall) = (Instant::now(), chrono::Utc::now());
        let horizon = chrono::Duration::from_std(HORIZON).unwrap_or_default();
        let mut wake: Option<Instant> = None;
        let mut soonest = |at: Instant| wake = Some(wake.map_or(at, |w| w.min(at)));
        let jobs: Vec<_> = {
            let mut state = rt.refresh_state.lock().unwrap_or_else(PoisonError::into_inner);
            state.reconcile(&snapshot);
            let mut jobs = Vec::new();
            rt.store.forget_stale_unauthorized(&rejected, &snapshot);
            // Far enough ahead that any expiry has passed, near enough for chrono.
            let eventually = wall + chrono::Duration::days(36_500);
            for c in snapshot.iter().filter(|c| refresh_candidate(c)) {
                test_hook("scan", &c.id);
                // Go `scheduleUnauthorizedRefresh`: a rejected token refreshes now,
                // or after `refreshFailureBackoff` when it was refreshed just before.
                // Its deadline replaces the ordinary one (Go `NextRefreshAfter`).
                if let Some((revision, noted)) = rejected.pending.get(&c.id)
                    && *revision == c.revision
                    && rt.executors.has_refresh_credential(c)
                {
                    let at = rejected
                        .refreshed
                        .get(&c.id)
                        .filter(|(r, t)| {
                            *r <= *revision && noted.saturating_duration_since(*t) < REFRESH_FAILURE_BACKOFF
                        })
                        .map_or(*noted, |_| *noted + REFRESH_FAILURE_BACKOFF);
                    if at > now {
                        soonest(at);
                    } else if state.reserve(c, now) {
                        jobs.push(spawn(c, true));
                    } else {
                        warn_refresh_held(&mut state, c);
                        if let Some(at) = state.retry_at(c).filter(|at| *at > now) {
                            soonest(at);
                        }
                    }
                    continue;
                }
                let plugin_due = crate::plugins::refresh::due_at(&rt, c, &cfg);
                if rt.executors.needs_prepare_at(c, &cfg, eventually) || plugin_due.is_some() {
                    soonest(now + HORIZON);
                }
                let due = rt
                    .executors
                    .prepare_due(c, &cfg, wall, horizon)
                    .or_else(|| plugin_due.filter(|at| *at <= wall + horizon).map(|at| at.max(wall)));
                match due {
                    Some(at) if at > wall => soonest(now + (at - wall).to_std().unwrap_or_default()),
                    Some(_) if state.reserve(c, now) => jobs.push(spawn(c, false)),
                    // A job still running, or backing off: look again when that ends.
                    Some(_) => {
                        warn_refresh_held(&mut state, c);
                        if let Some(at) = state.retry_at(c).filter(|at| *at > now) {
                            soonest(at);
                        }
                    }
                    None => {}
                }
            }
            jobs
        };
        let busy = !jobs.is_empty();
        // The loop waits for the batch, at most `REFRESH_JOB_BOUND` per job, then looks
        // again. A job it stops waiting for runs on, records its own outcome and wakes the
        // loop when it ends.
        futures_util::future::join_all(jobs.into_iter().map(|job| async move {
            let _ = tokio::time::timeout(REFRESH_JOB_BOUND, job).await;
        }))
        .await;
        drop(rt);
        // After a batch, look again at once: finished jobs set their backoff,
        // and the next scan turns it into a deadline.
        if busy {
            continue;
        }
        let deadline = async {
            match wake {
                Some(at) => tokio::time::sleep_until(at.into()).await,
                None => std::future::pending().await,
            }
        };
        tokio::select! {
            () = deadline => {}
            changed = store_changes.changed() => {
                if changed.is_err() {
                    break;
                }
                tokio::time::sleep(COALESCE).await;
            }
            changed = config_changes.changed() => {
                if changed.is_err() {
                    break;
                }
                tokio::time::sleep(COALESCE).await;
            }
            changed = unauthorized.changed() => {
                if changed.is_err() {
                    break;
                }
            }
            changed = jobs_ended.changed() => {
                if changed.is_err() {
                    break;
                }
                tokio::time::sleep(COALESCE).await;
            }
        }
    }
}

/// One background refresh job of [`refresh_loop`], which reserved `credential`: prepares
/// it, then records the outcome in the refresh state, which ends the reservation, and
/// logs it. The reservation ends exactly once on every path: a panic while preparing is
/// a failure, and [`Reservation`]'s drop covers the rest. The exception is a job dropped
/// before its first poll at runtime teardown, whose reservation goes with the runtime.
// ponytail: a job the loop stopped waiting for keeps running, holding the runtime, and
// neither `stop_auto_refresh` nor the runtime's drop aborts it (its exchange may have
// spent the refresh token already). At most one such job per credential outlives the
// loop, as the reservation holds off the next.
async fn run_refresh_job(
    rt: Arc<Runtime>,
    cfg: Arc<Config>,
    workers: Arc<tokio::sync::Semaphore>,
    credential: Arc<Credential>,
    rejected: bool,
) {
    let mut reservation = Reservation {
        rt: rt.clone(),
        credential: credential.clone(),
        ended: false,
    };
    let worker = workers.acquire_owned().await;
    let failed = rejected.then_some(credential.revision);
    let prepare = AssertUnwindSafe(rt.prepare_credential(&credential.id, &cfg, failed)).catch_unwind();
    tokio::pin!(prepare);
    // Past the bound, counted from when the job got its worker, the worker goes to the
    // next job, and this one awaits the same preparation, never cancelled, still
    // holding its reservation.
    let prepared = match tokio::time::timeout(REFRESH_JOB_BOUND, &mut prepare).await {
        Ok(prepared) => prepared,
        Err(_) => {
            tracing::warn!(
                "credential refresh for {} ({}) still running after {}s; no other refresh of it starts until it ends",
                credential.provider,
                credential.id,
                REFRESH_JOB_BOUND.as_secs()
            );
            drop(worker);
            prepare.await
        }
    };
    // A panic records no plugin deadline: it backs off here, plugin route or not.
    let (result, panicked) = match prepared {
        Ok(result) => (result, false),
        Err(panic) => {
            let text = format!("refresh panicked: {}", panic_text(&*panic));
            (Err(ExecError::local(500, FailureScope::Request, text)), true)
        }
    };
    if rejected && result.is_ok() {
        rt.store.forget_unauthorized(&credential.id, credential.revision);
    }
    let trigger = if rejected { " after an upstream 401" } else { "" };
    let current = rt.store.get(&credential.id);
    // A concurrent removal/re-import or management edit must not transfer the old
    // refresh failure/backoff to the replacement, which is tried when it is due.
    let Some(current) = current.filter(|c| match &result {
        Ok(prepared) => prepared.revision == c.revision,
        Err(_) => c.revision == credential.revision,
    }) else {
        reservation.end(|state| state.release(&credential.id));
        if let Err(error) = &result {
            warn_refresh_failed(&credential, trigger, error, None);
        }
        return;
    };
    // A plugin refresh keeps its own deadlines (Go `NextRefreshAfter`,
    // `crate::plugins::refresh`): release the reservation only.
    let plugin = !panicked && crate::plugins::refresh::route(&rt, &current, &cfg).is_some();
    let ineffective = !plugin && result.is_ok() && rt.readiness(&current, &cfg) != Readiness::Ready;
    let now = Instant::now();
    let retry = reservation.end(|state| {
        state.finish(&current, result.as_ref().err().filter(|_| !plugin), ineffective, now);
        state.retry_at(&current)
    });
    match &result {
        Err(error) => {
            let next = if plugin {
                crate::plugins::refresh::due_at(&rt, &current, &cfg)
                    .map(|at| (at - chrono::Utc::now()).to_std().unwrap_or_default())
            } else {
                retry.map(|at| at.saturating_duration_since(now))
            };
            warn_refresh_failed(&current, trigger, error, next);
        }
        // Go retries an ineffective refresh after 30 s and logs nothing.
        Ok(_) if ineffective => {}
        Ok(_) if current.revision != credential.revision => {
            tracing::info!(
                "credential refreshed for {} ({}){trigger}",
                current.provider,
                current.id
            );
        }
        Ok(_) => {}
    }
}

/// A refresh job's reservation of its credential. [`Self::end`] records the outcome and
/// wakes the refresh loop; a job that ends any other way (a panic outside preparation,
/// cancellation at shutdown) records a failure when this drops.
struct Reservation {
    rt: Arc<Runtime>,
    credential: Arc<Credential>,
    ended: bool,
}

impl Reservation {
    fn end<T>(&mut self, record: impl FnOnce(&mut RefreshState) -> T) -> T {
        let recorded = record(&mut self.rt.refresh_state.lock().unwrap_or_else(PoisonError::into_inner));
        self.ended = true;
        self.rt.refresh_done.send_replace(());
        recorded
    }
}

impl Drop for Reservation {
    fn drop(&mut self) {
        if !self.ended {
            let error = ExecError::local(500, FailureScope::Request, "refresh job ended without a result");
            let credential = self.credential.clone();
            self.end(|state| state.finish(&credential, Some(&error), false, Instant::now()));
            warn_refresh_failed(&credential, "", &error, None);
        }
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        if let Some(task) = self
            .refresh_task
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
        {
            task.abort();
        }
    }
}

/// Where cooldowns persist: `auth-dir` while `save-cooldown-status` is on.
fn cooldown_dir(cfg: &Config, policy: &Policy) -> Option<std::path::PathBuf> {
    policy.save_cooldown_status.then(|| cfg.auth_dir.clone())
}

/// How long the refresh loop waits for one refresh job, the wait for the credential's
/// preparation lock included, before it moves on. The job runs on and records its own
/// outcome; until then no other job for the credential starts.
const REFRESH_JOB_BOUND: Duration = Duration::from_secs(if cfg!(test) { 2 } else { 300 });

/// The pause before a panicked refresh loop starts again.
const REFRESH_LOOP_RESTART: Duration = Duration::from_secs(if cfg!(test) { 0 } else { 5 });

/// One warning per failed refresh (Go logs most of these at Debug; see
/// DIFFERENCES-FROM-GO.md): provider, credential, status, the error and when the next
/// attempt is. `trigger` names what started it. A built-in executor's error text is
/// sanitized as client-facing upstream errors are (Go `SanitizeUpstreamErrorSummary`);
/// of a plugin's failure only its error code is logged, never its message, and token
/// endpoint bodies never reach the error text.
fn warn_refresh_failed(c: &Credential, trigger: &str, error: &ExecError, next: Option<Duration>) {
    let text = match error.headers.get(crate::plugins::refresh::PLUGIN_ERROR) {
        Some(code) => match code.to_str().unwrap_or_default() {
            "" => "plugin refresh failed".to_owned(),
            code => format!("plugin refresh failed: {code}"),
        },
        None => crate::sanitize::summary(&String::from_utf8_lossy(&error.body)),
    };
    let next = match next {
        Some(after) if !after.is_zero() => format!("next attempt in {}s", ceil_secs(after)),
        _ => "next attempt when it is next due".to_owned(),
    };
    tracing::warn!(
        "credential refresh failed for {} ({}){trigger}: status {}: {text}; {next}",
        c.provider,
        c.id,
        error.status
    );
}

/// A due refresh held back by its previous job, which is still running: logged once
/// per job. A finished job's backoff is not logged here: a failure announced it, and Go
/// is silent about an ineffective refresh.
fn warn_refresh_held(state: &mut RefreshState, c: &Credential) {
    if state.note_hold(c) {
        tracing::warn!(
            "credential refresh for {} ({}) is due but its previous refresh is still running; it is tried again once that ends",
            c.provider,
            c.id
        );
    }
}

fn ceil_secs(d: Duration) -> u64 {
    d.as_secs() + u64::from(d.subsec_nanos() > 0)
}

/// A panic payload's message.
fn panic_text(panic: &(dyn std::any::Any + Send)) -> &str {
    panic
        .downcast_ref::<&str>()
        .copied()
        .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
        .unwrap_or("non-string payload")
}

/// Go `refreshFailureBackoff`: an unauthorized refresh waits this long after a refresh
/// that just rotated the tokens.
const REFRESH_FAILURE_BACKOFF: Duration = Duration::from_secs(300);

/// `oauth.auth-auto-refresh-workers`: non-positive means Go's default of 16.
fn refresh_workers(cfg: &Config) -> usize {
    cfg.document
        .get("oauth")
        .and_then(|o| o.get("auth-auto-refresh-workers"))
        .and_then(serde_yaml_ng::Value::as_i64)
        .filter(|n| *n > 0)
        .map_or(16, |n| n as usize)
}

/// How a selection picks among its ready candidates.
pub(crate) enum Pick {
    /// The configured selector (strategy and session affinity).
    Configured,
    /// A plugin scheduler's delegation to a built-in strategy.
    Builtin(crate::scheduler::Strategy),
    /// A plugin scheduler's chosen credential.
    Auth(String),
}

/// A selection's eligible credentials with their execution models, and those of them
/// that are ready now with their provider keys; when none is ready, the error Go's
/// availability check reports. `configured` adds the configured selector's own filter
/// (weighted round-robin skips non-positive weights); a plugin scheduler and its
/// built-in delegates see every available credential.
#[allow(clippy::type_complexity)]
fn ready<'a>(
    creds: &'a [Arc<Credential>],
    scheduler: &crate::scheduler::Scheduler,
    selection: &Selection,
    policy: &Policy,
    admit: &Admit<'_>,
    now: Instant,
    configured: bool,
) -> Result<(Vec<(&'a Arc<Credential>, String)>, Vec<(&'a Arc<Credential>, String)>), AcquireError> {
    let eligible: Vec<_> = creds
        .iter()
        .filter(|c| !c.disabled && !selection.exclude.contains(&c.id))
        .filter(|c| policy.retry_limit(c) >= selection.retry_round && (!configured || scheduler.admits(c, policy)))
        .filter_map(|c| admit(c).map(|m| (c, m)))
        .collect();
    let candidates: Vec<_> = eligible
        .iter()
        .filter(|(c, m)| scheduler.wait(c, m, now).is_none())
        .map(|(c, _)| (*c, crate::registry::provider_key(c)))
        .collect();
    if candidates.is_empty() {
        let cause = eligible
            .iter()
            .filter_map(|(c, m)| scheduler.last_error(c, m))
            .max_by_key(|s| s.deadline)
            .map(|s| s.error.clone());
        let wait = eligible.iter().filter_map(|(c, m)| scheduler.wait(c, m, now)).min();
        if !eligible.is_empty() && eligible.iter().all(|(c, m)| scheduler.quota_cooling(c, m, now)) {
            return Err(AcquireError::Cooldown {
                wait: wait.unwrap_or_default(),
                cause,
            });
        }
        return Err(AcquireError::Unavailable {
            retry_after: if eligible.is_empty() { None } else { wait },
            cause,
        });
    }
    Ok((eligible, candidates))
}

#[derive(Debug)]
pub enum AcquireError {
    /// No candidate is ready. `retry_after` is set when candidates exist but are all
    /// blocked (Go `auth_unavailable`); unset means none is eligible (`auth_not_found`).
    Unavailable {
        retry_after: Option<Duration>,
        cause: Option<String>,
    },
    /// Every eligible candidate is quota-cooling for this model.
    Cooldown {
        wait: Duration,
        cause: Option<String>,
    },
    Prepare {
        id: String,
        error: ExecError,
    },
    /// A plugin scheduler rejected the selection (Go `pickViaPluginScheduler`).
    Rejected {
        code: String,
        message: String,
    },
    /// A plugin scheduler's call failed; Go returns its error as the selection error.
    Scheduler(ExecError),
}

/// Route-model state is separate from the lease's resolved execution model.
#[derive(Debug, Clone, Default)]
pub struct Selection {
    /// Provider keys that may serve the model, in preference order.
    pub providers: Vec<String>,
    /// Single-provider shorthand, used when `providers` is empty.
    pub provider: String,
    /// The route model (requested model after `auto` resolution, suffix kept).
    pub model: String,
    /// The session this request binds to (Go `extractSessionIDs` primary).
    pub session: Option<String>,
    /// The session's parent, or the conversation alias of a prompt-cache-key session
    /// (Go fallback ID).
    pub session_parent: Option<String>,
    /// The session forked from `session_parent` (inherits its binding).
    pub session_fork: bool,
    /// A request without an explicit session, for the LCP matcher (Go `pickLCP`). Set
    /// only with session affinity on; it then decides the binding instead of `session`.
    pub lcp: Option<Arc<crate::lcp::Request>>,
    /// Credential IDs already tried in this request.
    pub exclude: Vec<String>,
    pub retry_round: usize,
    /// What a plugin scheduler learns about the request (Go `SchedulerPickRequest`'s
    /// `Stream` and `Options`); without it the scheduler sees no headers or metadata.
    pub scheduler: Option<Arc<crate::plugins::SchedulerContext>>,
}

impl Selection {
    pub fn new(provider: &str, model: &str) -> Self {
        Self {
            providers: vec![provider.to_owned()],
            model: model.to_owned(),
            ..Self::default()
        }
    }

    /// The provider keys this selection may use.
    pub fn provider_keys(&self) -> Vec<String> {
        if self.providers.is_empty() && !self.provider.is_empty() {
            vec![self.provider.clone()]
        } else {
            self.providers.clone()
        }
    }
}

/// Whether `next` would change nothing about the stored `current` (reconcile keeps
/// such a credential and its revision).
fn unchanged(current: &Credential, next: &Credential) -> bool {
    current.id == next.id
        && current.source == next.source
        && current.metadata == next.metadata
        && current.attributes == next.attributes
        && current.provider == next.provider
        && current.disabled == next.disabled
        && current.label == next.label
}

/// Admission without a registry: provider match, prefix, config aliases and the
/// credential's exclusions (attributes first, then file metadata).
pub fn standalone_admission<'a>(
    selection: &'a Selection,
    policy: &'a Policy,
) -> impl Fn(&Credential) -> Option<String> + 'a {
    let providers = selection.provider_keys();
    move |c| {
        if !providers.contains(&crate::registry::provider_key(c)) {
            return None;
        }
        let route = selection.model.trim();
        let prefix = crate::registry::credential_prefix(c);
        let base = crate::scheduler::canonical_model(route);
        if !prefix.is_empty()
            && !base.starts_with(&format!("{prefix}/"))
            && (policy.force_model_prefix || base.contains('/'))
        {
            return None;
        }
        let (models, _) = crate::registry::execution_models(&HashMap::new(), c, route);
        let model = models.into_iter().next().unwrap_or_default();
        // Go lowercases model IDs and patterns with `strings.ToLower`.
        let key = crate::scheduler::canonical_model(&model).go_lower();
        let excluded: Vec<String> = match c.attributes.get("excluded_models").filter(|v| !v.trim().is_empty()) {
            Some(list) => list.split(',').map(|p| p.trim().go_lower()).collect(),
            None => c
                .metadata
                .get("excluded_models")
                .and_then(serde_json::Value::as_array)
                .map(|l| {
                    l.iter()
                        .filter_map(|v| v.as_str())
                        .map(|p| p.trim().go_lower())
                        .collect()
                })
                .unwrap_or_default(),
        };
        if excluded.iter().any(|p| crate::registry::wildcard(p, &key)) {
            return None;
        }
        Some(model)
    }
}

#[derive(Debug, Clone)]
pub enum Outcome {
    Success,
    Failure(ExecError),
    /// A failure that must not change availability (compact request faults, a
    /// missing count_tokens endpoint).
    Neutral(ExecError),
    /// The client went away before the response finished.
    Cancelled,
}

/// Decides which credentials may serve a selection and under which model key their
/// cooldowns live. `None` rejects the credential.
pub type Admit<'a> = dyn Fn(&Credential) -> Option<String> + 'a;

/// Registry admission (Go `authSupportsRouteModel`) plus a registered executor, built-in
/// or plugin.
pub fn admission<'a>(
    registry: &'a Registry,
    aliases: &'a HashMap<String, Vec<crate::registry::OAuthAlias>>,
    selection: &'a Selection,
    executors: &'a Executors,
    plugins: &'a crate::plugins::PluginRuntime,
) -> impl Fn(&Credential) -> Option<String> + 'a {
    move |c| {
        let provider = crate::registry::provider_key(c);
        if !selection.provider_keys().contains(&provider)
            || !(executors.supports(&c.provider) || plugins.has_executor(&c.provider))
        {
            return None;
        }
        let key = crate::registry::selection_model(aliases, c, &selection.model);
        let route = crate::scheduler::canonical_model(&selection.model);
        if route.is_empty() {
            return Some(key);
        }
        let selection_key = crate::scheduler::canonical_model(&key);
        (registry.client_supports(&c.id, route)
            || (selection_key != route && registry.client_supports(&c.id, selection_key)))
        .then_some(key)
    }
}

/// One attempt with one credential. Not cloneable: it reports exactly one outcome.
pub struct Lease {
    store: Arc<CredentialStore>,
    pub credential: Arc<Credential>,
    pub selection: Selection,
    /// The model key the outcome is recorded under (Go `stateModelForExecution`).
    pub execution_model: String,
    pub attempt: u64,
    policy: Arc<Policy>,
    reported: bool,
    /// The scheduler generation at the pick (`Scheduler::reserve_probe`): bounded
    /// windows opened or probes reserved after it are not answered by this attempt.
    picked: u32,
    /// The upstream dispatch stamp (`Scheduler::dispatch`); 0 for remote leases.
    seq: u64,
    /// A credential from the remote dispatcher: its lease ends there, not in the local
    /// scheduler.
    remote: Option<crate::remote::RemoteEnd>,
    /// The LCP binding of the pick: the attempt's canonical session and lineage.
    pub lcp: Option<crate::lcp::Match>,
}

impl Lease {
    /// Whether the credential came from the remote dispatcher (Go Home mode).
    pub fn is_remote(&self) -> bool {
        self.remote.is_some()
    }

    /// What a Home pick keeps outside the credential's attributes.
    pub(crate) fn home_private(&self) -> Option<&crate::remote::Private> {
        self.remote.as_ref().map(|remote| &remote.private)
    }

    /// Resolves when the dispatcher cancels this lease's execution.
    pub(crate) fn remote_cancelled(&self) -> Option<futures_util::future::BoxFuture<'static, ()>> {
        let signal = self.remote.as_ref()?.cancel.clone()?;
        Some(crate::remote::cancelled(signal))
    }

    /// Whether the dispatcher cancelled this lease's execution (Go: its selection is
    /// no longer `Active`).
    pub(crate) fn remote_cancel_requested(&self) -> bool {
        self.remote
            .as_ref()
            .and_then(|remote| remote.cancel.as_ref())
            .is_some_and(|signal| *signal.borrow())
    }

    /// A new upstream dispatch on this lease (a refresh-and-retry): a cooldown recorded
    /// before it no longer predates this attempt (Go `nextExecutionSeq` per dispatch).
    pub(crate) fn redispatch(&mut self) {
        if self.remote.is_none() {
            self.seq = self
                .store
                .scheduler
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .dispatch();
        }
    }

    pub fn complete(mut self, outcome: Outcome) {
        self.report(outcome);
    }

    /// Joins a remote lease's release to `releases`: a Home pick a session kept ends or
    /// runs again during a later request, which awaits the release before its next pick.
    pub(crate) fn release_into(&mut self, releases: &crate::remote::PendingReleases) {
        if let Some(remote) = &mut self.remote {
            remote.releases = releases.clone();
        }
    }

    /// The upstream accepted this attempt (a stream's first chunk arrived): an ended
    /// bounded window it probes has its answer, so other requests may use the account
    /// while the stream runs (`Scheduler::accept_probe`). A no-op for remote leases.
    pub fn accepted(&self) {
        if self.remote.is_none() {
            self.store.accept_probe(self);
        }
    }

    /// Records an intermediate outcome for one model of a pooled alias without ending
    /// the lease.
    pub fn note(&self, model: &str, outcome: &Outcome) {
        if self.remote.is_none() {
            self.store.record_model(self, model, outcome);
        }
    }

    fn report(&mut self, outcome: Outcome) {
        if std::mem::replace(&mut self.reported, true) {
            return;
        }
        match &mut self.remote {
            // Go `reportHomeResult` leaves local cooldowns alone; the scope ends with
            // its release.
            Some(remote) => remote.finish(),
            None => self.store.record(self, &outcome),
        }
    }
}

impl Drop for Lease {
    fn drop(&mut self) {
        self.report(Outcome::Cancelled);
    }
}

impl std::fmt::Debug for Lease {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Lease")
            .field("credential", &self.credential.id)
            .field("attempt", &self.attempt)
            .finish()
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum PatchError {
    NotFound,
    /// The credential changed since the caller read it; re-read and retry.
    Stale {
        current: u64,
    },
    /// `type` decides the executor and cannot change in place.
    TypeIsImmutable,
    /// Config-sourced credentials persist through the config document, not here.
    ConfigBacked,
    Io(String),
    /// Another holder has the credential lock of this Codex file. The writer releases
    /// what it holds, waits for the lock ([`Runtime::lock_codex_file`]) and retries.
    LockBusy(std::path::PathBuf),
}

/// What a token refresh commits under ([`CredentialStore::apply_refresh`]).
#[derive(Debug, Clone, Copy)]
pub(crate) struct RefreshFence {
    /// The registration and credential version the refresh started under
    /// ([`CredentialStore::get_registered`]).
    pub registered: crate::plugins::refresh::Registered,
    /// A plugin refresh, whose schedule the commit records.
    pub plugin: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AttemptStats {
    pub success: u64,
    pub failure: u64,
    pub cancelled: u64,
}

struct Inner {
    creds: Vec<Arc<Credential>>,
    /// Last revision handed out. Revisions are never reused.
    generation: u64,
    /// Bumped on every reconcile and patch, including pure removals.
    epoch: u64,
}

/// Pending background refreshes after a 401, and the last token rotations.
#[derive(Debug, Clone, Default)]
pub(crate) struct Rejections {
    /// The rejected revision of each credential and when the 401 was recorded.
    pub pending: HashMap<String, (u64, Instant)>,
    /// The revision each credential's last token rotation committed, and when.
    pub refreshed: HashMap<String, (u64, Instant)>,
}

pub struct CredentialStore {
    inner: RwLock<Inner>,
    policy: RwLock<Arc<Policy>>,
    scheduler: Mutex<Scheduler>,
    attempts: AtomicU64,
    stats: [AtomicU64; 3],
    prepare_locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
    /// Go 8a01bc02: a credential file is written with `inner` unlocked. Each
    /// credential's lock serializes its own writes, and the reload gate (shared by
    /// writes, exclusive for a set replacement) keeps a reload from landing between a
    /// write and its publication.
    write_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
    reload: RwLock<()>,
    /// `auth-dir` while `save-cooldown-status` is on (Go `cooldownStore`).
    cooldown_dir: RwLock<Option<std::path::PathBuf>>,
    /// Replaces the `.cds` files while set (Go's token-store cooldown provider).
    cooldown_backend: RwLock<Option<Arc<dyn crate::cooldown_store::Backend>>>,
    /// Serializes cooldown snapshots with their writes, so the last write is the newest.
    cooldown_write: Mutex<()>,
    activity: Mutex<HashMap<String, CredentialActivity>>,
    /// Credential revisions whose file already holds Go's persisted form.
    persisted: Mutex<HashMap<String, u64>>,
    /// What each file credential's metadata was built from, by ID ([`Provenance`]).
    provenance: Mutex<HashMap<String, Provenance>>,
    /// Where failed attempts publish Go's error events (set by the runtime).
    error_events: std::sync::OnceLock<Arc<crate::usage::UsageQueue>>,
    /// Marked on every epoch bump, so background loops sleep until the set changes.
    changed: tokio::sync::watch::Sender<()>,
    /// Codex credentials an upstream answered 401, and the last token rotations, for the
    /// background refresh (Go `RejectedAccessToken`, `scheduleUnauthorizedRefresh` and
    /// `LastRefreshedAt`).
    unauthorized: Mutex<Rejections>,
    unauthorized_noted: tokio::sync::watch::Sender<()>,
    /// Ends the upstream WebSocket sessions a removed credential serves (set by the
    /// runtime to [`cpa_exec::Executors::credential_session_closer`]).
    session_closer: std::sync::OnceLock<SessionCloser>,
    /// Go `LastRefreshedAt` and `NextRefreshAfter` of the credentials a plugin
    /// refreshes, registered with every change to the set
    /// ([`crate::plugins::refresh::register`]).
    refresh_schedules: crate::plugins::refresh::Schedules,
}

/// Ends the upstream WebSocket sessions of one removed credential.
type SessionCloser = Box<dyn Fn(&str) + Send + Sync>;

/// The ids in `before` that `after` no longer has.
fn removed_ids(before: &[Arc<Credential>], after: &[Arc<Credential>]) -> Vec<String> {
    let kept: std::collections::HashSet<&str> = after.iter().map(|c| c.id.as_str()).collect();
    before
        .iter()
        .filter(|c| !kept.contains(c.id.as_str()))
        .map(|c| c.id.clone())
        .collect()
}

/// Whether `key` is set to `true` on `credential` (Go `IsPluginVirtualAuth`,
/// `isRuntimeOnlyAuth`).
fn marked(credential: &Credential, key: &str) -> bool {
    credential
        .attributes
        .get(key)
        .is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
}

/// What a file credential's metadata was built from at one revision. Go holds a loaded
/// file's numbers as float64 read from its text, and a saved record's numbers as that
/// save held them; a management save reproduces them only from this, never from the
/// file as it is now, which may have changed since without a reload.
#[derive(Clone)]
pub struct Provenance {
    pub revision: u64,
    /// SHA-256 of the file bytes the revision was loaded from or committed as.
    pub sha256: [u8; 32],
    /// The document a management save committed (Go's metadata after that save); `None`
    /// for a load, where Go's metadata is the float64 reading of those bytes.
    pub doc: Option<Arc<cpa_common::json::GoValue>>,
    /// `doc` is the text of the bytes the record was loaded from (numbers as written,
    /// read as float64 by a save) with a refresh's values in place, not Go's metadata.
    pub loaded: bool,
}

/// How [`CredentialStore::commit_file_backed`] commits a management save.
pub struct Commit {
    /// The bytes the file holds after the save (and the re-synthesized `next` read).
    pub bytes: Vec<u8>,
    /// `false` when the file already holds an equal document: nothing is written, but
    /// the credential is published from `bytes` all the same (Go's store skips the
    /// write, its manager still publishes the auth).
    pub write: bool,
    /// What the file must still hold under the write lock, else `Stale`: `Some(None)`
    /// for no file, `Some(Some(hash))` for those bytes; `None` skips the check.
    pub disk: Option<Option<[u8; 32]>>,
    /// Go's metadata after the save, recorded as the new revision's [`Provenance`].
    pub doc: Option<Arc<cpa_common::json::GoValue>>,
}

/// A value a refresh set, as Go holds it (integers exact, other numbers float64), or
/// with `literal` its number text as written.
fn go_typed(v: &Value, literal: bool) -> cpa_common::json::GoValue {
    use cpa_common::json::GoValue;
    match v {
        Value::Null => GoValue::Null,
        Value::Bool(b) => GoValue::Bool(*b),
        Value::Number(n) if literal || n.is_i64() || n.is_u64() => GoValue::Number(n.to_string()),
        Value::Number(n) => {
            let text = n.to_string();
            GoValue::Number(
                cpa_common::json::json_float(cpa_common::json::parse_float(text.as_bytes())).unwrap_or(text),
            )
        }
        Value::String(s) => GoValue::String(s.clone()),
        Value::Array(items) => GoValue::Array(items.iter().map(|v| go_typed(v, literal)).collect()),
        Value::Object(map) => GoValue::Object(map.iter().map(|(k, v)| (k.clone(), go_typed(v, literal))).collect()),
    }
}

fn sha256(bytes: &[u8]) -> [u8; 32] {
    use sha2::{Digest, Sha256};
    Sha256::digest(bytes).into()
}

impl CredentialStore {
    pub fn new(credentials: Vec<Credential>) -> Arc<Self> {
        let mut inner = Inner {
            creds: Vec::new(),
            generation: 0,
            epoch: 0,
        };
        for mut cred in credentials {
            inner.generation += 1;
            cred.revision = inner.generation;
            inner.creds.push(Arc::new(cred));
        }
        let refresh_schedules = crate::plugins::refresh::Schedules::default();
        crate::plugins::refresh::register(&refresh_schedules, &[], &inner.creds, &[]);
        crate::plugins::refresh::begin_bootstrap(&refresh_schedules);
        Arc::new(Self {
            inner: RwLock::new(inner),
            policy: RwLock::new(Arc::new(Policy::default())),
            scheduler: Mutex::default(),
            attempts: AtomicU64::new(0),
            stats: Default::default(),
            prepare_locks: Mutex::default(),
            write_locks: Mutex::default(),
            reload: RwLock::default(),
            cooldown_dir: RwLock::default(),
            cooldown_backend: RwLock::default(),
            cooldown_write: Mutex::default(),
            activity: Mutex::default(),
            persisted: Mutex::default(),
            provenance: Mutex::default(),
            error_events: std::sync::OnceLock::new(),
            changed: tokio::sync::watch::Sender::new(()),
            unauthorized: Mutex::default(),
            unauthorized_noted: tokio::sync::watch::Sender::new(()),
            session_closer: std::sync::OnceLock::new(),
            refresh_schedules,
        })
    }

    /// Credential `id` and what a refresh of it starts under: its registration and
    /// credential version ([`crate::plugins::refresh::Registered`]), read together.
    pub(crate) fn get_registered(&self, id: &str) -> Option<(Arc<Credential>, crate::plugins::refresh::Registered)> {
        let inner = self.read();
        let credential = inner.creds.iter().find(|c| c.id == id)?.clone();
        Some((credential, self.registered(id)))
    }

    /// What a refresh of `id` starts under; zeros for none.
    fn registered(&self, id: &str) -> crate::plugins::refresh::Registered {
        crate::plugins::refresh::registered(&self.refresh_schedules, id).unwrap_or_default()
    }

    /// Records a refresh outcome of credential `id` (Go reads `m.auths[id]` under
    /// `m.mu`): `record` sees the current credential and its schedule while it is under
    /// `registration` (`NotFound` otherwise) and, given `at`, still at that revision
    /// and credential version (`Stale` otherwise). No registration can land in
    /// between.
    pub(crate) fn record_refresh(
        &self,
        id: &str,
        registration: u64,
        at: Option<(u64, u64)>,
        record: impl FnOnce(&Credential, &mut crate::plugins::refresh::Schedule),
    ) -> Result<Arc<Credential>, PatchError> {
        let inner = self.read();
        let current = inner.creds.iter().find(|c| c.id == id).ok_or(PatchError::NotFound)?;
        let registered = self.registered(id);
        if registered.registration != registration {
            return Err(PatchError::NotFound);
        }
        if at.is_some_and(|at| at != (current.revision, registered.credential_version)) {
            return Err(PatchError::Stale {
                current: current.revision,
            });
        }
        crate::plugins::refresh::record(&self.refresh_schedules, current, record);
        Ok(current.clone())
    }

    /// The plugin refresh schedules ([`crate::plugins::refresh::register`]).
    pub(crate) fn refresh_schedules(&self) -> &crate::plugins::refresh::Schedules {
        &self.refresh_schedules
    }

    /// Ends the startup window in which the credentials loaded before plugins parse auth
    /// files are provisional ([`crate::plugins::refresh::end_bootstrap`]).
    pub fn end_bootstrap(&self) {
        if crate::plugins::refresh::end_bootstrap(&self.refresh_schedules) {
            // The refresh loop skips provisional schedules; it looks again.
            self.changed.send_replace(());
        }
    }

    /// Registers the plugin refresh schedules of a change from `before` to `after`;
    /// called with the change, under the write lock.
    fn register(
        &self,
        before: &[Arc<Credential>],
        after: &[Arc<Credential>],
        saved: &[cpa_plugin::hostauth::SavedRefresh],
    ) {
        crate::plugins::refresh::register(&self.refresh_schedules, before, after, saved);
    }

    /// Go `ApplyConfigWithCooldownStateStore` plus the restore that follows a config
    /// update: the current state goes to the old store before the swap, and a newly
    /// enabled store is restored from. `None` disables persistence.
    pub fn configure_cooldown_store(&self, dir: Option<std::path::PathBuf>) {
        let old = self.cooldown_dir.read().unwrap_or_else(PoisonError::into_inner).clone();
        if old == dir {
            return;
        }
        if old.is_some() {
            self.persist_cooldowns();
        }
        *self.cooldown_dir.write().unwrap_or_else(PoisonError::into_inner) = dir.clone();
        if let Some(dir) = dir {
            self.restore_cooldowns(&dir);
        }
    }

    /// Go's builder taking the token store's `CooldownStateStore`: cooldowns go to
    /// `backend` instead of `.cds` files, restored from it now when persistence is on.
    pub fn set_cooldown_backend(&self, backend: Arc<dyn crate::cooldown_store::Backend>) {
        *self.cooldown_backend.write().unwrap_or_else(PoisonError::into_inner) = Some(backend);
        let dir = self.cooldown_dir.read().unwrap_or_else(PoisonError::into_inner).clone();
        if let Some(dir) = dir {
            self.restore_cooldowns(&dir);
        }
    }

    fn cooldown_backend(&self) -> Option<Arc<dyn crate::cooldown_store::Backend>> {
        self.cooldown_backend
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Go `RestoreCooldownStates`: live records of live credentials whose cooling is
    /// enabled, then a rewrite that drops everything else.
    fn restore_cooldowns(&self, dir: &std::path::Path) {
        let loaded = match self.cooldown_backend() {
            Some(backend) => backend.load(),
            None => crate::cooldown_store::load(dir),
        };
        let records = match loaded {
            Ok(records) => records,
            Err(error) => {
                tracing::warn!(%error, "failed to restore cooldown state");
                return;
            }
        };
        if !records.is_empty() {
            let policy = self.policy.read().unwrap_or_else(PoisonError::into_inner).clone();
            let inner = self.read();
            let mut scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
            let (now, wall) = (Instant::now(), std::time::SystemTime::now());
            for record in &records {
                let Some(c) = inner.creds.iter().find(|c| c.id == record.auth_id.trim()) else {
                    continue;
                };
                if c.disabled || policy.cooling_disabled(c) {
                    continue;
                }
                let has_models = records
                    .iter()
                    .any(|r| r.auth_id.trim() == c.id && !r.model.trim().is_empty());
                scheduler.restore(c, record, has_models, policy.max_trusted_cooldown, now, wall);
            }
        }
        self.persist_cooldowns();
    }

    /// Go `persistCooldownStates`: rewrites the `.cds` files from the live cooldowns.
    pub fn persist_cooldowns(&self) {
        let Some(dir) = self.cooldown_dir.read().unwrap_or_else(PoisonError::into_inner).clone() else {
            return;
        };
        let _write = self.cooldown_write.lock().unwrap_or_else(PoisonError::into_inner);
        let wall = std::time::SystemTime::now();
        let mut records = {
            let policy = self.policy.read().unwrap_or_else(PoisonError::into_inner).clone();
            let inner = self.read();
            let scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
            let now = Instant::now();
            inner
                .creds
                .iter()
                .filter(|c| !c.disabled && !policy.cooling_disabled(c))
                .flat_map(|c| scheduler.records(c, now, wall))
                .collect::<Vec<_>>()
        };
        records.sort_by(|a, b| (&a.provider, &a.auth_id, &a.model).cmp(&(&b.provider, &b.auth_id, &b.model)));
        let saved = match self.cooldown_backend() {
            Some(backend) => backend.save(records, wall),
            None => crate::cooldown_store::save(&dir, records, wall),
        };
        if let Err(error) = saved {
            tracing::warn!(%error, "failed to persist cooldown state");
        }
    }

    /// Go `Manager.persist` after a result (`FileTokenStore.Save`, metadata branch): the
    /// file gets `"disabled"` and Go's `json.Marshal` form unless it already holds the
    /// same JSON. Checked once per revision, so a file is not read on every request.
    // ponytail: atomic replace instead of Go's in-place truncate, and a removed file is
    // not recreated (Go recreates one deleted between watcher reloads).
    fn persist_credential(&self, credential: &Arc<Credential>) {
        let Source::File(path) = &credential.source else {
            return;
        };
        // Go also skips runtime-only credentials and plugin-virtual ones.
        if credential.disabled || marked(credential, "runtime_only") || marked(credential, "plugin_virtual") {
            return;
        }
        {
            let persisted = self.persisted.lock().unwrap_or_else(PoisonError::into_inner);
            if persisted.get(&credential.id) == Some(&credential.revision) {
                return;
            }
        }
        // Written only while the credential is still at this revision: a refresh committed
        // after this request started must not be overwritten with the older token.
        let written = self.write_unlocked(
            &credential.id,
            credential.revision,
            None,
            false,
            |current| {
                let mut metadata = current.metadata.clone();
                metadata.insert("disabled".into(), Value::Bool(current.disabled));
                let go = |bytes: &[u8]| cpa_common::json::GoValue::parse_f64(bytes);
                // An unreadable file or metadata is skipped (`NotFound`), not reported.
                let Some(target) = serde_json::to_vec(&metadata).ok().and_then(|b| go(&b)) else {
                    return Err(PatchError::NotFound);
                };
                let existing = std::fs::read(path).map_err(|_| PatchError::NotFound)?;
                if go(&existing).as_ref() == Some(&target) {
                    return Ok(None);
                }
                Ok(Some((Some(path.clone()), target.marshal(), ())))
            },
            |inner, index, bytes, ()| {
                // Same revision: the file now says what memory already meant (absent
                // `disabled` is false, numbers are float64), so memory takes the written
                // form and the watcher's reload finds nothing changed.
                if let Ok(written) = serde_json::from_slice::<Map<String, Value>>(bytes) {
                    let mut next = Credential::clone(&inner.creds[index]);
                    next.metadata = written;
                    inner.creds[index] = Arc::new(next);
                }
                // A save's document stays Go's metadata, now held by these bytes. A load's
                // float64 reading is not provably these bytes' (they come from serde's
                // values), so it is forgotten.
                let id = &inner.creds[index].id;
                let mut provenance = self.provenance.lock().unwrap_or_else(PoisonError::into_inner);
                match provenance.get_mut(id) {
                    Some(p) if p.doc.is_some() => p.sha256 = sha256(bytes),
                    Some(_) => {
                        provenance.remove(id);
                    }
                    None => {}
                }
            },
        );
        match written {
            Ok(_) => {}
            Err(PatchError::Io(error)) => {
                tracing::warn!(id = %credential.id, %error, "failed to persist credential");
                return;
            }
            Err(_) => return,
        }
        self.persisted
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(credential.id.clone(), credential.revision);
    }

    /// Go `updateInternalLocked` for a credential a reload, save, import or upsert
    /// replaced with other tokens or another API key (`CredentialsChanged`), enabled
    /// before and after: its unauthorized cooldowns go, so the new token is selectable
    /// at once, and every other cooldown (a model's 429, a live credential quota) stays.
    /// Called with the change, under the write lock; returns whether anything was
    /// cleared, for the caller to persist.
    fn clear_replaced_unauthorized(&self, before: &[Arc<Credential>], after: &[Arc<Credential>]) -> bool {
        let replaced: Vec<&str> = after
            .iter()
            .filter(|next| {
                before
                    .iter()
                    .find(|c| c.id == next.id)
                    .is_some_and(|previous| !previous.disabled && !next.disabled && credentials_changed(previous, next))
            })
            .map(|c| c.id.as_str())
            .collect();
        if replaced.is_empty() {
            return false;
        }
        let mut scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
        let now = Instant::now();
        let mut cleared = false;
        for id in replaced {
            cleared |= scheduler.clear_unauthorized(id, now);
        }
        cleared
    }

    /// Go `clearDisabledCooldownStates` after a policy change.
    fn clear_disabled_cooldowns(&self) {
        let policy = self.policy.read().unwrap_or_else(PoisonError::into_inner).clone();
        let cleared = {
            let inner = self.read();
            self.scheduler
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .clear_disabled(&inner.creds, &policy)
        };
        if cleared {
            self.persist_cooldowns();
        }
    }

    pub fn snapshot(&self) -> Vec<Arc<Credential>> {
        self.read().creds.clone()
    }

    pub fn get(&self, id: &str) -> Option<Arc<Credential>> {
        self.read().creds.iter().find(|c| c.id == id).cloned()
    }

    /// Selects among the selection's providers without registry admission (tests and
    /// callers that already filtered credentials).
    pub fn select(self: &Arc<Self>, selection: Selection) -> Option<Lease> {
        let policy = self.policy.read().unwrap_or_else(PoisonError::into_inner).clone();
        let scope = selection.clone();
        let admit = standalone_admission(&scope, &policy);
        self.select_with(selection, policy.clone(), &admit).ok()
    }

    pub fn select_with(
        self: &Arc<Self>,
        selection: Selection,
        policy: Arc<Policy>,
        admit: &Admit<'_>,
    ) -> Result<Lease, AcquireError> {
        self.select_ranked(selection, policy, admit, &|_| crate::scheduler::Windows::default())
    }

    /// [`Self::select_with`] with each credential's usage windows (`soonest-reset`).
    pub fn select_ranked(
        self: &Arc<Self>,
        selection: Selection,
        policy: Arc<Policy>,
        admit: &Admit<'_>,
        ranks: &crate::scheduler::Ranks<'_>,
    ) -> Result<Lease, AcquireError> {
        self.select_picked(selection, policy, admit, ranks, Pick::Configured)
    }

    /// The ready candidates a plugin scheduler chooses among (Go
    /// `availableAuthsForSelector`'s priority list): the highest priority tier, or every
    /// tier when the scheduler asks for them.
    pub(crate) fn scheduler_candidates(
        &self,
        selection: &Selection,
        policy: &Policy,
        admit: &Admit<'_>,
        across: bool,
    ) -> Result<Vec<Arc<Credential>>, AcquireError> {
        let inner = self.read();
        let scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
        let (_, ready) = ready(
            &inner.creds,
            &scheduler,
            selection,
            policy,
            admit,
            Instant::now(),
            false,
        )?;
        let tier = ready.iter().map(|(c, _)| crate::scheduler::priority(c)).max();
        let mut out: Vec<_> = ready
            .into_iter()
            .filter(|(c, _)| across || Some(crate::scheduler::priority(c)) == tier)
            .map(|(c, _)| Arc::clone(c))
            .collect();
        // Go `availableAuthsFromPriorityBuckets` orders both modes by ID.
        out.sort_by(|a, b| a.id.cmp(&b.id));
        Ok(out)
    }

    /// [`Self::select_ranked`] with the choice a plugin scheduler made.
    pub(crate) fn select_picked(
        self: &Arc<Self>,
        selection: Selection,
        policy: Arc<Policy>,
        admit: &Admit<'_>,
        ranks: &crate::scheduler::Ranks<'_>,
        pick: Pick,
    ) -> Result<Lease, AcquireError> {
        let now = Instant::now();
        let credential = {
            let inner = self.read();
            let mut scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
            let configured = matches!(pick, Pick::Configured);
            let (eligible, candidates) = ready(&inner.creds, &scheduler, &selection, &policy, admit, now, configured)?;
            let refs: Vec<(&Credential, &str)> = candidates.iter().map(|(c, p)| (c.as_ref(), p.as_str())).collect();
            let chosen = match &pick {
                // Go serves the candidate from its pre-call snapshot without checking it
                // again; here one that stopped being ready during the call leaves the
                // choice to the configured selector (docs/DIFFERENCES-FROM-GO.md).
                Pick::Auth(id) => refs.iter().find(|(c, _)| c.id == *id).map(|(c, _)| (*c, None)),
                Pick::Builtin(strategy) => scheduler
                    .pick_builtin(&refs, &selection, *strategy, ranks)
                    .map(|c| (c, None)),
                Pick::Configured => None,
            };
            let (picked, lcp) = match chosen {
                Some(chosen) => chosen,
                None => {
                    let refs: Vec<_> = refs.into_iter().filter(|(c, _)| scheduler.admits(c, &policy)).collect();
                    if refs.is_empty() {
                        // Only the configured selector's filter removed them: its error.
                        return Err(ready(&inner.creds, &scheduler, &selection, &policy, admit, now, true)
                            .expect_err("no admitted candidate is ready"));
                    }
                    scheduler.pick_session(&refs, &selection, &policy, ranks, now).unwrap()
                }
            };
            let (c, m) = eligible.iter().find(|(c, _)| c.id == picked.id).unwrap();
            let generation = scheduler.reserve_probe(c, m, now);
            (Arc::clone(c), lcp, generation, scheduler.dispatch())
        };
        let (credential, lcp, picked, seq) = credential;
        let execution_model = admit(&credential).unwrap_or_else(|| selection.model.clone());
        Ok(Lease {
            store: self.clone(),
            credential,
            selection,
            execution_model,
            attempt: self.attempts.fetch_add(1, Ordering::Relaxed),
            policy,
            reported: false,
            picked,
            seq,
            remote: None,
            lcp,
        })
    }

    /// The registry projection of this credential's cooldown state for `model`.
    pub fn suspension(&self, credential: &Credential, model: &str) -> crate::registry::Suspension {
        use crate::registry::Suspension;
        let scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
        let now = Instant::now();
        let live = |m: &str| {
            scheduler
                .cooldowns
                .get(&(credential.id.clone(), crate::scheduler::canonical_model(m).to_owned()))
                .filter(|s| s.deadline > now)
        };
        if let Some(state) = live(model) {
            return match (state.quota, state.status) {
                (true, 429) => Suspension::Quota,
                (quota_exceeded, _) => Suspension::Other { quota_exceeded },
            };
        }
        if live("").is_some() {
            // Credential-wide quota: Go reports these models as `credential_quota`.
            return Suspension::Other { quota_exceeded: false };
        }
        Suspension::None
    }

    /// Whether `model` is cooling for this credential right now. A probe reservation does
    /// not count: the lease that holds it is the one asking.
    pub fn blocked(&self, credential: &Credential, model: &str) -> bool {
        let scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
        scheduler.cooling(credential, model, Instant::now())
    }

    /// Clears every cooldown and affinity binding of one credential (Go `ResetQuota`).
    /// Returns the model keys that were cooling.
    pub fn reset_cooldown(&self, id: &str) -> Vec<String> {
        let models = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner).reset(id);
        if !models.is_empty() {
            self.persist_cooldowns();
        }
        models
    }

    /// Returns the next round's wait, if any credential still permits that round
    /// (Go `closestCooldownWaitWithAttempted`). A wait exceeding the cap is rejected,
    /// not shortened. `status` is the round error's status; `attempted` the credentials
    /// that executed this round (they get the 10s quota floor after a 429).
    pub fn retry_wait(
        &self,
        selection: &Selection,
        policy: &Policy,
        status: u16,
        attempted: &[String],
        admit: &Admit<'_>,
    ) -> Option<Duration> {
        self.retry_wait_at(selection, policy, status, attempted, admit, Instant::now())
    }

    fn retry_wait_at(
        &self,
        selection: &Selection,
        policy: &Policy,
        status: u16,
        attempted: &[String],
        admit: &Admit<'_>,
        now: Instant,
    ) -> Option<Duration> {
        let inner = self.read();
        let scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
        let wait = inner
            .creds
            .iter()
            .filter(|c| !c.disabled)
            .filter(|c| policy.retry_limit(c) > selection.retry_round && scheduler.admits(c, policy))
            .filter_map(|c| admit(c).map(|m| (c, m)))
            .filter(|(c, m)| scheduler.retry_eligible(c, m, now))
            .map(|(c, m)| {
                let wait = scheduler.wait(c, &m, now).unwrap_or_default();
                if status == 429 && attempted.contains(&c.id) && !policy.cooling_disabled(c) {
                    wait.max(Duration::from_secs(10))
                } else {
                    wait
                }
            })
            .min()?;
        if wait > policy.max_retry_interval {
            None
        } else {
            Some(wait)
        }
    }

    fn accept_probe(&self, lease: &Lease) {
        let inner = self.read();
        // Like results: a credential edited or re-created since the pick is left alone.
        if !inner
            .creds
            .iter()
            .any(|c| c.id == lease.credential.id && c.revision == lease.credential.revision)
        {
            return;
        }
        self.scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .accept_probe_picked(&lease.credential, &lease.execution_model, lease.picked, Instant::now());
    }

    fn record(&self, lease: &Lease, outcome: &Outcome) {
        self.record_model(lease, &lease.execution_model, outcome);
    }

    fn record_model(&self, lease: &Lease, model: &str, outcome: &Outcome) {
        let slot = match outcome {
            Outcome::Success => 0,
            Outcome::Failure(_) | Outcome::Neutral(_) => 1,
            Outcome::Cancelled => 2,
        };
        self.stats[slot].fetch_add(1, Ordering::Relaxed);
        if !matches!(outcome, Outcome::Cancelled) {
            self.note_activity(&lease.credential.id, matches!(outcome, Outcome::Success));
        }
        let inner = self.read();
        // Outcomes from credentials deleted/re-created during an attempt must not
        // poison the replacement. Metadata edits likewise invalidate stale results.
        if inner
            .creds
            .iter()
            .any(|c| c.id == lease.credential.id && c.revision == lease.credential.revision)
        {
            let (now, wall) = (Instant::now(), std::time::SystemTime::now());
            let persist = self
                .cooldown_dir
                .read()
                .unwrap_or_else(PoisonError::into_inner)
                .is_some();
            let mut scheduler = self.scheduler.lock().unwrap_or_else(PoisonError::into_inner);
            let before = persist.then(|| scheduler.records(&lease.credential, now, wall));
            scheduler.record_dispatched(
                &lease.credential,
                model,
                outcome,
                &lease.policy,
                lease.picked,
                lease.seq,
                now,
            );
            scheduler.session_result(
                &lease.credential,
                &lease.selection,
                outcome,
                &lease.policy,
                lease.lcp.as_ref(),
                now,
            );
            // Go MarkResult: a 401 that cools the credential schedules a background
            // refresh of the rejected token (feb63984; the runtime checks for a refresh
            // credential). A forced cooldown counts even on a request-scoped 401.
            // ponytail: Codex only for now; other providers (Claude's included) still
            // refresh after a 401 inline only, until the post-replay port.
            let rejected = matches!(outcome, Outcome::Failure(error)
                if lease.credential.provider == "codex"
                    && crate::classify::names_unauthorized(error)
                    && lease.policy.error_action(&lease.credential, error).cooldown);
            // Go `publishErrorEvent` after MarkResult (and the availability-neutral record).
            if let (Outcome::Failure(error) | Outcome::Neutral(error), Some(queue)) = (outcome, self.error_events.get())
                && queue.wants_errors()
            {
                let records = scheduler.records(&lease.credential, now, wall);
                queue.enqueue_error(&crate::error_events::payload(&lease.credential, model, error, &records));
            }
            // Go MarkResult persists only when this credential's cooldown records changed.
            let changed = before.is_some_and(|before| before != scheduler.records(&lease.credential, now, wall));
            drop(scheduler);
            drop(inner);
            // After the store lock: a refresh commit holds this lock while it writes.
            if rejected {
                let mut state = self.unauthorized.lock().unwrap_or_else(PoisonError::into_inner);
                let revision = lease.credential.revision;
                // Go sets `NextRefreshAfter` only when none is pending.
                if state
                    .pending
                    .get(&lease.credential.id)
                    .is_none_or(|(r, _)| *r != revision)
                {
                    state.pending.insert(lease.credential.id.clone(), (revision, now));
                    self.unauthorized_noted.send_replace(());
                }
            }
            if changed {
                self.persist_cooldowns();
            }
            // Go persists on every recorded result, a client-cancelled stream included.
            self.persist_credential(&lease.credential);
        }
    }

    /// Resolves after the next change to the credential set or any credential.
    pub fn subscribe(&self) -> tokio::sync::watch::Receiver<()> {
        self.changed.subscribe()
    }

    /// Pending 401 refreshes and the last rotations. Read it before the credential
    /// snapshot it is compared with.
    pub(crate) fn unauthorized(&self) -> Rejections {
        self.unauthorized.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }

    /// Forgets a pending unauthorized refresh unless a 401 on a newer revision replaced it.
    pub(crate) fn forget_unauthorized(&self, id: &str, revision: u64) {
        let mut state = self.unauthorized.lock().unwrap_or_else(PoisonError::into_inner);
        if state.pending.get(id).is_some_and(|(r, _)| *r <= revision) {
            state.pending.remove(id);
        }
    }

    /// Drops the rejections `seen` (read before `snapshot`) whose credential the snapshot
    /// replaced or removed. A 401 recorded after `seen` is never touched.
    pub(crate) fn forget_stale_unauthorized(&self, seen: &Rejections, snapshot: &[Arc<Credential>]) {
        for (id, (revision, _)) in &seen.pending {
            if snapshot
                .iter()
                .find(|c| c.id == *id)
                .is_none_or(|c| c.revision > *revision)
            {
                self.forget_unauthorized(id, *revision);
            }
        }
        let mut state = self.unauthorized.lock().unwrap_or_else(PoisonError::into_inner);
        state
            .refreshed
            .retain(|id, _| !seen.refreshed.contains_key(id) || snapshot.iter().any(|c| c.id == *id));
    }

    /// [`Self::apply_patch`] for a token refresh that started under `fence`'s
    /// registration: refused (`NotFound`) once the credential's ID was registered again
    /// (Go's `RegistrationEpoch` check), and a plugin refresh's schedule is recorded
    /// with the commit ([`crate::plugins::refresh::committed`]). When `rotated` says the
    /// commit replaced the tokens, its time is recorded under the same lock that 401s
    /// are noted under, before any scan can see the new revision without it (Go
    /// `LastRefreshedAt`).
    pub(crate) fn apply_refresh(
        &self,
        id: &str,
        expected_revision: u64,
        fence: RefreshFence,
        patch: &MetadataPatch,
        edit: impl FnOnce(&mut Credential),
        rotated: impl FnOnce(&Credential) -> bool,
    ) -> Result<(Arc<Credential>, bool), PatchError> {
        let mut state = self.unauthorized.lock().unwrap_or_else(PoisonError::into_inner);
        let committed = self.apply_patch_with(id, expected_revision, Some(fence), patch, edit)?;
        let rotated = rotated(&committed);
        if rotated {
            state
                .refreshed
                .insert(id.to_owned(), (committed.revision, Instant::now()));
        }
        Ok((committed, rotated))
    }

    /// Go `updateInternal` for a Codex refresh of `original`, run while the caller holds
    /// the file's credential lock. Refused (`NotFound`) once the ID was registered again since
    /// `registered`. When the credential version moved or the credentials changed since
    /// `original` and no refreshed partition still holds a version `patch` may be applied
    /// over (Go `CanApplyTo`), the refresh is discarded with no side effect. Otherwise
    /// `patch` is applied to the file as it is now, written with legacy keys renamed (Go
    /// `PersistCodexAuthFile`), and that document published as the credential's
    /// metadata, with its proxy, its time is recorded as [`Self::apply_refresh`] records it,
    /// and new tokens clear unauthorized cooldowns. Blocking.
    fn admit_codex_refresh(
        &self,
        original: &Credential,
        registered: crate::plugins::refresh::Registered,
        patch: &cpa_exec::codex_refresh::RefreshPatch,
    ) -> Result<CodexAdmission, PatchError> {
        let id = original.id.as_str();
        let committed = {
            let mut state = self.unauthorized.lock().unwrap_or_else(PoisonError::into_inner);
            let committed = loop {
                let revision = self.get(id).ok_or(PatchError::NotFound)?.revision;
                let mut discarded = None;
                // The registration and version are checked here, not by the writer: a
                // moved version is a discard decision, not an edit to retry on. The
                // writer's gate holds off registrations, its lock this credential's writes.
                let admitted = self.write_unlocked(
                    id,
                    revision,
                    None,
                    false,
                    |current| {
                        let now = self.registered(id);
                        if now.registration != registered.registration {
                            return Err(PatchError::NotFound);
                        }
                        let moved = now.credential_version != registered.credential_version;
                        if (moved || credentials_changed(original, current)) && !patch.can_apply_to(&current.metadata) {
                            discarded = Some(current.clone());
                            return Ok(None);
                        }
                        let Source::File(path) = &current.source else {
                            return Err(PatchError::ConfigBacked);
                        };
                        let (out, written) = save_codex_refresh(path, current, patch);
                        let Ok(Value::Object(metadata)) = serde_json::from_slice::<Value>(&out) else {
                            unreachable!("Go's encoding of a JSON object");
                        };
                        let mut next = Credential::clone(current);
                        next.metadata = metadata;
                        next.refresh_derived();
                        publish_metadata_proxy(&mut next);
                        Ok(Some((None, out, (next, written))))
                    },
                    |inner, index, bytes, (mut next, written)| {
                        inner.generation += 1;
                        next.revision = inner.generation;
                        // The file holds Go's encoding of its own float64 reading; after a
                        // failed save it holds something else.
                        if written {
                            self.note_provenance(&next.id, next.revision, sha256(bytes), None);
                        } else {
                            self.provenance
                                .lock()
                                .unwrap_or_else(PoisonError::into_inner)
                                .remove(&next.id);
                        }
                        let next = Arc::new(next);
                        self.register(
                            std::slice::from_ref(&inner.creds[index]),
                            std::slice::from_ref(&next),
                            &[],
                        );
                        inner.creds[index] = next;
                        inner.epoch += 1;
                        self.changed.send_replace(());
                        inner.creds[index].clone()
                    },
                );
                match admitted {
                    // Edited in memory meanwhile: decide again on the edit.
                    Err(PatchError::Stale { .. }) => continue,
                    Ok(None) => {
                        let current = discarded.expect("only a discard writes nothing");
                        return Ok(CodexAdmission::Discarded(current));
                    }
                    other => break other?.expect("checked above"),
                }
            };
            if credentials_changed(original, &committed) {
                state
                    .refreshed
                    .insert(id.to_owned(), (committed.revision, Instant::now()));
            }
            committed
        };
        if credentials_changed(original, &committed) {
            self.recover_unauthorized(id);
        }
        Ok(CodexAdmission::Committed(committed))
    }

    /// Changes whenever a 401 schedules a background refresh.
    pub(crate) fn subscribe_unauthorized(&self) -> tokio::sync::watch::Receiver<()> {
        self.unauthorized_noted.subscribe()
    }

    /// Changes whenever the credential set or any credential changes.
    pub fn epoch(&self) -> u64 {
        self.read().epoch
    }

    /// Attempts finished so far, by outcome.
    pub fn stats(&self) -> AttemptStats {
        let get = |i: usize| self.stats[i].load(Ordering::Relaxed);
        AttemptStats {
            success: get(0),
            failure: get(1),
            cancelled: get(2),
        }
    }

    /// Serializes preparation of one credential across concurrent requests.
    pub fn prepare_lock(&self, id: &str) -> Arc<tokio::sync::Mutex<()>> {
        let mut locks = self.prepare_locks.lock().unwrap_or_else(PoisonError::into_inner);
        locks.entry(id.to_owned()).or_default().clone()
    }

    /// Applies a metadata change if the credential is still at `expected_revision`.
    /// File-backed credentials are written atomically (0600) before memory changes.
    /// Blocking: call from `spawn_blocking` in async code.
    pub fn apply_patch(
        &self,
        id: &str,
        expected_revision: u64,
        patch: &MetadataPatch,
    ) -> Result<Arc<Credential>, PatchError> {
        self.apply_patch_with(id, expected_revision, None, patch, |_| {})
    }

    /// [`Self::apply_patch`], with `edit` applied to the credential before it is
    /// published (fields outside the document, such as a plugin refresh's proxy URL),
    /// and a token refresh's `fence` ([`Self::apply_refresh`]).
    fn apply_patch_with(
        &self,
        id: &str,
        expected_revision: u64,
        fence: Option<RefreshFence>,
        patch: &MetadataPatch,
        edit: impl FnOnce(&mut Credential),
    ) -> Result<Arc<Credential>, PatchError> {
        let committed = self.write_unlocked(
            id,
            expected_revision,
            fence.map(|f| f.registered),
            false,
            |current| {
                if patch.remove.iter().any(|k| k == "type")
                    || patch
                        .set
                        .get("type")
                        .is_some_and(|t| t.as_str() != Some(current.provider.as_str()))
                {
                    return Err(PatchError::TypeIsImmutable);
                }
                let Source::File(path) = &current.source else {
                    return Err(PatchError::ConfigBacked);
                };
                let mut next = Credential::clone(current);
                patch.apply(&mut next.metadata);
                next.refresh_derived();
                edit(&mut next);
                // Go `FileTokenStore.Save` always records the disabled state.
                next.metadata.insert("disabled".into(), Value::Bool(next.disabled));
                // Go's `json.NewEncoder(f).Encode`: compact JSON and a newline.
                let mut bytes = serde_json::to_vec(&next.metadata).map_err(|e| PatchError::Io(e.to_string()))?;
                bytes.push(b'\n');
                let basis = self.patched_doc(current, path, patch, next.disabled);
                Ok(Some((Some(path.clone()), bytes, (next, basis))))
            },
            |inner, index, bytes, (mut next, basis)| {
                inner.generation += 1;
                next.revision = inner.generation;
                // The written bytes are serde's, not Go's: a later management save takes
                // its numbers from `doc`, Go's metadata after the refresh, or refuses.
                match basis {
                    Some((doc, loaded)) => {
                        let provenance = Provenance {
                            revision: next.revision,
                            sha256: sha256(bytes),
                            doc: Some(Arc::new(doc)),
                            loaded,
                        };
                        self.provenance
                            .lock()
                            .unwrap_or_else(PoisonError::into_inner)
                            .insert(next.id.clone(), provenance);
                    }
                    None => {
                        self.provenance
                            .lock()
                            .unwrap_or_else(PoisonError::into_inner)
                            .remove(&next.id);
                    }
                }
                let next = Arc::new(next);
                self.register(
                    std::slice::from_ref(&inner.creds[index]),
                    std::slice::from_ref(&next),
                    &[],
                );
                // Go publishes `LastRefreshedAt` with the refreshed auth (`MergeRefreshedAuth`
                // under `m.mu`), so a registration after this commit replaces it. The
                // writer checked the refresh's registration under the gate. Lock order:
                // `inner`, then the schedules, as in `register`.
                if fence.is_some_and(|f| f.plugin) {
                    crate::plugins::refresh::record(&self.refresh_schedules, &next, |c, s| {
                        crate::plugins::refresh::committed(c, s, chrono::Utc::now())
                    });
                }
                inner.creds[index] = next;
                inner.epoch += 1;
                self.changed.send_replace(());
                inner.creds[index].clone()
            },
        )?;
        Ok(committed.expect("apply_patch always writes"))
    }

    /// Go 8a01bc02 (`persistLocked`): writes a file-backed credential with `inner`
    /// unlocked, so a slow disk never stalls selection or reads of other credentials.
    /// `prepare` sees the credential at `expected_revision` (`Stale` otherwise) and
    /// returns the file to write (`None` to write nothing) and the bytes, or `None` for
    /// nothing to do; `publish` then
    /// puts the result in place under the write lock. The credential's write lock and
    /// the reload gate (shared) are held throughout, so neither another write of it nor
    /// a set replacement can land between the write and its publication. A publication
    /// that touches another credential (an identity change) passes `exclusive` and holds
    /// the gate exclusively instead, so no write of any credential is in flight. A token
    /// refresh passes what it started under: it is refused (`NotFound`) once the
    /// credential's ID was registered again, before anything is merged, and meets a
    /// credential version moved since as an edit (`Stale`).
    fn write_unlocked<T, R>(
        &self,
        id: &str,
        expected_revision: u64,
        registered: Option<crate::plugins::refresh::Registered>,
        exclusive: bool,
        prepare: impl FnOnce(&Arc<Credential>) -> Result<Option<(Option<std::path::PathBuf>, Vec<u8>, T)>, PatchError>,
        publish: impl FnOnce(&mut Inner, usize, &[u8], T) -> R,
    ) -> Result<Option<R>, PatchError> {
        // Acquired once, before the check and the write: re-taking the gate while holding
        // it can deadlock behind a waiting reload.
        let lock = (!exclusive).then(|| {
            let mut locks = self.write_locks.lock().unwrap_or_else(PoisonError::into_inner);
            locks.entry(id.to_owned()).or_default().clone()
        });
        let _gate = if exclusive {
            (None, Some(self.reload.write().unwrap_or_else(PoisonError::into_inner)))
        } else {
            (Some(self.reload.read().unwrap_or_else(PoisonError::into_inner)), None)
        };
        let _own = lock.as_ref().map(|l| l.lock().unwrap_or_else(PoisonError::into_inner));
        let current = self
            .read()
            .creds
            .iter()
            .find(|c| c.id == id)
            .cloned()
            .ok_or(PatchError::NotFound)?;
        // Go `updateInternal`: "stale registration epoch" for a refresh, ahead of the
        // revision check. The gate holds off every set replacement.
        if let Some(registered) = registered {
            let now = self.registered(id);
            if now.registration != registered.registration {
                return Err(PatchError::NotFound);
            }
            if now.credential_version != registered.credential_version {
                return Err(PatchError::Stale {
                    current: current.revision,
                });
            }
        }
        if current.revision != expected_revision {
            return Err(PatchError::Stale {
                current: current.revision,
            });
        }
        let Some((path, bytes, value)) = prepare(&current)? else {
            return Ok(None);
        };
        // Go `Manager.persist` never writes a plugin-virtual credential (one of several a
        // plugin parsed from one file): its document is not the file's. A refresh or
        // patch of one is kept in memory.
        if let Some(path) = path.filter(|_| !marked(&current, "plugin_virtual")) {
            write_bytes_atomic(&path, &bytes).map_err(|e| PatchError::Io(e.to_string()))?;
        }
        let mut inner = self.inner.write().unwrap_or_else(PoisonError::into_inner);
        // Every other change to this credential waits on the locks held here.
        let index = inner
            .creds
            .iter()
            .position(|c| c.id == id && c.revision == expected_revision)
            .ok_or(PatchError::NotFound)?;
        Ok(Some(publish(&mut inner, index, &bytes, value)))
    }

    /// Replaces a config-backed or runtime-only credential in memory if it is still at
    /// `expected_revision`: Go's `Manager.Update` never persists config API keys (the
    /// next config publish re-synthesizes them) or `runtime_only` auths. `NotFound`
    /// unless `next.id` names such a credential.
    pub fn replace_config_backed(
        &self,
        next: Credential,
        expected_revision: u64,
    ) -> Result<Arc<Credential>, PatchError> {
        let mut inner = self.inner.write().unwrap_or_else(PoisonError::into_inner);
        let generation = inner.generation + 1;
        let slot = inner
            .creds
            .iter_mut()
            .find(|c| c.id == next.id && matches!(c.source, Source::Config { .. } | Source::Runtime))
            .ok_or(PatchError::NotFound)?;
        if slot.revision != expected_revision {
            return Err(PatchError::Stale { current: slot.revision });
        }
        let mut next = next;
        next.source = slot.source.clone();
        next.revision = generation;
        let next = Arc::new(next);
        self.register(std::slice::from_ref(slot), std::slice::from_ref(&next), &[]);
        let cleared = self.clear_replaced_unauthorized(std::slice::from_ref(slot), std::slice::from_ref(&next));
        *slot = next;
        let committed = slot.clone();
        inner.generation = generation;
        // Registrations depend on the credential (prefix, models): invalidate the
        // registry cache like `apply_patch` does.
        inner.epoch += 1;
        self.changed.send_replace(());
        drop(inner);
        if cleared {
            self.persist_cooldowns();
        }
        // Go `Manager.Update` clears the cooldowns of an auth it stores disabled (or
        // with cooling off), so a later re-enable routes to it at once.
        self.clear_disabled_cooldowns();
        Ok(committed)
    }

    /// Go `Manager.Modify` for an auth file: while `id` is still at `expected_revision`,
    /// writes `bytes` to its file and puts `next` (the credential re-synthesized from
    /// those bytes, possibly under a new provider or ID; `None` drops it) in its place.
    /// One write lock covers the check, the file and the swap, so a concurrent token
    /// refresh ([`Self::apply_patch`]) lands either before (`Stale`) or after, never
    /// under it, and nothing else in the set is re-read or replaced.
    pub fn replace_file_backed(
        &self,
        id: &str,
        expected_revision: u64,
        bytes: &[u8],
        next: Option<Credential>,
    ) -> Result<(), PatchError> {
        let commit = Commit {
            bytes: bytes.to_vec(),
            write: true,
            disk: None,
            doc: None,
        };
        self.commit_file_backed(id, expected_revision, commit, next)
    }

    /// [`Self::replace_file_backed`] for a management save ([`Commit`]): the file check
    /// and the optional write run under the same lock and revision check, and the new
    /// revision records the save's [`Provenance`].
    pub fn commit_file_backed(
        &self,
        id: &str,
        expected_revision: u64,
        commit: Commit,
        next: Option<Credential>,
    ) -> Result<(), PatchError> {
        let Commit {
            bytes,
            write,
            disk,
            doc,
        } = commit;
        // A new ID can replace another credential, whose own write lock is not held here.
        let exclusive = next.as_ref().is_some_and(|n| n.id != id);
        let removed = self.write_unlocked(
            id,
            expected_revision,
            None,
            exclusive,
            |current| {
                let Source::File(path) = &current.source else {
                    return Err(PatchError::ConfigBacked);
                };
                if let Some(want) = disk {
                    let now = std::fs::read(path).ok().map(|b| sha256(&b));
                    if now != want {
                        return Err(PatchError::Stale {
                            current: current.revision,
                        });
                    }
                }
                // The file's hash after the commit.
                let held = if write { Some(sha256(&bytes)) } else { disk.flatten() };
                Ok(Some((write.then(|| path.clone()), bytes, (next, held))))
            },
            |inner, index, _, (next, held)| {
                let before = inner.creds.clone();
                let previous = inner.creds.remove(index);
                self.provenance
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .remove(&previous.id);
                if let Some(mut next) = next {
                    inner.generation += 1;
                    next.revision = inner.generation;
                    if let Some(held) = held {
                        self.note_provenance(&next.id, next.revision, held, doc);
                    }
                    inner.creds.retain(|c| c.id != next.id);
                    let at = index.min(inner.creds.len());
                    inner.creds.insert(at, Arc::new(next));
                }
                self.register(&before, &inner.creds, &[]);
                self.clear_replaced_unauthorized(&before, &inner.creds);
                inner.epoch += 1;
                self.changed.send_replace(());
                self.scheduler
                    .lock()
                    .unwrap_or_else(PoisonError::into_inner)
                    .reconcile(&inner.creds);
                removed_ids(&[previous], &inner.creds)
            },
        )?;
        self.close_sessions(removed.unwrap_or_default());
        self.clear_disabled_cooldowns();
        self.persist_cooldowns();
        Ok(())
    }

    /// Go's metadata after `patch` (a token refresh) lands on `current`: Go's refresh
    /// changes only the patched keys of the auth it holds. From a save, that is the saved
    /// document with the patched values as Go holds them; from a load, the loaded text
    /// (while `path` still holds it) with the patched values as written, `true`. `None`
    /// when neither is known.
    fn patched_doc(
        &self,
        current: &Credential,
        path: &std::path::Path,
        patch: &MetadataPatch,
        disabled: bool,
    ) -> Option<(cpa_common::json::GoValue, bool)> {
        use cpa_common::json::GoValue;
        let prior = self
            .provenance(&current.id)
            .filter(|p| p.revision == current.revision)?;
        let (base, loaded) = match prior.doc {
            Some(doc) => (GoValue::clone(&doc), prior.loaded),
            None => {
                let bytes = std::fs::read(path).ok().filter(|b| sha256(b) == prior.sha256)?;
                (GoValue::parse(&bytes)?, true)
            }
        };
        let mut doc = base.into_object().ok()?;
        for key in &patch.remove {
            doc.remove(key);
        }
        for (key, value) in &patch.set {
            doc.insert(key.clone(), go_typed(value, loaded));
        }
        doc.insert("disabled".into(), GoValue::Bool(disabled));
        Some((GoValue::Object(doc), loaded))
    }

    /// The [`Provenance`] of credential `id`, if one is known.
    pub fn provenance(&self, id: &str) -> Option<Provenance> {
        self.provenance
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(id)
            .cloned()
    }

    fn note_provenance(&self, id: &str, revision: u64, sha256: [u8; 32], doc: Option<Arc<cpa_common::json::GoValue>>) {
        self.provenance.lock().unwrap_or_else(PoisonError::into_inner).insert(
            id.to_owned(),
            Provenance {
                revision,
                sha256,
                doc,
                loaded: false,
            },
        );
    }

    /// Records that the current file credentials were loaded from the bytes `read`
    /// hashed (an auth-folder scan's [`AuthScan::read`]). A credential whose recorded
    /// save already holds those bytes at its revision keeps that save's document.
    ///
    /// [`AuthScan::read`]: cpa_core::config::credentials::AuthScan
    pub fn note_loaded(&self, read: &std::collections::BTreeMap<std::path::PathBuf, [u8; 32]>) {
        let creds = self.snapshot();
        let mut provenance = self.provenance.lock().unwrap_or_else(PoisonError::into_inner);
        provenance.retain(|id, _| creds.iter().any(|c| c.id == *id));
        for c in creds.iter() {
            let Source::File(path) = &c.source else { continue };
            let Some(&hash) = read.get(path) else { continue };
            let same = provenance
                .get(&c.id)
                .is_some_and(|p| p.revision == c.revision && p.sha256 == hash);
            if !same {
                provenance.insert(
                    c.id.clone(),
                    Provenance {
                        revision: c.revision,
                        sha256: hash,
                        doc: None,
                        loaded: false,
                    },
                );
            }
        }
    }

    /// Go `Service.removeAuth` (1e37b52b): a credential that left the set ends only the
    /// upstream WebSocket sessions it serves. Runs with the set's locks released.
    fn close_sessions(&self, removed: Vec<String>) {
        if let Some(close) = self.session_closer.get() {
            for id in removed {
                close(&id);
            }
        }
    }

    /// Replaces the credential set (watcher reload, management import/delete). Unchanged
    /// credentials keep their revision; new and changed ones get fresh revisions.
    pub fn reconcile(&self, credentials: Vec<Credential>) {
        self.reconcile_scanned(credentials, &std::collections::BTreeMap::new());
    }

    /// [`Self::reconcile`] for an auth-folder scan; `read` has the SHA-256 of the bytes
    /// each file credential was built from. Go c4c1d43e: a scanned credential that would
    /// replace the current one is applied only while its file still holds those bytes.
    /// Otherwise a write committed after the scan read the file (a token refresh, an
    /// edit) has changed it, and the current credential is kept: the stale snapshot
    /// would undo that write, and the watcher reloads the file it sees changed. A file
    /// that is gone or unreadable keeps the current credential too. The check runs
    /// under the exclusive reload gate, so no write lands between it and the swap, but
    /// before `inner` is taken, so its file reads never stall readers. Returns the files
    /// whose scanned credential was rejected.
    pub fn reconcile_scanned(
        &self,
        credentials: Vec<Credential>,
        read: &std::collections::BTreeMap<std::path::PathBuf, [u8; 32]>,
    ) -> Vec<std::path::PathBuf> {
        self.reconcile_scanned_with(credentials, read, |_, _| {})
    }

    /// [`Self::reconcile_scanned`]; `keep` first adds to the set from the current
    /// credentials, under the gate, so no write lands between what it reads and the swap.
    pub fn reconcile_scanned_with(
        &self,
        credentials: Vec<Credential>,
        read: &std::collections::BTreeMap<std::path::PathBuf, [u8; 32]>,
        keep: impl FnOnce(&[Arc<Credential>], &mut Vec<Credential>),
    ) -> Vec<std::path::PathBuf> {
        use sha2::{Digest, Sha256};
        let reload = self.reload.write().unwrap_or_else(PoisonError::into_inner);
        let mut credentials = credentials;
        keep(&self.snapshot(), &mut credentials);
        // A credential this scan synthesized has no revision yet; one kept for an
        // incomplete or deferred file is the store's own record, not built from `read`.
        let built: std::collections::HashSet<std::path::PathBuf> = credentials
            .iter()
            .filter(|c| c.revision == 0)
            .filter_map(|c| match &c.source {
                Source::File(path) => Some(path.clone()),
                _ => None,
            })
            .collect();
        let mut rejected = Vec::new();
        if !read.is_empty() {
            let current = self.snapshot();
            let by_id: HashMap<&str, &Arc<Credential>> = current.iter().map(|c| (c.id.as_str(), c)).collect();
            for cred in &mut credentials {
                let Source::File(path) = &cred.source else { continue };
                let Some(seen) = read.get(path) else { continue };
                let Some(&existing) = by_id.get(cred.id.as_str()) else {
                    continue;
                };
                if unchanged(existing, cred) {
                    continue;
                }
                // The scan's own rule: a FIFO or device in the file's place is never read
                // (it could block or never end) and counts as a changed file.
                let on_disk: Option<[u8; 32]> = cpa_core::config::credentials::read_regular(path)
                    .filter(|data| !data.is_empty())
                    .map(|data| Sha256::digest(&data).into());
                if on_disk.as_ref() != Some(seen) {
                    rejected.push(path.clone());
                    *cred = Credential::clone(existing);
                }
            }
        }
        let mut guard = self.inner.write().unwrap_or_else(PoisonError::into_inner);
        let inner = &mut *guard;
        let mut next = Vec::with_capacity(credentials.len());
        let mut by_id = HashMap::with_capacity(inner.creds.len());
        for c in &inner.creds {
            by_id.entry(c.id.as_str()).or_insert(c);
        }
        // A credential the startup load registered provisionally is registered again
        // when the first plugin-aware load parses another `NextRefreshAfter` for it,
        // whatever else it equals: Go's first load registers it with that one.
        let provisional = crate::plugins::refresh::provisional(&self.refresh_schedules);
        for mut cred in credentials {
            let same = |c: &Credential| {
                unchanged(c, &cred)
                    && !(provisional.contains(c.id.as_str()) && c.next_refresh_after != cred.next_refresh_after)
            };
            match by_id.get(cred.id.as_str()).filter(|c| same(c)) {
                Some(&existing) => next.push(existing.clone()),
                None => {
                    inner.generation += 1;
                    cred.revision = inner.generation;
                    next.push(Arc::new(cred));
                }
            }
        }
        // Runtime-only credentials (relay sessions) have no file or config entry; they
        // stay until their session ends.
        let runtime: Vec<_> = inner
            .creds
            .iter()
            .filter(|c| c.source == Source::Runtime && !next.iter().any(|n| n.id == c.id))
            .cloned()
            .collect();
        next.extend(runtime);
        let removed = removed_ids(&inner.creds, &next);
        self.register(&inner.creds, &next, &[]);
        self.clear_replaced_unauthorized(&inner.creds, &next);
        inner.creds = next;
        inner.epoch += 1;
        self.changed.send_replace(());
        self.scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .reconcile(&inner.creds);
        drop(guard);
        // Under the gate still: no save lands between the scan's publication and this.
        let mut loaded = read.clone();
        loaded.retain(|path, _| built.contains(path) && !rejected.contains(path));
        self.note_loaded(&loaded);
        drop(reload);
        self.close_sessions(removed);
        self.clear_disabled_cooldowns();
        self.persist_cooldowns();
        rejected
    }

    /// Replaces the config-sourced credentials (Home config API keys, Go
    /// `registerConfigAPIKeyAuths`) under a single write lock and keeps every other
    /// current entry, so a concurrent [`Self::upsert`] or relay session change is never
    /// undone the way a snapshot followed by [`Self::reconcile`] could undo it. An
    /// unchanged key keeps its revision, as in `reconcile`.
    pub fn replace_config(&self, keys: Vec<Credential>) {
        let reload = self.reload.write().unwrap_or_else(PoisonError::into_inner);
        let mut inner = self.inner.write().unwrap_or_else(PoisonError::into_inner);
        let mut next: Vec<_> = inner
            .creds
            .iter()
            .filter(|c| !matches!(c.source, Source::Config { .. }))
            .cloned()
            .collect();
        for mut key in keys {
            match inner
                .creds
                .iter()
                .find(|c| c.id == key.id && unchanged(c, &key))
                .cloned()
            {
                Some(existing) => next.push(existing),
                None => {
                    inner.generation += 1;
                    key.revision = inner.generation;
                    next.push(Arc::new(key));
                }
            }
        }
        let removed = removed_ids(&inner.creds, &next);
        self.register(&inner.creds, &next, &[]);
        self.clear_replaced_unauthorized(&inner.creds, &next);
        inner.creds = next;
        inner.epoch += 1;
        self.changed.send_replace(());
        self.scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .reconcile(&inner.creds);
        drop(inner);
        drop(reload);
        self.close_sessions(removed);
        self.clear_disabled_cooldowns();
        self.persist_cooldowns();
    }

    /// Inserts or replaces one credential (a plugin's `host.auth.save`) under a single
    /// write lock, so a concurrent `apply_patch` on another credential is never undone
    /// the way a snapshot followed by [`Self::reconcile`] could undo it. An unchanged
    /// credential keeps its revision, as in `reconcile`.
    pub fn upsert(&self, credential: Credential) {
        self.upsert_file(None, vec![credential], &[]);
    }

    /// [`Self::upsert`] for every credential an auth file saved at `path` holds (Go
    /// `upsertAuthRecordsForPath`): the file's other credentials, parsed from it
    /// earlier, go, runtime-only ones excepted. `saved` has the refresh schedules a
    /// plugin's save registers its credentials with.
    pub fn upsert_file(
        &self,
        path: Option<&std::path::Path>,
        credentials: Vec<Credential>,
        saved: &[cpa_plugin::hostauth::SavedRefresh],
    ) {
        let reload = self.reload.write().unwrap_or_else(PoisonError::into_inner);
        let mut inner = self.inner.write().unwrap_or_else(PoisonError::into_inner);
        let before = inner.creds.clone();
        let mut changed = false;
        let mut removed = Vec::new();
        if let Some(path) = path {
            let clean = cpa_core::config::credentials::absolute_clean_path;
            let target = clean(path);
            let before = std::mem::take(&mut inner.creds);
            for credential in before {
                let stale = !marked(&credential, "runtime_only")
                    && !credentials.iter().any(|c| c.id == credential.id)
                    && matches!(&credential.source, Source::File(p) if clean(p) == target);
                if stale {
                    removed.push(credential.id.clone());
                } else {
                    inner.creds.push(credential);
                }
            }
            changed = !removed.is_empty();
        }
        for mut credential in credentials {
            let slot = inner.creds.iter().position(|c| c.id == credential.id);
            if slot.is_some_and(|i| unchanged(&inner.creds[i], &credential)) {
                continue;
            }
            inner.generation += 1;
            credential.revision = inner.generation;
            let credential = Arc::new(credential);
            match slot {
                Some(i) => inner.creds[i] = credential,
                None => inner.creds.push(credential),
            }
            changed = true;
        }
        if !changed {
            return;
        }
        self.register(&before, &inner.creds, saved);
        self.clear_replaced_unauthorized(&before, &inner.creds);
        inner.epoch += 1;
        self.changed.send_replace(());
        self.scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .reconcile(&inner.creds);
        drop(inner);
        drop(reload);
        self.close_sessions(removed);
        self.clear_disabled_cooldowns();
        self.persist_cooldowns();
    }

    /// Adds a runtime-only credential (Go's auth add for a `/v1/ws` relay session)
    /// unless one with its ID is already active. Additive API for the relay route.
    pub fn add_runtime(&self, mut credential: Credential) -> bool {
        let mut inner = self.inner.write().unwrap_or_else(PoisonError::into_inner);
        if inner.creds.iter().any(|c| c.id == credential.id && !c.disabled) {
            return false;
        }
        let before = inner.creds.clone();
        inner.creds.retain(|c| c.id != credential.id);
        inner.generation += 1;
        credential.revision = inner.generation;
        inner.creds.push(Arc::new(credential));
        self.register(&before, &inner.creds, &[]);
        inner.epoch += 1;
        self.changed.send_replace(());
        self.scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .reconcile(&inner.creds);
        true
    }

    /// Removes a credential when its relay session ends (Go's auth delete). Additive
    /// API for the relay route.
    pub fn remove_runtime(&self, id: &str) {
        let mut inner = self.inner.write().unwrap_or_else(PoisonError::into_inner);
        let before = inner.creds.clone();
        inner.creds.retain(|c| !(c.id == id && c.source == Source::Runtime));
        if inner.creds.len() == before.len() {
            return;
        }
        self.register(&before, &inner.creds, &[]);
        inner.epoch += 1;
        self.changed.send_replace(());
        self.scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .reconcile(&inner.creds);
    }

    fn read(&self) -> std::sync::RwLockReadGuard<'_, Inner> {
        self.inner.read().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Per-credential outcome counters for management views (Go `Auth.Success`/`Failed`
/// and its 20 x 10-minute recent-request ring). Additive read API.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CredentialActivity {
    pub success: u64,
    pub failed: u64,
    /// `(bucket, success, failed)` for the most recent buckets, where `bucket` is
    /// Unix seconds / 600; at most 20 entries, oldest first.
    pub recent: Vec<(i64, u64, u64)>,
}

pub const RECENT_BUCKET_SECONDS: i64 = 600;
const RECENT_BUCKETS: usize = 20;

impl CredentialStore {
    fn note_activity(&self, id: &str, success: bool) {
        let bucket = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs() as i64 / RECENT_BUCKET_SECONDS);
        let mut all = self.activity.lock().unwrap_or_else(PoisonError::into_inner);
        let entry = all.entry(id.to_owned()).or_default();
        if success {
            entry.success += 1;
        } else {
            entry.failed += 1;
        }
        match entry.recent.last_mut() {
            Some(last) if last.0 == bucket => {
                if success {
                    last.1 += 1;
                } else {
                    last.2 += 1;
                }
            }
            _ => entry.recent.push((bucket, u64::from(success), u64::from(!success))),
        }
        entry.recent.retain(|(b, _, _)| bucket - b < RECENT_BUCKETS as i64);
    }

    /// Counters for one credential; zero when it has served nothing yet.
    pub fn activity(&self, id: &str) -> CredentialActivity {
        self.activity
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(id)
            .cloned()
            .unwrap_or_default()
    }

    /// Active cooldowns of one credential.
    pub fn cooldowns(&self, id: &str) -> Vec<crate::scheduler::CooldownState> {
        self.scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .cooldowns_of(id, Instant::now())
    }

    /// Clears the cooldowns of one credential (Go `Manager.ResetQuota`); returns the
    /// model keys that were cooling.
    pub fn reset_cooldowns(&self, id: &str) -> Vec<String> {
        let had = !self.cooldowns(id).is_empty();
        let models = self
            .scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .reset_cooldowns(id);
        if had {
            // Go `ResetQuota` persists the cleared state.
            self.persist_cooldowns();
        }
        models
    }

    /// The recovery Go runs after a token refresh and after `BindCodexSIWC` saves a
    /// binding: an enabled credential's unauthorized cooldowns are cleared and persisted,
    /// live quota blocks stay. Go also forgets the rejected access token; here a pending
    /// unauthorized refresh keys on the revision, which the new tokens replaced.
    pub fn recover_unauthorized(&self, id: &str) {
        if self.get(id).is_none_or(|c| c.disabled) {
            return;
        }
        let cleared = self
            .scheduler
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clear_unauthorized(id, Instant::now());
        if cleared {
            self.persist_cooldowns();
        }
    }
}

impl Runtime {
    /// Runs the executor's single-flighted preparation now, due or not (management
    /// refresh, Go `RefreshAuthFile`). Returns the committed credential.
    pub async fn refresh_credential(&self, id: &str) -> Result<Arc<Credential>, ExecError> {
        let cfg = self.config();
        let revision = self.store.get(id).map(|c| c.revision);
        self.prepare_credential_with(id, &cfg, revision, true).await
    }
}

/// Commits a token refresh of credential `id` that started from `current` under
/// `fence`'s registration: `patch` is what the refresh changed, merged with any edit
/// committed since (Go `UpdateRefreshedAuth`). Blocking.
pub(crate) fn commit_refresh(
    store: &CredentialStore,
    id: &str,
    current: &Credential,
    mut fence: RefreshFence,
    patch: &MetadataPatch,
    publish_proxy: impl Fn(&mut Credential) + Copy,
) -> Result<Arc<Credential>, PatchError> {
    let mut revision = current.revision;
    let mut attempt = patch.clone();
    loop {
        match store.apply_refresh(id, revision, fence, &attempt, publish_proxy, |c| {
            credentials_changed(current, c)
        }) {
            // Edited since the snapshot (the prepare lock does not hold off other writers),
            // within the refresh's registration: the writer refuses a re-registered ID
            // first (Go "stale registration epoch"), on every retry. Go 935aa6e3: an edit
            // that changed the credentials wins and this refresh is dropped; any other edit
            // is merged with it (Go `MergeRefreshedAuth`), so a rotated refresh token is
            // not lost. Credentials changed and put back since (A→B→A) count as changed:
            // the credential version moved (Go `CredentialVersion`).
            Err(PatchError::Stale { .. }) => {
                #[cfg(test)]
                if let Some(hook) = tests::AFTER_STALE.with(std::cell::Cell::take) {
                    hook();
                }
                // The writer's check, before anything here returns: an ID registered
                // again since then fails as Go's "stale registration epoch" does,
                // whatever its credentials.
                let (latest, now) = store.get_registered(id).ok_or(PatchError::NotFound)?;
                if now.registration != fence.registered.registration {
                    return Err(PatchError::NotFound);
                }
                let (rebased, partition_applies) =
                    rebase_patch(&current.provider, &current.metadata, &latest.metadata, patch);
                // Go 7b0319fb: a Codex token partition the refresh still matches
                // applies even when the other partition changed meanwhile
                // (`CredentialRefreshPatch.CanApplyTo`).
                let moved = now.credential_version != fence.registered.credential_version;
                if (moved || credentials_changed(current, &latest)) && !partition_applies {
                    return Ok(latest);
                }
                // Merged into `latest` from here, at its credential version.
                fence.registered = now;
                attempt = rebased;
                revision = latest.revision;
                if attempt.set.is_empty() && attempt.remove.is_empty() {
                    // Nothing left to write, but the refresh happened (Go records
                    // `LastRefreshedAt` whatever the merge changes), recorded while the
                    // credential is still `latest` under the refresh's registration. An
                    // edit since goes round again: its newer revision fails the writer's
                    // check, as revisions are never reused, so the empty patch is never
                    // written.
                    let at = (revision, fence.registered.credential_version);
                    match store.record_refresh(id, fence.registered.registration, Some(at), |c, s| {
                        if fence.plugin {
                            crate::plugins::refresh::committed(c, s, chrono::Utc::now());
                        }
                    }) {
                        Err(PatchError::Stale { .. }) => continue,
                        recorded => return recorded,
                    }
                }
            }
            other => {
                let (committed, rotated) = other?;
                // Go `updateInternal` after a refresh: new tokens clear the credential's
                // unauthorized cooldowns, keeping live quota blocks (50d5fe18). Here, so a
                // cancelled caller still does.
                if rotated {
                    store.recover_unauthorized(id);
                }
                return Ok(committed);
            }
        }
    }
}

/// Go `mergeAuthContent` for a prepare patch computed from `base` (the snapshot) that
/// lost the race to another edit, `user` being the stored metadata now: the part of
/// `patch` to apply on top of `user`. A value the patch did not change keeps the edit;
/// a value both changed keeps the edit unless it is a token payload. A missing key is
/// not JSON null. Codex outer tokens move as one partition (Go `CredentialRefreshPatch`).
/// The Sign in with ChatGPT partition (`siwc`) moves the same way, inside its map. The
/// flag reports whether a refreshed Codex partition still matches the stored version.
// ponytail: no prepare patch sets `proxy_url` or `use_siwc`, so Go's dedicated merges for
// those keys are not ported; add them with the first producer.
fn rebase_patch(
    provider: &str,
    base: &Map<String, Value>,
    user: &Map<String, Value>,
    patch: &MetadataPatch,
) -> (MetadataPatch, bool) {
    // Go `codexOuterCredentialKeys` (internal/auth/codex/token.go).
    const CODEX_OUTER: [&str; 8] = [
        "id_token",
        "access_token",
        "refresh_token",
        "account_id",
        "last_refresh",
        "email",
        "expired",
        "plan_type",
    ];
    // Go `IsAuthTokenPayloadKey`.
    let token_payload = |k: &str| {
        matches!(
            k.trim().to_ascii_lowercase().as_str(),
            "access_token"
                | "refresh_token"
                | "id_token"
                | "session_id"
                | "expired"
                | "last_refresh"
                | "expires_in"
                | "timestamp"
                | "token_type"
                | "user_code"
                | "verification_uri"
                | "verification_uri_complete"
        )
    };
    let codex = provider == "codex";
    let kept_by_user = |k: &str| base.get(k) == user.get(k);
    let mut out = MetadataPatch::default();
    let mut partition_applies = false;
    for (k, v) in &patch.set {
        let outer = codex && (CODEX_OUTER.contains(&k.as_str()) || k == "siwc");
        if !outer && base.get(k) != Some(v) && (kept_by_user(k) || token_payload(k)) {
            out.set.insert(k.clone(), v.clone());
        }
    }
    out.remove = patch
        .remove
        .iter()
        .filter(|k| base.contains_key(*k) && kept_by_user(k))
        .cloned()
        .collect();
    if codex {
        // Go `CredentialRefreshPatch.Apply`: the refreshed tokens apply only while the
        // stored identity is still the one refreshed (or its result), and then only the
        // fields the refresh changed.
        let fields = |m: &Map<String, Value>, keys: &[&str]| -> Map<String, Value> {
            keys.iter()
                .filter_map(|k| m.get(*k).map(|v| ((*k).to_owned(), v.clone())))
                .collect()
        };
        let mut updated = base.clone();
        patch.apply(&mut updated);
        // Go `sameCredentialVersion` (`reflect.DeepEqual` on map reads: null is missing).
        let same = |current: &Map<String, Value>, b: &Map<String, Value>| {
            [
                "access_token",
                "refresh_token",
                "id_token",
                "account_id",
                "client_id",
                "device_id",
            ]
            .iter()
            .all(|k| current.get(*k).filter(|v| !v.is_null()) == b.get(*k).filter(|v| !v.is_null()))
        };
        // The changed fields of one partition, when `current` still holds the version
        // refreshed or its result.
        let changes = |current: &Map<String, Value>, before: &Map<String, Value>, after: &Map<String, Value>| {
            [before, after].into_iter().find(|b| same(current, b)).map(|baseline| {
                after
                    .iter()
                    .filter(|(k, v)| baseline.get(*k) != Some(*v))
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect::<Map<String, Value>>()
            })
        };
        let (before, after) = (fields(base, &CODEX_OUTER), fields(&updated, &CODEX_OUTER));
        if before != after
            && let Some(changed) = changes(user, &before, &after)
        {
            partition_applies = true;
            out.set.extend(changed);
        }
        // Go `codexSIWCCredentialKeys`.
        const CODEX_SIWC: [&str; 9] = [
            "access_token",
            "refresh_token",
            "id_token",
            "client_id",
            "device_id",
            "expired",
            "last_refresh",
            "scope",
            "scopes",
        ];
        let siwc = |m: &Map<String, Value>| m.get("siwc").and_then(Value::as_object).cloned().unwrap_or_default();
        let (before, after) = (fields(&siwc(base), &CODEX_SIWC), fields(&siwc(&updated), &CODEX_SIWC));
        let current = siwc(user);
        if before != after
            && let Some(changed) = changes(&current, &before, &after)
        {
            partition_applies = true;
            if !changed.is_empty() {
                let mut merged = current;
                merged.extend(changed);
                out.set.insert("siwc".into(), Value::Object(merged));
            }
        }
    }
    (out, partition_applies)
}

/// Go `CodexExecutor.Refresh` for credential `current`, whose file is `path`, as one
/// transaction: the file's credential lock (`<file>.lock`, shared with Go and
/// `--siwc-bind`) is taken, the file read under it, the grants sent from the tokens it
/// holds ([`cpa_exec::codex_refresh::Refresher::refresh_locked`]), their result written
/// onto the file as read again under the same lock when a grant was attempted
/// ([`codex_patched`]), and then admitted to the store, which writes the file again,
/// or discarded ([`CredentialStore::admit_codex_refresh`]), before the lock is released. A spawned
/// task owns it all, the preparation lock (`guard`) included: a cancelled caller cannot
/// release the lock while a grant is in flight and leave its new tokens unwritten.
#[allow(clippy::too_many_arguments)]
async fn refresh_codex_file(
    refreshes: &CodexRefreshes,
    store: Arc<CredentialStore>,
    refresher: cpa_exec::codex_refresh::Refresher,
    guard: tokio::sync::OwnedMutexGuard<()>,
    current: Arc<Credential>,
    registered: crate::plugins::refresh::Registered,
    view: Arc<Credential>,
    path: std::path::PathBuf,
    mode: cpa_exec::codex_refresh::RefreshMode,
) -> Result<Arc<Credential>, ExecError> {
    let local = |e: String| ExecError::local(500, FailureScope::Request, format!("codex executor: {e}"));
    let shutdown = refreshes.shutdown.clone();
    let transaction = refreshes.tasks.spawn(async move {
        let _guard = guard;
        let (lock, disk) = read_locked_codex_file(&path, &shutdown).await.map_err(local)?;
        let patch = refresher.refresh_locked(&view, &disk, mode).await?;
        if patch.is_empty() {
            return Ok(current);
        }
        let admitted = tokio::task::spawn_blocking(move || {
            let _lock = lock;
            // Go `refreshLocked` writes after a grant, whatever its manager then admits;
            // an adopt-only refresh reaches the file only when admitted.
            if patch.granted() {
                let bytes = std::fs::read(&path).map_err(|e| {
                    PatchError::Io(format!("re-read credential file {} before write: {e}", path.display()))
                })?;
                let out = codex_patched(&bytes, &patch, true).ok_or_else(|| {
                    PatchError::Io(format!("invalid credential JSON in {} before write", path.display()))
                })?;
                write_bytes_atomic(&path, &out)
                    .map_err(|e| PatchError::Io(format!("persist refreshed credentials to {}: {e}", path.display())))?;
            }
            #[cfg(test)]
            tests::before_admit(&path);
            store.admit_codex_refresh(&current, registered, &patch)
        })
        .await
        .map_err(|e| PatchError::Io(e.to_string()))
        .and_then(|r| r)
        .map_err(|e| {
            ExecError::local(
                500,
                FailureScope::Request,
                format!("committing prepared credential: {e:?}"),
            )
        })?;
        Ok(match admitted {
            CodexAdmission::Committed(c) | CodexAdmission::Discarded(c) => c,
        })
    });
    transaction.await.map_err(|e| local(e.to_string()))?
}

/// The Codex credential document `bytes` with `patch` applied (each partition over a
/// version it may still be applied over, every other field as it is), as Go's
/// `json.Marshal` of the decoded map; `None` when it is not a JSON object. For
/// `refresh_write`, Go `refreshLocked`'s write after a grant: the document must be a
/// non-empty object and keys stay as written. Otherwise Go `PersistCodexAuthFile`'s: any
/// object, legacy keys renamed (Go `NormalizeCredentialMetadata`).
fn codex_patched(bytes: &[u8], patch: &cpa_exec::codex_refresh::RefreshPatch, refresh_write: bool) -> Option<Vec<u8>> {
    use cpa_common::json::GoValue;
    // ponytail: the file is read through serde for the partition baselines, so one
    // holding invalid UTF-8 or a lone surrogate escape fails here (DIFFERENCES-FROM-GO.md).
    let target = match serde_json::from_slice::<Value>(bytes) {
        Ok(Value::Object(target)) if !(refresh_write && target.is_empty()) => target,
        _ => return None,
    };
    let mut doc = GoValue::parse_f64(bytes)?.into_object().ok()?;
    patch.apply(&target, &mut doc);
    if !refresh_write {
        let legacy: Vec<String> = doc
            .keys()
            .filter(|k| cpa_plugin::auth::canonical_metadata_key(k) != k.as_str())
            .cloned()
            .collect();
        for key in legacy {
            let value = doc.remove(&key).expect("listed above");
            doc.entry(cpa_plugin::auth::canonical_metadata_key(&key).to_owned())
                .or_insert(value);
        }
    }
    Some(GoValue::Object(doc).marshal())
}

/// Go `PersistCodexAuthFile` for an admitted refresh of `current`, while the caller holds
/// the file's credential lock: `patch` over the file as it is now, written. A file that
/// is gone is written from memory instead (the patch over `current`'s metadata, with its
/// `disabled` flag). A save that fails is logged and the patch over memory is published
/// unwritten, as Go's manager does (`failed to persist updated auth`), so the new tokens
/// are never dropped for a spent refresh token. Returns the document and whether the
/// file now holds it. Blocking.
fn save_codex_refresh(
    path: &Path,
    current: &Credential,
    patch: &cpa_exec::codex_refresh::RefreshPatch,
) -> (Vec<u8>, bool) {
    let memory = || {
        let mut metadata = current.metadata.clone();
        metadata.insert("disabled".into(), Value::Bool(current.disabled));
        let bytes = serde_json::to_vec(&metadata).expect("JSON values serialize");
        codex_patched(&bytes, patch, false).expect("a JSON object")
    };
    let warn = |error: String| {
        tracing::warn!(credential = %current.id, %error, "failed to persist updated codex auth");
    };
    let out = match std::fs::read(path) {
        Ok(bytes) => {
            codex_patched(&bytes, patch, false).ok_or_else(|| format!("invalid credential JSON in {}", path.display()))
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(memory()),
        Err(e) => Err(format!("read credential file {}: {e}", path.display())),
    };
    let saved = out.and_then(|out| match write_bytes_atomic(path, &out) {
        Ok(()) => Ok(out),
        Err(e) => Err(format!("write credential file {}: {e}", path.display())),
    });
    match saved {
        Ok(out) => (out, true),
        Err(error) => {
            warn(error);
            (memory(), false)
        }
    }
}

/// What [`CredentialStore::admit_codex_refresh`] did with a refresh.
enum CodexAdmission {
    /// Published as the credential.
    Committed(Arc<Credential>),
    /// Dropped, nothing changed: the credential as it is.
    Discarded(Arc<Credential>),
}

/// A credential's own proxy, published from its metadata (`proxy_url`, trimmed), or
/// none when the metadata has none (Go's canonical proxy merge).
fn publish_metadata_proxy(c: &mut Credential) {
    match c.str("proxy_url").map(str::trim).filter(|p| !p.is_empty()) {
        Some(proxy) => {
            let proxy = proxy.to_owned();
            c.attributes.insert("proxy_url".into(), proxy)
        }
        None => c.attributes.remove("proxy_url"),
    };
}

/// Why a wait for a Codex credential lock ended without it.
const LOCK_WAIT_STOPPED: &str = "shutting down while waiting for the credential lock";

/// The longest pause between two attempts at a Codex credential lock.
const LOCK_POLL_CEILING: Duration = Duration::from_millis(100);

/// The credential lock of the Codex file at `path` (Go's blocking `flock`), waited for
/// without holding a thread; the wait gives up at `shutdown`.
async fn wait_codex_lock(path: &Path, shutdown: &tokio_util::sync::CancellationToken) -> Result<std::fs::File, String> {
    #[cfg(test)]
    tests::LOCK_ATTEMPTS
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .push(path.to_owned());
    let stopped = || LOCK_WAIT_STOPPED.to_owned();
    if shutdown.is_cancelled() {
        return Err(stopped());
    }
    let lock = cpa_exec::codex_siwc_bind::open_lock_file(path)?;
    // ponytail: polled, not a blocking wait, so shutdown can stop it; up to 100 ms later
    // than Go's blocking flock once the holder releases. Upgrade: a lock wait on a
    // blocking thread that a signal interrupts.
    let mut delay = Duration::from_millis(5);
    loop {
        // Before every attempt: a shutdown during the sleep wins over a lock freed then.
        if shutdown.is_cancelled() {
            return Err(stopped());
        }
        if cpa_exec::codex_siwc_bind::try_lock(&lock)? {
            return Ok(lock);
        }
        tokio::select! {
            biased;
            _ = shutdown.cancelled() => return Err(stopped()),
            _ = tokio::time::sleep(delay) => {}
        }
        delay = (delay * 2).min(LOCK_POLL_CEILING);
    }
}

/// A held credential lock and the file read under it.
type LockedFile = (std::fs::File, Map<String, Value>);

/// Go `refreshLocked`'s read: the Codex credential file under its lock, which the
/// returned file holds. A file that is gone, or that is not a non-empty JSON object,
/// fails before anything refreshes. The wait for the lock gives up at `shutdown`.
async fn read_locked_codex_file(
    path: &Path,
    shutdown: &tokio_util::sync::CancellationToken,
) -> Result<LockedFile, String> {
    let lock = wait_codex_lock(path, shutdown).await?;
    let data = std::fs::read(path).map_err(|e| format!("read credential file {}: {e}", path.display()))?;
    match serde_json::from_slice(&data) {
        Ok(Value::Object(disk)) if !disk.is_empty() => Ok((lock, disk)),
        _ => Err(format!("invalid credential JSON in {}", path.display())),
    }
}

/// Go `CredentialsChanged`: the tokens or API key differ.
pub(crate) fn credentials_changed(a: &Credential, b: &Credential) -> bool {
    let text = |c: &Credential, keys: &[&str]| {
        keys.iter()
            .find_map(|k| {
                c.metadata
                    .get(*k)
                    .and_then(Value::as_str)
                    .map(str::trim)
                    .filter(|v| !v.is_empty())
            })
            .unwrap_or_default()
            .to_owned()
    };
    let siwc = |c: &Credential, key: &str| {
        c.metadata
            .get("siwc")
            .and_then(|s| s.get(key))
            .and_then(Value::as_str)
            .map_or("", str::trim)
            .to_owned()
    };
    let api_key = |c: &Credential| {
        c.attributes
            .get("api_key")
            .filter(|k| !k.is_empty())
            .cloned()
            .unwrap_or_else(|| text(c, &["api_key"]))
    };
    // Go `parseBoolAny`.
    let parse_bool = |s: &str| match s.trim() {
        "1" | "t" | "T" | "TRUE" | "true" | "True" => Some(true),
        "0" | "f" | "F" | "FALSE" | "false" | "False" => Some(false),
        _ => None,
    };
    let use_siwc = |c: &Credential| {
        let value = c.metadata.get("use_siwc")?;
        value
            .as_bool()
            .or_else(|| parse_bool(value.as_str()?))
            .or_else(|| value.as_f64().map(|n| n != 0.0))
    };
    // Go `authAccessToken`: the token requests use, which follows `IsCodexUseSIWC` (a
    // true attribute, else the file's flag).
    let effective_access_token = |c: &Credential| {
        let attribute = c.attributes.get("use_siwc").and_then(|v| parse_bool(v)) == Some(true);
        if attribute || use_siwc(c) == Some(true) {
            siwc(c, "access_token")
        } else {
            text(c, &["access_token", "accessToken"])
        }
    };
    effective_access_token(a) != effective_access_token(b)
        || [
            &["access_token", "accessToken"][..],
            &["refresh_token", "refreshToken"],
            &["id_token", "idToken"],
        ]
        .iter()
        .any(|keys| text(a, keys) != text(b, keys))
        || api_key(a) != api_key(b)
        || ["access_token", "refresh_token", "id_token", "client_id"]
            .iter()
            .any(|k| siwc(a, k) != siwc(b, k))
        || use_siwc(a) != use_siwc(b)
}

/// Replaces `path` with `bytes` through an exclusively created, uniquely named 0600
/// sibling and a rename. The temp name does not end in `.json`, so a crash never leaves
/// a loadable credential.
pub(crate) fn write_bytes_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    #[cfg(test)]
    tests::stall_write(path);
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let dir = path.parent().unwrap_or(Path::new("."));
    let name = path.file_name().unwrap_or_default().to_string_lossy();
    let (tmp, mut file) = loop {
        let tmp = dir.join(format!(
            ".{name}.{}.{}.tmp",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        // create_new is O_CREAT|O_EXCL: it never follows or reuses an existing path.
        let mut options = std::fs::OpenOptions::new();
        options.write(true).create_new(true);
        // Go's 0600; on Windows Go ignores mode bits and creates the file plainly.
        #[cfg(unix)]
        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
        match options.open(&tmp) {
            Ok(file) => break (tmp, file),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    };
    let result = file
        .write_all(bytes)
        .and_then(|()| file.sync_all())
        .and_then(|()| std::fs::rename(&tmp, path));
    if result.is_err() {
        let _ = std::fs::remove_file(&tmp);
    }
    result
}

/// A response stream that reports its lease's outcome on end, on the first error (after
/// which it yields nothing more), or as `Cancelled` when dropped early.
///
/// A remote lease's cancellation (Go's selection-bound attempt context) is watched by
/// its own task: a draining dispatcher closes the upstream body and ends the lease even
/// while the client is not reading, and the reader then sees `context canceled`.
pub struct Completing {
    slot: Arc<Mutex<Slot>>,
    watcher: Option<tokio::task::JoinHandle<()>>,
}

struct Slot {
    inner: ExecStream,
    lease: Option<Lease>,
    /// The watcher ended the lease; the next poll yields the cancellation error.
    cancelled: bool,
    waker: Option<std::task::Waker>,
}

impl Completing {
    pub fn new(inner: ExecStream, lease: Lease) -> Self {
        let cancelled = lease.remote_cancelled();
        let slot = Arc::new(Mutex::new(Slot {
            inner,
            lease: Some(lease),
            cancelled: false,
            waker: None,
        }));
        let watcher = cancelled.map(|cancelled| {
            let slot = Arc::downgrade(&slot);
            tokio::spawn(async move {
                cancelled.await;
                let Some(slot) = slot.upgrade() else { return };
                let (inner, lease, waker) = {
                    let mut s = slot.lock().unwrap_or_else(PoisonError::into_inner);
                    let Some(lease) = s.lease.take() else { return };
                    s.cancelled = true;
                    let inner = std::mem::replace(&mut s.inner, Box::pin(futures_util::stream::empty()));
                    (inner, lease, s.waker.take())
                };
                // The upstream body closes first, then the lease ends.
                drop(inner);
                lease.complete(Outcome::Cancelled);
                if let Some(waker) = waker {
                    waker.wake();
                }
            })
        });
        Self { slot, watcher }
    }
}

impl Drop for Completing {
    fn drop(&mut self) {
        if let Some(watcher) = &self.watcher {
            watcher.abort();
        }
    }
}

impl Stream for Completing {
    type Item = Result<Bytes, ExecError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut s = self.slot.lock().unwrap_or_else(PoisonError::into_inner);
        if std::mem::take(&mut s.cancelled) {
            return Poll::Ready(Some(Err(crate::remote::cancelled_error())));
        }
        if s.lease.is_none() {
            return Poll::Ready(None);
        }
        if self.watcher.is_some() {
            s.waker = Some(cx.waker().clone());
        }
        let item = ready!(s.inner.poll_next_unpin(cx));
        match &item {
            Some(Ok(_)) => {}
            None => s.lease.take().unwrap().complete(Outcome::Success),
            Some(Err(e)) => {
                // The upstream body closes before the lease ends: a remote lease's release
                // must not reach the control plane while the response is still open.
                s.inner = Box::pin(futures_util::stream::empty());
                s.lease.take().unwrap().complete(Outcome::Failure(e.clone()));
            }
        }
        Poll::Ready(item)
    }
}

/// Go `configuredSignatureCacheEnabled` / `configuredSignatureBypassStrict`
/// (internal/api/server_reload.go): `oauth.providers.antigravity.signature-cache-enabled`
/// (default true) and `.signature-bypass-strict` (default false), legacy
/// `antigravity-signature-*` spellings included. Applied on every publish, as Go
/// applies them at startup and on each reload.
fn signature_cache_config(cfg: &Config) -> (bool, bool) {
    let flag = |key: &str| {
        cfg.document
            .get("oauth")
            .and_then(|o| o.get("providers"))
            .and_then(|p| p.get("antigravity"))
            .and_then(|a| a.get(key))
            .and_then(serde_yaml_ng::Value::as_bool)
    };
    (
        flag("signature-cache-enabled").unwrap_or(true),
        flag("signature-bypass-strict").unwrap_or(false),
    )
}

/// Credentials the background refresh considers: enabled auth files, never API-key
/// kinds (Go `nextRefreshCheckAt` skips `AuthKind() == apikey` for every provider).
fn refresh_candidate(c: &Credential) -> bool {
    matches!(c.source, Source::File(_)) && !c.disabled && cpa_core::registry::dynamic::auth_kind(c) != Some("apikey")
}

/// Test hook at `site` for credential `id` ([`tests::hook`]); nothing otherwise.
fn test_hook(site: &'static str, id: &str) {
    #[cfg(test)]
    tests::hook(site, id);
    let _ = (site, id);
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    thread_local! {
        /// Runs once where [`commit_refresh`] meets an edit made since its snapshot,
        /// before it reads the credential again.
        pub(super) static AFTER_STALE: std::cell::Cell<Option<Box<dyn FnOnce()>>> = const { std::cell::Cell::new(None) };
    }

    /// Hook sites ([`test_hook`]) armed to panic once, by site and credential ID, and how
    /// often each was reached. Process-wide: refresh jobs run on any worker thread.
    static PANICS: Mutex<Vec<(&'static str, String)>> = Mutex::new(Vec::new());
    static REACHED: Mutex<Vec<(&'static str, String)>> = Mutex::new(Vec::new());

    pub(super) fn hook(site: &'static str, id: &str) {
        REACHED.lock().unwrap().push((site, id.to_owned()));
        let mut panics = PANICS.lock().unwrap();
        if let Some(i) = panics.iter().position(|(s, i)| *s == site && i == id) {
            panics.remove(i);
            drop(panics);
            panic!("injected {site} panic");
        }
    }

    /// The next time `site` is reached for credential `id`, it panics.
    fn arm_panic(site: &'static str, id: &str) {
        PANICS.lock().unwrap().push((site, id.to_owned()));
    }

    /// How often `site` was reached for credential `id`.
    fn reached(site: &'static str, id: &str) -> usize {
        REACHED
            .lock()
            .unwrap()
            .iter()
            .filter(|(s, i)| *s == site && i == id)
            .count()
    }

    /// Every Codex credential file a refresh or management write waited to lock, in
    /// order (all tests).
    pub(crate) static LOCK_ATTEMPTS: Mutex<Vec<std::path::PathBuf>> = Mutex::new(Vec::new());

    /// Waits until something waited to lock the Codex file at `path`.
    pub(crate) async fn lock_waited(path: &Path) {
        let waited = async {
            while !LOCK_ATTEMPTS.lock().unwrap().iter().any(|p| p == path) {
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        };
        tokio::time::timeout(Duration::from_secs(5), waited)
            .await
            .expect("something waits for the credential lock");
    }

    type AdmitHook = (std::path::PathBuf, Box<dyn FnOnce() + Send>);

    /// Runs once, for its file, where a Codex refresh is about to be admitted.
    static BEFORE_ADMIT: Mutex<Vec<AdmitHook>> = Mutex::new(Vec::new());

    pub(super) fn before_admit(path: &Path) {
        let hook = {
            let mut hooks = BEFORE_ADMIT.lock().unwrap();
            hooks.iter().position(|(p, _)| p == path).map(|i| hooks.remove(i).1)
        };
        if let Some(hook) = hook {
            hook();
        }
    }

    /// Go checks a refresh's `RegistrationEpoch` before anything else in
    /// `updateInternal`: a refresh that meets an edit, after which its ID is registered
    /// again with other tokens, fails as a stale registration, not as a refresh dropped
    /// for changed credentials (which hands the caller the new credential).
    #[test]
    fn a_refresh_meeting_an_edit_then_a_new_registration_fails_as_stale() {
        let dir = std::env::temp_dir().join(format!("cpa-refresh-stale-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let credential = {
            let dir = dir.clone();
            move |token: &str| {
                let metadata = serde_json::json!({"type":"pp","access_token":token});
                let path = dir.join("a.json");
                std::fs::write(&path, metadata.to_string()).unwrap();
                Credential::from_file(&dir, &path, metadata.as_object().cloned().unwrap()).unwrap()
            }
        };
        let store = Arc::new(CredentialStore::new(vec![credential("a")]));
        let (current, registration) = store.get_registered("a.json").unwrap();
        // An unrelated edit under the same registration: the refresh meets it as stale.
        let mut note = MetadataPatch::default();
        note.set.insert("note".into(), "edited".into());
        store.apply_patch("a.json", current.revision, &note).unwrap();
        AFTER_STALE.with(|hook| {
            hook.set(Some(Box::new({
                let (store, credential) = (store.clone(), credential.clone());
                move || {
                    store.reconcile(vec![]);
                    store.reconcile(vec![credential("b")]);
                }
            })))
        });
        let mut patch = MetadataPatch::default();
        patch.set.insert("access_token".into(), "p2".into());
        let fence = RefreshFence {
            registered: registration,
            plugin: false,
        };
        let committed = commit_refresh(&store, "a.json", &current, fence, &patch, |_| {});
        assert!(AFTER_STALE.with(|hook| hook.take()).is_none(), "the hook ran");
        assert!(matches!(committed, Err(PatchError::NotFound)), "{committed:?}");
        assert_eq!(store.get("a.json").unwrap().metadata["access_token"], "b");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Go `nextRefreshCheckAt` skips `AuthKind() == apikey` for every provider. The
    /// kinds are Go's `AuthKind` goldens (tests/fixtures/server_go.json `auth_kind`).
    #[test]
    fn refresh_skips_api_key_kinds_like_go() {
        let fixture: serde_json::Value =
            serde_json::from_str(include_str!("../tests/fixtures/server_go.json")).unwrap();
        let mut kinds = std::collections::BTreeSet::new();
        for case in fixture["auth_kind"].as_array().unwrap() {
            let meta = serde_json::json!({"type": "kimi"}).as_object().unwrap().clone();
            let mut c = Credential::from_file(Path::new("/a"), Path::new("/a/x.json"), meta).unwrap();
            c.metadata = case["metadata"].as_object().cloned().unwrap_or_default();
            c.attributes = case["attributes"]
                .as_object()
                .map(|a| {
                    a.iter()
                        .map(|(k, v)| (k.clone(), v.as_str().unwrap().to_owned()))
                        .collect()
                })
                .unwrap_or_default();
            let kind = case["kind"].as_str().unwrap();
            kinds.insert(kind);
            assert_eq!(refresh_candidate(&c), kind != "apikey", "case {case}");
            c.disabled = true;
            assert!(!refresh_candidate(&c));
        }
        assert!(kinds.contains("apikey") && kinds.contains("oauth"), "{kinds:?}");
    }

    #[test]
    fn signature_cache_config_reads_v8_and_legacy_keys() {
        let at = |yaml: &str| signature_cache_config(&Config::parse(yaml).unwrap());
        assert_eq!(at("{}\n"), (true, false));
        assert_eq!(
            at("antigravity-signature-cache-enabled: false\nantigravity-signature-bypass-strict: true\n"),
            (false, true)
        );
        assert_eq!(
            at("oauth: {providers: {antigravity: {signature-cache-enabled: false, signature-bypass-strict: true}}}\n"),
            (false, true)
        );
        assert_eq!(
            at("oauth: {providers: {antigravity: {signature-cache-enabled: null}}}\n"),
            (true, false)
        );
    }

    fn cred(id: &str, provider: &str, disabled: bool) -> Credential {
        let mut metadata = Map::new();
        metadata.insert("type".into(), provider.into());
        metadata.insert("disabled".into(), disabled.into());
        Credential::from_file(Path::new("/a"), &Path::new("/a").join(id), metadata).unwrap()
    }

    fn sel(provider: &str) -> Selection {
        Selection {
            provider: provider.into(),
            ..Selection::default()
        }
    }

    #[test]
    fn select_round_robins_enabled_credentials_and_honours_exclusions() {
        let store = CredentialStore::new(vec![
            cred("c1.json", "claude", false),
            cred("off.json", "claude", true),
            cred("x.json", "codex", false),
            cred("c2.json", "claude", false),
        ]);
        let picks: Vec<String> = (0..4)
            .map(|_| store.select(sel("claude")).unwrap().credential.id.clone())
            .collect();
        assert_eq!(picks, ["c1.json", "c2.json", "c1.json", "c2.json"]);
        assert!(store.select(sel("gemini")).is_none());
        let only = Selection {
            exclude: vec!["c1.json".into()],
            ..sel("claude")
        };
        for _ in 0..3 {
            assert_eq!(store.select(only.clone()).unwrap().credential.id, "c2.json");
        }
    }

    /// Sequential cache invalidation of the derived registry: after a prefix change, a
    /// disable, a removal or a re-registration the next use rebuilds it, and a request
    /// result alone does not. This is not Go's publication fence (7c2133e2, 08e5762a,
    /// f75ea073): a build already in flight still returns its older snapshot.
    #[test]
    fn the_registry_follows_the_latest_credentials() {
        let rt = crate::testing::runtime(
            Config::parse("").unwrap(),
            Vec::new(),
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        );
        let with = |prefix: &str, disabled: bool| {
            let mut c = cred("a.json", "claude", disabled);
            c.metadata.insert("prefix".into(), prefix.into());
            c
        };
        rt.store.reconcile(vec![with("old", false)]);
        let model = cpa_core::registry::dynamic::models_for(&rt.config(), &HashMap::new(), &with("", false), 0)
            .first()
            .map(|spec| spec.id.clone())
            .expect("a Claude catalog model");
        let supports = |prefix: &str| rt.registry().client_supports("a.json", &format!("{prefix}/{model}"));
        assert!(supports("old"));
        let built = rt.registry();
        rt.store
            .select(Selection::new("claude", &model))
            .unwrap()
            .complete(Outcome::Success);
        assert!(Arc::ptr_eq(&built, &rt.registry()), "a result does not rebuild it");
        rt.store.reconcile(vec![with("new", false)]);
        assert!(supports("new") && !supports("old"), "a superseded prefix");
        rt.store.reconcile(vec![with("new", true)]);
        assert!(!rt.registry().has_client("a.json"), "disabled");
        rt.store.reconcile(vec![with("new", false)]);
        assert!(supports("new"), "enabled again");
        rt.store.reconcile(Vec::new());
        assert!(!rt.registry().has_client("a.json"), "removed");
        rt.store.reconcile(vec![with("fresh", false)]);
        assert!(supports("fresh") && !supports("new"), "re-registered");
    }

    #[test]
    fn standalone_admission_reads_attributes_first() {
        let mut c = cred("a.json", "claude", false);
        c.metadata.insert("prefix".into(), "meta".into());
        c.metadata
            .insert("excluded_models".into(), serde_json::json!(["claude-sonnet*"]));
        c.attributes.insert("prefix".into(), "team".into());
        c.attributes.insert("excluded_models".into(), "claude-opus*".into());
        let policy = Policy::default();
        let admit = |model: &str| {
            let s = Selection::new("claude", model);
            standalone_admission(&s, &policy)(&c)
        };
        assert_eq!(
            admit("team/claude-sonnet-5(high)").as_deref(),
            Some("claude-sonnet-5(high)")
        );
        assert_eq!(admit("team/claude-opus-5"), None, "attribute exclusions win");
        assert_eq!(
            admit("meta/claude-sonnet-5"),
            None,
            "metadata prefix is not authoritative"
        );
        assert_eq!(admit("claude-sonnet-5").as_deref(), Some("claude-sonnet-5"));
        let forced = Policy {
            force_model_prefix: true,
            ..Policy::default()
        };
        let s = Selection::new("claude", "claude-sonnet-5");
        assert_eq!(standalone_admission(&s, &forced)(&c), None);
        assert_eq!(standalone_admission(&Selection::new("codex", "x"), &policy)(&c), None);
    }

    #[test]
    fn patch_persists_atomically_preserves_unknown_fields_and_rejects_stale() {
        let dir = std::env::temp_dir().join(format!("cpa-store-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("claude-a.json");
        std::fs::write(
            &path,
            r#"{"type":"claude","access_token":"old","zz_unknown":{"k":[1,2]}}"#,
        )
        .unwrap();
        // A stale temp-file-looking path and a symlink must not be reused or followed.
        let victim = dir.join("victim");
        std::fs::write(&victim, "keep").unwrap();
        #[cfg(unix)]
        std::os::unix::fs::symlink(
            &victim,
            dir.join(format!(".claude-a.json.{}.0.tmp", std::process::id())),
        )
        .unwrap();
        let mut cfg = cpa_core::config::Config::parse("").unwrap();
        cfg.auth_dir = dir.clone();
        let store = CredentialStore::new(cpa_core::config::credentials::from_auth_dir(&cfg));
        let rev = store.get("claude-a.json").unwrap().revision;

        let mut patch = MetadataPatch::default();
        patch.set.insert("access_token".into(), "new".into());
        patch.set.insert("email".into(), "a@x.test".into());
        patch.set.insert("disabled".into(), true.into());
        let updated = store.apply_patch("claude-a.json", rev, &patch).unwrap();
        assert!(updated.revision > rev);
        assert!(updated.disabled);
        assert_eq!(updated.label, "a@x.test", "derived label follows the new email");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "{\"type\":\"claude\",\"access_token\":\"new\",\"zz_unknown\":{\"k\":[1,2]},\"email\":\"a@x.test\",\"disabled\":true}\n"
        );
        #[cfg(unix)]
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
        assert_eq!(
            std::fs::read_to_string(&victim).unwrap(),
            "keep",
            "symlink target untouched"
        );
        assert!(
            store.select(sel("claude")).is_none(),
            "patched-disabled credential leaves rotation"
        );

        assert_eq!(
            store.apply_patch("claude-a.json", rev, &patch).unwrap_err(),
            PatchError::Stale {
                current: updated.revision
            }
        );
        assert_eq!(
            store.apply_patch("nope.json", 0, &patch).unwrap_err(),
            PatchError::NotFound
        );
        let mut retype = MetadataPatch::default();
        retype.set.insert("type".into(), "codex".into());
        assert_eq!(
            store
                .apply_patch("claude-a.json", updated.revision, &retype)
                .unwrap_err(),
            PatchError::TypeIsImmutable
        );
        let leftovers: Vec<_> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().into_string().unwrap())
            .filter(|n| n.ends_with(".tmp") && !n.ends_with(".0.tmp"))
            .collect();
        assert!(leftovers.is_empty(), "no temp files left behind: {leftovers:?}");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A plugin save running alongside token refreshes of another credential never
    /// reinstalls a stale copy of it: every refresh finds the revision it left.
    #[test]
    fn upsert_never_undoes_a_concurrent_patch() {
        let dir = std::env::temp_dir().join(format!("cpa-upsert-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("refreshed.json"), r#"{"type":"claude","refresh_token":"r0"}"#).unwrap();
        std::fs::write(dir.join("saved.json"), r#"{"type":"claude"}"#).unwrap();
        let mut cfg = cpa_core::config::Config::parse("").unwrap();
        cfg.auth_dir = dir.clone();
        let store = Arc::new(CredentialStore::new(cpa_core::config::credentials::from_auth_dir(&cfg)));
        let saved = (*store.get("saved.json").unwrap()).clone();
        let saver = {
            let store = store.clone();
            std::thread::spawn(move || {
                for n in 0..500 {
                    let mut next = saved.clone();
                    next.metadata.insert("n".into(), n.into());
                    store.upsert(next);
                }
            })
        };
        let mut revision = store.get("refreshed.json").unwrap().revision;
        for n in 1..=500 {
            let mut patch = MetadataPatch::default();
            patch.set.insert("refresh_token".into(), format!("r{n}").into());
            revision = store
                .apply_patch("refreshed.json", revision, &patch)
                .unwrap_or_else(|e| panic!("refresh {n} was undone: {e:?}"))
                .revision;
        }
        saver.join().unwrap();
        let refreshed = store.get("refreshed.json").unwrap();
        assert_eq!(refreshed.revision, revision);
        assert_eq!(refreshed.metadata["refresh_token"], "r500");
        assert_eq!(store.get("saved.json").unwrap().metadata["n"], 499);
        assert_eq!(store.snapshot().len(), 2);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Home config updates replacing the config keys never undo a concurrent plugin save
    /// or relay session change, and unchanged keys keep their revision.
    #[test]
    fn replace_config_keeps_concurrent_changes_to_other_credentials() {
        let keys = |key: &str| {
            let cfg = cpa_core::config::Config::parse(&format!(
                "codex-api-key:\n  - api-key: {key}\n    base-url: http://127.0.0.1:9\n"
            ))
            .unwrap();
            cpa_core::config::credentials::from_config(&cfg)
        };
        let store = Arc::new(CredentialStore::new(keys("sk-a")));
        let mut saved = Credential::relay_session("saved");
        saved.source = Source::File("saved.json".into());
        saved.id = "saved.json".into();
        // Each step checks that the previous one survived the concurrent replacements.
        let changer = {
            let store = store.clone();
            std::thread::spawn(move || {
                for n in 0..2000 {
                    if n > 0 {
                        assert_eq!(
                            store.get("saved.json").unwrap().metadata["n"],
                            n - 1,
                            "a save was undone"
                        );
                        assert!(store.get("relay").is_none(), "a closed relay session came back");
                    }
                    let mut next = saved.clone();
                    next.metadata.insert("n".into(), n.into());
                    store.upsert(next);
                    store.add_runtime(Credential::relay_session("relay"));
                    store.remove_runtime("relay");
                }
            })
        };
        let mut n = 0;
        while !changer.is_finished() {
            store.replace_config(keys(if n % 2 == 0 { "sk-b" } else { "sk-a" }));
            n += 1;
        }
        changer.join().unwrap();
        store.replace_config(keys("sk-a"));
        let revision = store.snapshot().iter().find(|c| c.id != "saved.json").unwrap().revision;
        store.replace_config(keys("sk-a"));
        let ids: Vec<_> = store.snapshot().iter().map(|c| (c.id.clone(), c.revision)).collect();
        assert_eq!(ids.len(), 2, "{ids:?}");
        assert!(ids.contains(&(keys("sk-a")[0].id.clone(), revision)), "{ids:?}");
        assert_eq!(store.get("saved.json").unwrap().metadata["n"], 1999);
    }

    /// The next write of `path` (from any thread) stops inside [`write_bytes_atomic`],
    /// before the file changes, until the returned release is sent or dropped.
    fn stall_next_write(path: &Path) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
        let (entered_tx, entered) = std::sync::mpsc::channel();
        let (release, release_rx) = std::sync::mpsc::channel();
        STALLS
            .lock()
            .unwrap()
            .insert(path.to_path_buf(), (entered_tx, release_rx));
        (entered, release)
    }

    type Stall = (std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>);
    static STALLS: std::sync::LazyLock<Mutex<HashMap<std::path::PathBuf, Stall>>> =
        std::sync::LazyLock::new(Mutex::default);

    pub(super) fn stall_write(path: &Path) {
        let Some((entered, release)) = STALLS.lock().unwrap().remove(path) else {
            return;
        };
        let _ = entered.send(());
        let _ = release.recv();
    }

    /// Runs `f` on its own thread; its result, or `None` while it is still running after
    /// `wait`.
    fn spawn_bounded<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> std::sync::mpsc::Receiver<T> {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let _ = tx.send(f());
        });
        rx
    }

    const BOUND: Duration = Duration::from_secs(5);
    const BLOCKED: Duration = Duration::from_millis(300);

    fn stalled_store(
        name: &str,
        files: &[&str],
    ) -> (std::path::PathBuf, cpa_core::config::Config, Arc<CredentialStore>) {
        let dir = std::env::temp_dir().join(format!("cpa-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        for file in files {
            std::fs::write(dir.join(file), r#"{"type":"claude","access_token":"old"}"#).unwrap();
        }
        let mut cfg = cpa_core::config::Config::parse("").unwrap();
        cfg.auth_dir = dir.clone();
        let store = CredentialStore::new(cpa_core::config::credentials::from_auth_dir(&cfg));
        (dir, cfg, store)
    }

    fn token_patch(token: &str) -> MetadataPatch {
        let mut patch = MetadataPatch::default();
        patch.set.insert("access_token".into(), token.into());
        patch
    }

    /// Go 8a01bc02 (`TestManagerBlockedSaveAllowsUnrelatedCredential`,
    /// `TestManagerBlockedSaveSerializesLoad`): while a refresh commit's file write is
    /// stalled on disk, snapshots and selection proceed, before and while a reload is
    /// pending; another credential's write proceeds; and neither the reload nor another
    /// write of the same credential overtakes the stalled one. (A reload whose scan read
    /// the file before the write is Go c4c1d43e's stale-snapshot check, not ported here.)
    #[test]
    fn a_stalled_credential_write_blocks_only_its_reload() {
        let (dir, cfg, store) = stalled_store("stalled-write", &["a.json", "b.json"]);
        let before = store.get("a.json").unwrap().revision;
        let (entered, release) = stall_next_write(&dir.join("a.json"));
        let writer = spawn_bounded({
            let store = store.clone();
            move || {
                store
                    .apply_patch("a.json", before, &token_patch("new"))
                    .map(|c| c.revision)
            }
        });
        entered.recv_timeout(BOUND).expect("the write reached the disk");
        // Leases stay alive until the end: dropping one records a result and persists.
        let mut leases = Vec::new();
        let read_and_select = |leases: &mut Vec<Lease>, when: &str| {
            let reader = spawn_bounded({
                let store = store.clone();
                move || store.snapshot().len()
            });
            assert_eq!(reader.recv_timeout(BOUND).ok(), Some(2), "a snapshot {when}");
            let selector = spawn_bounded({
                let store = store.clone();
                move || {
                    store.select(Selection {
                        exclude: vec!["a.json".into()],
                        ..sel("claude")
                    })
                }
            });
            let lease = selector
                .recv_timeout(BOUND)
                .unwrap_or_else(|_| panic!("a selection {when}"));
            leases.push(lease.expect("b.json"));
        };
        read_and_select(&mut leases, "during the write");
        let other = spawn_bounded({
            let store = store.clone();
            move || {
                let revision = store.get("b.json").unwrap().revision;
                store.apply_patch("b.json", revision, &token_patch("b2")).map(|_| ())
            }
        });
        assert!(
            matches!(other.recv_timeout(BOUND), Ok(Ok(()))),
            "another credential's write"
        );
        // A scan made now still reads A's old file, which is c4c1d43e's stale snapshot;
        // this reload carries what the write is about to publish, so the end state shows
        // which one landed last.
        let mut rescan = cpa_core::config::credentials::from_auth_dir(&cfg);
        let in_scan = rescan.iter_mut().find(|c| c.id == "a.json").unwrap();
        in_scan.metadata.insert("access_token".into(), "new".into());
        in_scan.metadata.insert("reloaded".into(), true.into());
        let reload = spawn_bounded({
            let store = store.clone();
            move || store.reconcile(rescan)
        });
        assert!(
            reload.recv_timeout(BLOCKED).is_err(),
            "the reload overtook the stalled write"
        );
        read_and_select(&mut leases, "while a reload is pending");
        let same = spawn_bounded({
            let store = store.clone();
            move || store.apply_patch("a.json", before, &token_patch("other")).map(|_| ())
        });
        assert!(
            same.recv_timeout(BLOCKED).is_err(),
            "a write of the same credential overtook it"
        );
        release.send(()).unwrap();
        let published = writer
            .recv_timeout(BOUND)
            .expect("the write finished")
            .expect("and published");
        assert!(published > before);
        reload.recv_timeout(BOUND).expect("the reload finished");
        assert!(
            matches!(same.recv_timeout(BOUND), Ok(Err(PatchError::Stale { .. }))),
            "the same-credential write saw the published revision"
        );
        drop(leases);
        let file: Map<String, Value> = serde_json::from_slice(&std::fs::read(dir.join("a.json")).unwrap()).unwrap();
        assert_eq!(file["access_token"], "new");
        let a = store.get("a.json").unwrap();
        assert_eq!(
            a.metadata.get("reloaded"),
            Some(&Value::Bool(true)),
            "the reload landed last"
        );
        assert!(a.revision > published);
        assert_eq!(store.get("b.json").unwrap().metadata["access_token"], "b2");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// An edit that renames credential A to B's ID replaces B, so it must not run while
    /// a write of B is between its revision check and its publication.
    #[test]
    fn an_identity_change_waits_for_a_write_of_the_credential_it_replaces() {
        let (dir, _cfg, store) = stalled_store("identity-change", &["a.json", "b.json"]);
        let b = store.get("b.json").unwrap().revision;
        let a = store.get("a.json").unwrap();
        let (entered, release) = stall_next_write(&dir.join("b.json"));
        let writer = spawn_bounded({
            let store = store.clone();
            move || store.apply_patch("b.json", b, &token_patch("b2")).map(|c| c.revision)
        });
        entered.recv_timeout(BOUND).expect("B's write reached the disk");
        let mut renamed = Credential::clone(&a);
        renamed.id = "b.json".into();
        renamed.metadata.insert("access_token".into(), "renamed".into());
        let replace = spawn_bounded({
            let store = store.clone();
            move || {
                let bytes = br#"{"type":"claude","access_token":"renamed"}"#;
                store.replace_file_backed("a.json", a.revision, bytes, Some(renamed))
            }
        });
        assert!(replace.recv_timeout(BLOCKED).is_err(), "the rename overtook B's write");
        release.send(()).unwrap();
        let written = writer.recv_timeout(BOUND).expect("B's write finished");
        assert!(written.is_ok(), "B's write was published, not dropped: {written:?}");
        assert!(matches!(replace.recv_timeout(BOUND), Ok(Ok(()))));
        let ids: Vec<String> = store.snapshot().iter().map(|c| c.id.clone()).collect();
        assert_eq!(ids, ["b.json"]);
        assert_eq!(store.get("b.json").unwrap().metadata["access_token"], "renamed");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Go c4c1d43e `TestFileSnapshotCannotOverwriteLaterPersistedPrefix`: a scan that
    /// read a file before a later write cannot undo that write; a real edit still
    /// applies; a file gone or unreadable since the scan keeps the current credential.
    #[test]
    fn a_stale_scan_cannot_undo_a_later_write() {
        let dir = std::env::temp_dir().join(format!("cpa-stale-scan-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("synthetic.json");
        let write = |prefix: &str| std::fs::write(&path, format!(r#"{{"type":"codex","prefix":"{prefix}"}}"#)).unwrap();
        let mut cfg = cpa_core::config::Config::parse("").unwrap();
        cfg.auth_dir = dir.clone();
        let scan = || cpa_core::config::credentials::scan_auth_dir(&cfg);
        write("pfx-8");
        let store = CredentialStore::new(scan().credentials);
        let stale = scan();
        let revision = store.get("synthetic.json").unwrap().revision;
        let mut patch = MetadataPatch::default();
        patch.set.insert("prefix".into(), "pfx-9".into());
        store.apply_patch("synthetic.json", revision, &patch).unwrap();
        let current = || store.get("synthetic.json").unwrap();
        let before = current();
        store.reconcile_scanned(stale.credentials, &stale.read);
        assert_eq!(
            current().metadata["prefix"],
            "pfx-9",
            "the stale scan overwrote the write"
        );
        assert_eq!(current().revision, before.revision);
        write("manual-edit");
        let manual = scan();
        store.reconcile_scanned(manual.credentials, &manual.read);
        assert_eq!(current().metadata["prefix"], "manual-edit", "a real edit was lost");
        let before = current();
        write("deleted-edit");
        let deleted = scan();
        std::fs::remove_file(&path).unwrap();
        store.reconcile_scanned(deleted.credentials.clone(), &deleted.read);
        assert_eq!(
            current().revision,
            before.revision,
            "a deleted file's snapshot was applied"
        );
        std::fs::create_dir(&path).unwrap();
        store.reconcile_scanned(deleted.credentials.clone(), &deleted.read);
        assert_eq!(
            current().revision,
            before.revision,
            "an unreadable file's snapshot was applied"
        );
        // A FIFO in its place is not opened (reading one blocks until a writer appears).
        #[cfg(unix)]
        {
            std::fs::remove_dir(&path).unwrap();
            let fifo = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
            // SAFETY: valid NUL-terminated path in this test's private directory.
            assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);
            let done = spawn_bounded({
                let store = store.clone();
                move || store.reconcile_scanned(deleted.credentials, &deleted.read)
            });
            done.recv_timeout(BOUND).expect("the freshness check opened the FIFO");
            assert_eq!(current().revision, before.revision, "a FIFO's snapshot was applied");
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn reconcile_keeps_unchanged_revisions_and_never_reuses_old_ones() {
        let store = CredentialStore::new(vec![cred("a.json", "claude", false), cred("b.json", "claude", false)]);
        let a = store.get("a.json").unwrap();
        let b = store.get("b.json").unwrap();
        store.reconcile(vec![cred("a.json", "claude", false)]);
        assert!(
            Arc::ptr_eq(&store.get("a.json").unwrap(), &a),
            "unchanged credential kept as is"
        );
        assert!(store.get("b.json").is_none());
        store.reconcile(vec![cred("a.json", "claude", false), cred("b.json", "claude", false)]);
        assert!(
            store.get("b.json").unwrap().revision > b.revision,
            "re-created credential gets a new revision"
        );
    }

    #[test]
    fn attribute_only_reload_changes_priority_and_rejects_stale_outcome() {
        let a = cred("a.json", "claude", false);
        let mut b = cred("b.json", "claude", false);
        b.attributes.insert("priority".into(), "1".into());
        let store = CredentialStore::new(vec![a.clone(), b.clone()]);
        let old = store.select(sel("claude")).unwrap();
        assert_eq!(old.credential.id, "b.json");
        let revision = old.credential.revision;
        b.attributes.insert("priority".into(), "2".into());
        store.reconcile(vec![a, b]);
        assert!(store.get("b.json").unwrap().revision > revision);
        old.complete(Outcome::Failure(ExecError::local(
            401,
            FailureScope::Credential,
            "expired",
        )));
        let current = store.select(sel("claude")).unwrap();
        assert_eq!(
            current.credential.id, "b.json",
            "stale outcome must not cool new revision"
        );
        assert_eq!(current.credential.attributes["priority"], "2");
        current.complete(Outcome::Success);
        assert_eq!(store.stats().failure, 1);
        assert_eq!(store.stats().success, 1);
    }

    #[test]
    fn stale_lease_cannot_poison_deleted_and_recreated_credential() {
        let credential = cred("a.json", "claude", false);
        let store = CredentialStore::new(vec![credential.clone()]);
        let old = store.select(sel("claude")).unwrap();
        store.reconcile(Vec::new());
        store.reconcile(vec![credential]);
        old.complete(Outcome::Failure(ExecError::local(
            429,
            FailureScope::Credential,
            "quota",
        )));
        store.select(sel("claude")).unwrap().complete(Outcome::Success);
        assert_eq!(store.stats().failure, 1);
        assert_eq!(store.stats().success, 1);
    }

    /// Go `TestRetryIntervalFiltersCooldownCredentials` and
    /// `TestRetryRoundAvailabilityRejectsStaleQuotaForNonRetryableStatus`: the next round
    /// waits for the earliest cooldown within max-retry-interval, skipping longer ones,
    /// and a credential cooling after a 402 or 404 never permits a round, whatever its
    /// deadline, while one cooling after a 429 does.
    #[test]
    fn retry_wait_skips_cooldowns_beyond_the_cap_and_non_retryable_statuses() {
        let now = Instant::now();
        let selection = sel("claude");
        let admit_all = |_: &Credential| Some(String::new());
        // One credential per (status, retry-after seconds), each cooling from `now`.
        let wait = |cap: u64, cooldowns: &[(u16, u64)]| {
            let policy = Policy {
                request_retry: 1,
                max_retry_interval: Duration::from_secs(cap),
                ..Policy::default()
            };
            let ids: Vec<String> = (0..cooldowns.len()).map(|i| format!("c{i}.json")).collect();
            let store = CredentialStore::new(ids.iter().map(|id| cred(id, "claude", false)).collect());
            for (id, (status, seconds)) in ids.iter().zip(cooldowns) {
                let mut error = ExecError::local(*status, FailureScope::Model, "cooling");
                error.retry_after = Some(Duration::from_secs(*seconds));
                let credential = store.get(id).unwrap();
                store.scheduler.lock().unwrap().record(
                    &credential,
                    &selection.model,
                    &Outcome::Failure(error),
                    &policy,
                    now,
                );
            }
            store.retry_wait_at(&selection, &policy, 429, &[], &admit_all, now)
        };
        let short_and_long = wait(30, &[(429, 10), (429, 60)]);
        assert!(
            short_and_long.is_some_and(|w| !w.is_zero() && w <= Duration::from_secs(10)),
            "{short_and_long:?}"
        );
        assert_eq!(wait(30, &[(429, 60)]), None, "only a cooldown beyond the cap");
        assert!(wait(3600, &[(429, 60)]).is_some(), "rate limit");
        assert_eq!(wait(3600, &[(402, 60)]), None, "payment required");
        assert_eq!(wait(3600, &[(404, 60)]), None, "not found");
    }

    #[test]
    fn retry_wait_obeys_exact_cap_and_attempted_quota_floor() {
        let store = CredentialStore::new(vec![cred("a.json", "claude", false)]);
        let now = Instant::now();
        let mut selection = sel("claude");
        let admit_all = |_: &Credential| Some(String::new());
        let tried = ["a.json".to_owned()];
        let mut policy = Policy {
            request_retry: 1,
            ..Policy::default()
        };
        // A transport fault (status 0) retries immediately.
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 0, &tried, &admit_all, now),
            Some(Duration::ZERO)
        );
        // An attempted credential after a 429 waits at least 10s, which the default
        // max-retry-interval of 0 forbids; an untried one may go immediately.
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 429, &tried, &admit_all, now),
            None
        );
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 429, &[], &admit_all, now),
            Some(Duration::ZERO)
        );
        policy.max_retry_interval = Duration::from_secs(10);
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 429, &tried, &admit_all, now),
            Some(Duration::from_secs(10))
        );
        let quota = ExecError::local(429, FailureScope::Model, "quota");
        let credential = store.get("a.json").unwrap();
        store.scheduler.lock().unwrap().record(
            &credential,
            &selection.model,
            &Outcome::Failure(quota.clone()),
            &policy,
            now,
        );
        let later = now + Duration::from_millis(1);
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 429, &tried, &admit_all, later),
            Some(Duration::from_secs(10))
        );
        policy.max_retry_interval = Duration::from_secs(9);
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 429, &tried, &admit_all, later),
            None
        );
        policy.disable_cooling = true;
        store.scheduler.lock().unwrap().record(
            &credential,
            &selection.model,
            &Outcome::Failure(quota.clone()),
            &policy,
            later,
        );
        policy.max_retry_interval = Duration::ZERO;
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 429, &tried, &admit_all, later),
            Some(Duration::ZERO),
            "disabled cooling has no floor"
        );
        selection.retry_round = 1;
        assert_eq!(
            store.retry_wait_at(&selection, &policy, 0, &tried, &admit_all, later),
            None
        );
    }

    /// A 429 with a reset six days away (`max-trusted-cooldown` bounds it).
    fn weekly_limit(scope: FailureScope) -> Outcome {
        let mut error = ExecError::local(429, scope, "usage_limit_reached");
        error.retry_after = Some(Duration::from_secs(6 * 24 * 3600));
        Outcome::Failure(error)
    }

    /// A probe whose hold lapsed was taken over by a later pick: the first probe's
    /// cancellation leaves the account reserved for the second, whose own does not.
    #[test]
    fn a_stale_probe_cancellation_keeps_the_newer_reservation() {
        let store = CredentialStore::new(vec![cred("a.json", "claude", false)]);
        let selection = Selection::new("claude", "m");
        let credential = store.get("a.json").unwrap();
        // A bounded window of the 10 s minimum that ended a second ago.
        let policy = Policy {
            max_trusted_cooldown: Duration::from_secs(10),
            ..Policy::default()
        };
        let opened = Instant::now().checked_sub(Duration::from_secs(11)).unwrap();
        store
            .scheduler
            .lock()
            .unwrap()
            .record(&credential, "m", &weekly_limit(FailureScope::Model), &policy, opened);
        let first = store.select(selection.clone()).expect("the probe");
        assert_eq!(first.execution_model, "m");
        assert!(store.select(selection.clone()).is_none(), "reserved");
        // The first probe's hold lapses, and the next pick probes again.
        let key = ("a.json".to_owned(), "m".to_owned());
        store
            .scheduler
            .lock()
            .unwrap()
            .cooldowns
            .get_mut(&key)
            .unwrap()
            .trust
            .probe = Some(Instant::now());
        let second = store.select(selection.clone()).expect("the second probe");
        first.complete(Outcome::Cancelled);
        assert!(store.select(selection.clone()).is_none(), "still reserved");
        second.complete(Outcome::Cancelled);
        assert!(store.select(selection).is_some(), "its own cancellation frees it");
    }

    /// Go 35af74f9 (TestManager_Issue6643_InFlightSuccessesKeepFreshQuotaCooldown):
    /// successes of requests dispatched before a 429 was recorded, whether picked by
    /// selection or by the credits fallback outside it, leave the cooldown; a lease
    /// dispatched again after it (a refresh-and-retry) clears it.
    #[tokio::test]
    async fn successes_dispatched_before_a_cooldown_keep_it() {
        let rt = Arc::new(crate::testing::runtime(
            Config::parse("").unwrap(),
            vec![cred("a.json", "claude", false)],
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        let selection = Selection::new("claude", "m");
        let cfg = rt.config();
        let in_flight = rt.store.select(selection.clone()).unwrap();
        let credits = rt
            .lease_credential("a.json", selection.clone(), &cfg, Credential::clone)
            .await
            .unwrap();
        let mut retried = rt.store.select(selection.clone()).unwrap();
        let mut quota = ExecError::local(429, FailureScope::Model, "rate limited");
        quota.retry_after = Some(Duration::from_secs(3600));
        rt.store
            .select(selection.clone())
            .unwrap()
            .complete(Outcome::Failure(quota));
        assert!(rt.store.select(selection.clone()).is_none(), "cooling");
        in_flight.complete(Outcome::Success);
        assert!(rt.store.select(selection.clone()).is_none(), "a stale success keeps it");
        credits.complete(Outcome::Success);
        assert!(
            rt.store.select(selection.clone()).is_none(),
            "a stale credits success keeps it"
        );
        retried.redispatch();
        retried.complete(Outcome::Success);
        assert!(rt.store.select(selection).is_some(), "a later dispatch clears it");
    }

    /// A request picked before a bounded window opened succeeds after it (a stream that
    /// outlived the 429): its answer is older than the window, which stays, live or
    /// ended, until its own probe.
    #[test]
    fn a_late_success_keeps_a_newer_window() {
        let selection = Selection::new("claude", "m");
        // A model window, opened by a request picked after the stream.
        let store = CredentialStore::new(vec![cred("a.json", "claude", false)]);
        let stream = store.select(selection.clone()).unwrap();
        let other = store.select(selection.clone()).unwrap();
        other.complete(weekly_limit(FailureScope::Model));
        assert!(store.select(selection.clone()).is_none(), "cooling");
        stream.accepted();
        stream.complete(Outcome::Success);
        assert!(store.select(selection.clone()).is_none(), "the window stands");
        // A credential-wide window that already ended keeps its probe.
        let store = CredentialStore::new(vec![cred("a.json", "claude", false)]);
        let stream = store.select(selection.clone()).unwrap();
        let policy = Policy {
            max_trusted_cooldown: Duration::from_secs(10),
            ..Policy::default()
        };
        let opened = Instant::now().checked_sub(Duration::from_secs(11)).unwrap();
        store.scheduler.lock().unwrap().record(
            &store.get("a.json").unwrap(),
            "m",
            &weekly_limit(FailureScope::Credential),
            &policy,
            opened,
        );
        stream.accepted();
        stream.complete(Outcome::Success);
        let _probe = store.select(selection.clone()).expect("the window's probe");
        assert!(store.select(selection).is_none(), "one probe");
    }

    #[test]
    fn config_routing_drives_policy_at_startup_and_on_publish() {
        let executors = || Executors {
            claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
            codex: Default::default(),
            devices: Default::default(),
            openai: Default::default(),
            google: Default::default(),
        };
        // Legacy top-level keys and the canonical routing block both reach the scheduler.
        let rt = crate::testing::runtime(
            Config::parse("request-retry: 2\nrouting:\n  strategy: ff\n  session-affinity-ttl: 250ms\n").unwrap(),
            Vec::new(),
            executors(),
        );
        let policy = rt.policy();
        assert_eq!(policy.strategy, crate::scheduler::Strategy::FillFirst);
        assert_eq!(policy.request_retry, 2);
        assert_eq!(policy.session_affinity_ttl, Duration::from_secs(1));

        rt.publish_config(Config::parse("routing:\n  strategy: wrr\n").unwrap());
        let policy = rt.policy();
        assert_eq!(policy.strategy, crate::scheduler::Strategy::WeightedRoundRobin);
        assert_eq!(policy.request_retry, 0);
        assert_eq!(policy.session_affinity_ttl, Duration::from_secs(3600));
    }

    /// Go `nextModelPoolOffset` (conductor_models.go): per-key cursor, no advance for
    /// single-entry pools or blank keys, reset to zero at the int32 guard.
    #[test]
    fn pool_offsets_rotate_per_key_like_go() {
        let rt = crate::testing::runtime(
            Config::parse("").unwrap(),
            Vec::new(),
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        );
        let offsets: Vec<usize> = (0..4).map(|_| rt.next_pool_offset("a|openai|m", 3)).collect();
        assert_eq!(offsets, [0, 1, 2, 0]);
        assert_eq!(rt.next_pool_offset(" a|openai|m ", 3), 1, "keys are trimmed");
        assert_eq!(rt.next_pool_offset("b|openai|m", 3), 0, "keys rotate independently");
        assert_eq!(rt.next_pool_offset("c", 1), 0);
        assert_eq!(rt.next_pool_offset("c", 2), 0, "a single-entry pool does not advance");
        assert_eq!(rt.next_pool_offset("  ", 2), 0);
        rt.pool_offsets.lock().unwrap().insert("d".into(), 2_147_483_641);
        assert_eq!(rt.next_pool_offset("d", 3), 0, "the guard resets before use");
        assert_eq!(rt.next_pool_offset("d", 3), 1);
    }

    /// Go `Manager.persist` after `MarkResult`: the auth file gains `"disabled": false`
    /// in `json.Marshal` form (sorted keys, float64 numbers, HTML escaping, no newline)
    /// once, and is not rewritten while it already holds that JSON.
    #[test]
    fn first_use_persists_disabled_in_go_marshal_form() {
        let dir = std::env::temp_dir().join(format!(
            "persist-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("a.json");
        let original = "{\"type\":\"claude\",\"email\":\"a<b>@x.invalid\",\"n\":1.50,\"big\":1e3,\"nested\":{\"z\":1,\"a\":[true,null]}}\n";
        std::fs::write(&path, original).unwrap();
        let metadata: Map<String, Value> = serde_json::from_str(original).unwrap();
        let store = CredentialStore::new(vec![Credential::from_file(&dir, &path, metadata).unwrap()]);
        let revision = store.get("a.json").unwrap().revision;
        store
            .select(Selection::new("claude", "m"))
            .unwrap()
            .complete(Outcome::Success);
        let written = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            written,
            r#"{"big":1000,"disabled":false,"email":"a\u003cb\u003e@x.invalid","n":1.5,"nested":{"a":[true,null],"z":1},"type":"claude"}"#
        );
        let current = store.get("a.json").unwrap();
        assert_eq!(current.revision, revision, "a neutral write keeps the revision");
        assert_eq!(current.metadata.get("disabled"), Some(&Value::Bool(false)));
        assert_eq!(current.metadata.get("big"), Some(&Value::from(1000)));
        // The watcher's reload of the written file changes nothing.
        let reloaded: Map<String, Value> = serde_json::from_str(&written).unwrap();
        store.reconcile(vec![Credential::from_file(&dir, &path, reloaded).unwrap()]);
        assert_eq!(store.get("a.json").unwrap().revision, revision);
        // Same JSON in another layout is left alone.
        std::fs::write(&path, "{\"type\":\"claude\", \"disabled\":false}").unwrap();
        let mut metadata = Map::new();
        metadata.insert("type".into(), "claude".into());
        metadata.insert("disabled".into(), false.into());
        store.reconcile(vec![Credential::from_file(&dir, &path, metadata).unwrap()]);
        store
            .select(Selection::new("claude", "m"))
            .unwrap()
            .complete(Outcome::Success);
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "{\"type\":\"claude\", \"disabled\":false}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A result recorded after a refresh committed a newer revision must not write the
    /// older token back (Go persists under the manager lock with generation checks).
    #[test]
    fn stale_result_does_not_overwrite_a_refreshed_credential() {
        let dir = std::env::temp_dir().join(format!(
            "stale-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("a.json");
        std::fs::write(&path, r#"{"type":"claude","access_token":"old"}"#).unwrap();
        let metadata: Map<String, Value> = serde_json::from_str(r#"{"type":"claude","access_token":"old"}"#).unwrap();
        let store = CredentialStore::new(vec![Credential::from_file(&dir, &path, metadata).unwrap()]);
        let stale = store.get("a.json").unwrap();
        let mut patch = MetadataPatch::default();
        patch.set.insert("access_token".into(), "new".into());
        store.apply_patch("a.json", stale.revision, &patch).unwrap();
        let refreshed = std::fs::read_to_string(&path).unwrap();
        store.persist_credential(&stale);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), refreshed);
        assert!(refreshed.contains("\"new\"") && refreshed.contains("\"disabled\":false"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Go `Manager.persist` skips plugin-virtual auths: a refresh of one of the
    /// credentials a plugin parsed from one file commits in memory and leaves the shared
    /// file alone.
    #[test]
    fn a_plugin_virtual_refresh_never_rewrites_the_shared_source_file() {
        let dir = std::env::temp_dir().join(format!("virtual-{}-{}", std::process::id(), line!()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("multi.json");
        let source = r#"{"type":"claude","accounts":[{"access_token":"a"},{"access_token":"b"}]}"#;
        std::fs::write(&path, source).unwrap();
        let metadata: Map<String, Value> = serde_json::from_str(r#"{"type":"claude","access_token":"a"}"#).unwrap();
        let mut credential = Credential::from_file(&dir, &path, metadata).unwrap();
        credential.id = "multi-a".into();
        credential.attributes.insert("plugin_virtual".into(), "true".into());
        let store = CredentialStore::new(vec![credential]);
        let current = store.get("multi-a").unwrap();
        let mut patch = MetadataPatch::default();
        patch.set.insert("access_token".into(), "refreshed".into());
        let committed = store.apply_patch("multi-a", current.revision, &patch).unwrap();
        assert_eq!(committed.metadata["access_token"], "refreshed");
        assert_eq!(store.get("multi-a").unwrap().metadata["access_token"], "refreshed");
        store.persist_credential(&committed);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), source);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Go `save-cooldown-status`: a cooldown change writes `<auth-dir>/<file>.cds`, a new
    /// process restores it, reset clears it, and a file Go wrote restores too.
    #[test]
    fn cooldowns_persist_restore_and_reset_through_cds_files() {
        let dir = std::env::temp_dir().join(format!(
            "cds-rt-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let config = || {
            Config::parse(&format!(
                "auth-dir: {}\nrouting:\n  cooldown:\n    save-cooldown-status: true\n",
                dir.display()
            ))
            .unwrap()
        };
        let creds = || {
            let metadata = |p: &str| {
                let mut m = Map::new();
                m.insert("type".into(), p.into());
                m
            };
            vec![
                Credential::from_file(&dir, &dir.join("a.json"), metadata("claude")).unwrap(),
                Credential::from_file(&dir, &dir.join("b.json"), metadata("claude")).unwrap(),
            ]
        };
        let executors = || Executors {
            claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
            codex: Default::default(),
            openai: Default::default(),
            google: Default::default(),
            devices: Default::default(),
        };
        let rt = crate::testing::runtime(config(), creds(), executors());
        let mut selection = Selection::new("claude", "m1");
        selection.exclude.push("b.json".into());
        let lease = rt.store.select(selection.clone()).unwrap();
        let mut quota = ExecError::local(429, FailureScope::Model, "rate limited");
        quota.retry_after = Some(Duration::from_secs(120));
        lease.complete(Outcome::Failure(quota));
        let file = dir.join("a.cds");
        let written = std::fs::read_to_string(&file).expect("cooldown written");
        #[cfg(unix)]
        assert_eq!(
            std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
            0o600,
            "Go os.CreateTemp mode"
        );
        assert!(
            written.contains("\"model\": \"m1\"") && written.contains("\"reason\": \"quota\""),
            "{written}"
        );
        assert!(!dir.join("b.cds").exists());
        // A successful attempt on another credential changes no cooldown: no rewrite.
        let modified = std::fs::metadata(&file).unwrap().modified().unwrap();
        let mut other = Selection::new("claude", "m1");
        other.exclude.push("a.json".into());
        rt.store.select(other).unwrap().complete(Outcome::Success);
        assert_eq!(std::fs::metadata(&file).unwrap().modified().unwrap(), modified);

        // A new process restores the cooldown.
        drop(rt);
        let rt = crate::testing::runtime(config(), creds(), executors());
        let a = rt.store.get("a.json").unwrap();
        let wait = rt
            .store
            .scheduler
            .lock()
            .unwrap()
            .wait(&a, "m1", Instant::now())
            .unwrap();
        assert!(
            wait > Duration::from_secs(100) && wait <= Duration::from_secs(120),
            "{wait:?}"
        );
        assert_eq!(rt.store.reset_cooldown("a.json"), ["m1"]);
        assert!(!file.exists(), "reset removes the stale file");

        // A file CLIProxyAPI wrote (local time with an offset) restores model and
        // credential-wide quota records; an expired record is dropped on rewrite.
        let at = |secs: i64| {
            (chrono::Utc::now() + chrono::Duration::seconds(secs))
                .with_timezone(&chrono::FixedOffset::east_opt(7200).unwrap())
                .to_rfc3339_opts(chrono::SecondsFormat::Nanos, false)
        };
        let go = format!(
            r#"{{"version":1,"auth_id":"b.json","provider":"claude","updated_at":"{now}","records":[
{{"provider":"claude","auth_id":"b.json","status":"cooling","next_retry_after":"{late}","reason":"credential_quota","quota":{{"exceeded":true,"reason":"credential_quota","next_recover_at":"{late}","observed_at":"0001-01-01T00:00:00Z"}},"last_error":{{"message":"credential quota","retryable":false,"http_status":429}},"updated_at":"{now}"}},
{{"provider":"claude","auth_id":"b.json","model":"m2","status":"cooling","next_retry_after":"{soon}","reason":"unauthorized","quota":{{"exceeded":false,"next_recover_at":"0001-01-01T00:00:00Z","observed_at":"0001-01-01T00:00:00Z"}},"last_error":{{"message":"unauthorized","retryable":false,"http_status":401}},"updated_at":"{now}"}},
{{"provider":"claude","auth_id":"b.json","model":"m4","status":"cooling","next_retry_after":"{soon}","reason":"quota","quota":{{"exceeded":true,"reason":"quota","next_recover_at":"{late}","observed_at":"0001-01-01T00:00:00Z"}},"updated_at":"{now}"}},
{{"provider":"claude","auth_id":"b.json","model":"m5","status":"cooling","next_retry_after":"{past}","reason":"quota","quota":{{"exceeded":true,"reason":"quota","next_recover_at":"{late}","observed_at":"0001-01-01T00:00:00Z"}},"updated_at":"{now}"}},
{{"provider":"claude","auth_id":"b.json","model":"m3","status":"cooling","next_retry_after":"{past}","reason":"boom","quota":{{"exceeded":false,"next_recover_at":"0001-01-01T00:00:00Z","observed_at":"0001-01-01T00:00:00Z"}},"updated_at":"{now}"}},
{{"provider":"claude","auth_id":"gone.json","model":"m1","status":"cooling","next_retry_after":"{late}","quota":{{"exceeded":false,"next_recover_at":"0001-01-01T00:00:00Z","observed_at":"0001-01-01T00:00:00Z"}},"updated_at":"{now}"}}]}}"#,
            now = at(0),
            late = at(600),
            soon = at(60),
            past = at(-5),
        );
        std::fs::write(dir.join("b.cds"), go).unwrap();
        drop(rt);
        let rt = crate::testing::runtime(config(), creds(), executors());
        let b = rt.store.get("b.json").unwrap();
        let now = Instant::now();
        let scheduler = rt.store.scheduler.lock().unwrap();
        let wait = |m: &str| scheduler.wait(&b, m, now).unwrap_or_default().as_secs();
        assert!((590..=600).contains(&wait("m9")), "credential quota blocks every model");
        assert!(scheduler.quota_cooling(&b, "m9", now));
        let records = scheduler.records(&b, now, std::time::SystemTime::now());
        drop(scheduler);
        let models: Vec<&str> = records.iter().map(|r| r.model.as_str()).collect();
        assert_eq!(
            models,
            ["", "m2", "m4"],
            "expired (by retry deadline) and unknown-credential records are dropped"
        );
        let m4 = records.iter().find(|r| r.model == "m4").unwrap();
        let left = m4
            .next_retry_after
            .unwrap()
            .duration_since(std::time::SystemTime::now())
            .unwrap();
        assert!(
            left > Duration::from_secs(590),
            "the later quota recovery wins: {left:?}"
        );
        let rewritten = std::fs::read_to_string(dir.join("b.cds")).unwrap();
        assert!(!rewritten.contains("gone.json") && !rewritten.contains("\"m3\""));

        // Turning the option off persists the final state and stops writing.
        rt.publish_config(Config::parse(&format!("auth-dir: {}\n", dir.display())).unwrap());
        rt.store.reset_cooldown("b.json");
        assert!(dir.join("b.cds").exists(), "no writes once disabled");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn preparation_waiter_observes_deletion_and_refresh_loop_is_replaceable() {
        let rt = Arc::new(crate::testing::runtime(
            Config::parse("").unwrap(),
            vec![cred("a.json", "claude", false)],
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        let lock = rt.store.prepare_lock("a.json");
        let guard = lock.lock().await;
        let worker = {
            let rt = rt.clone();
            tokio::spawn(async move { rt.prepare_credential("a.json", &rt.config(), None).await })
        };
        tokio::task::yield_now().await;
        assert!(!worker.is_finished());
        rt.store.reconcile(Vec::new());
        drop(guard);
        let error = worker.await.unwrap().unwrap_err();
        assert_eq!(error.scope, FailureScope::Request);
        assert!(rt.store.snapshot().is_empty());
        rt.start_auto_refresh();
        let first = rt.refresh_task.lock().unwrap().clone().unwrap();
        rt.start_auto_refresh();
        tokio::task::yield_now().await;
        assert!(first.is_finished());
        let second = rt.refresh_task.lock().unwrap().clone().unwrap();
        rt.stop_auto_refresh();
        tokio::task::yield_now().await;
        assert!(second.is_finished());
        assert!(rt.refresh_task.lock().unwrap().is_none());
    }

    /// A refresh whose caller is cancelled while its commit waits keeps the preparation
    /// lock until the commit returns: a writer that serializes on the lock (an SIWC
    /// binding) lands after the rotated tokens instead of making them stale.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_cancelled_refresh_holds_the_preparation_lock_through_its_commit() {
        let (hit_tx, mut hit) = tokio::sync::mpsc::unbounded_channel();
        let answer = Arc::new(tokio::sync::Semaphore::new(0));
        let app = axum::Router::new().route(
            "/oauth/token",
            axum::routing::post({
                let answer = answer.clone();
                move || async move {
                    hit_tx.send(()).unwrap();
                    answer.acquire().await.unwrap().forget();
                    r#"{"access_token":"rotated","refresh_token":"rotated-rt","expires_in":3600}"#
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let token_url = format!("http://{}/oauth/token", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!("cpa-prepare-cancel-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("codex.json");
        std::fs::write(
            &path,
            r#"{"type":"codex","access_token":"outer","refresh_token":"outer-rt"}"#,
        )
        .unwrap();
        let mut cfg = Config::parse("").unwrap();
        cfg.auth_dir = dir.clone();
        let client = wreq::Client::new();
        let oauth =
            cpa_exec::codex_oauth::CodexOAuth::with_endpoints(client.clone(), &token_url, &token_url, &token_url);
        let rt = Arc::new(crate::testing::runtime(
            cfg.clone(),
            cpa_core::config::credentials::from_auth_dir(&cfg)
                .into_iter()
                .map(crate::testing::local)
                .collect(),
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: cpa_exec::codex::CodexExecutor::with_client(client, oauth),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        let refresh = tokio::spawn({
            let rt = rt.clone();
            async move { rt.refresh_credential("codex.json").await }
        });
        if tokio::time::timeout(Duration::from_secs(5), hit.recv()).await.is_err() {
            panic!("no refresh request: {:?}", refresh.await);
        }
        // Hold the store so the refresh's commit job blocks inside `apply_patch`, then
        // let the token response through and cancel the caller while the job waits.
        let (held_tx, held) = std::sync::mpsc::channel();
        let (release, release_rx) = std::sync::mpsc::channel::<()>();
        let holder = std::thread::spawn({
            let store = rt.store.clone();
            move || {
                let _inner = store.inner.write().unwrap();
                held_tx.send(()).unwrap();
                release_rx.recv().unwrap();
            }
        });
        held.recv().unwrap();
        answer.add_permits(1);
        tokio::time::sleep(Duration::from_millis(500)).await;
        refresh.abort();
        assert!(refresh.await.unwrap_err().is_cancelled());
        let lock = rt.store.prepare_lock("codex.json");
        assert!(
            tokio::time::timeout(Duration::from_millis(300), lock.clone().lock_owned())
                .await
                .is_err(),
            "the detached commit still holds the lock"
        );
        release.send(()).unwrap();
        holder.join().unwrap();
        let _binding = tokio::time::timeout(Duration::from_secs(5), lock.lock_owned())
            .await
            .unwrap();
        let current = rt.store.get("codex.json").unwrap();
        assert_eq!(current.str("access_token"), Some("rotated"));
        let mut patch = MetadataPatch::default();
        patch.set.insert("use_siwc".into(), true.into());
        let bound = rt.store.apply_patch("codex.json", current.revision, &patch).unwrap();
        let disk: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        for meta in [&disk, &Value::Object(bound.metadata.clone())] {
            assert_eq!(
                (&meta["access_token"], &meta["refresh_token"], &meta["use_siwc"]),
                (
                    &serde_json::json!("rotated"),
                    &serde_json::json!("rotated-rt"),
                    &serde_json::json!(true)
                ),
                "{meta}"
            );
        }
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// Go 935aa6e3 (TestManager_RefreshAuth_DropsStaleConcurrentCredential): tokens saved
    /// while a refresh is in flight win over its result, in memory and on disk, and the
    /// refresh answers with them. An edit that leaves the credentials alone is merged with
    /// the refresh (Go `MergeRefreshedAuth`), so a rotated refresh token is not lost and a
    /// field the refresh did not change keeps the edit.
    #[tokio::test]
    async fn an_in_flight_refresh_does_not_overwrite_newer_credentials() {
        for (edit, want) in [
            (
                serde_json::json!({"access_token": "saved", "refresh_token": "saved-rt"}),
                ("saved", "saved-rt", None, "free"),
            ),
            (
                serde_json::json!({"note": "kept"}),
                ("rotated", "rotated-rt", Some("kept"), "free"),
            ),
            // The refresh leaves the plan as it was, so the edit stands.
            (
                serde_json::json!({"plan_type": "team"}),
                ("rotated", "rotated-rt", None, "team"),
            ),
        ] {
            let (hit_tx, mut hit) = tokio::sync::mpsc::unbounded_channel();
            let answer = Arc::new(tokio::sync::Semaphore::new(0));
            let app = axum::Router::new().route(
                "/oauth/token",
                axum::routing::post({
                    let answer = answer.clone();
                    move || async move {
                        hit_tx.send(()).unwrap();
                        answer.acquire().await.unwrap().forget();
                        r#"{"access_token":"rotated","refresh_token":"rotated-rt","expires_in":3600}"#
                    }
                }),
            );
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let token_url = format!("http://{}/oauth/token", listener.local_addr().unwrap());
            tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
            let dir = std::env::temp_dir().join(format!("cpa-refresh-stale-{}", uuid::Uuid::new_v4()));
            std::fs::create_dir_all(&dir).unwrap();
            let path = dir.join("codex.json");
            std::fs::write(
                &path,
                r#"{"type":"codex","access_token":"outer","refresh_token":"outer-rt","plan_type":"free"}"#,
            )
            .unwrap();
            let mut cfg = Config::parse("").unwrap();
            cfg.auth_dir = dir.clone();
            let client = wreq::Client::new();
            let oauth =
                cpa_exec::codex_oauth::CodexOAuth::with_endpoints(client.clone(), &token_url, &token_url, &token_url);
            let rt = Arc::new(crate::testing::runtime(
                cfg.clone(),
                cpa_core::config::credentials::from_auth_dir(&cfg)
                    .into_iter()
                    .map(crate::testing::local)
                    .collect(),
                Executors {
                    claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                    codex: cpa_exec::codex::CodexExecutor::with_client(client, oauth),
                    devices: Default::default(),
                    openai: Default::default(),
                    google: Default::default(),
                },
            ));
            let refresh = tokio::spawn({
                let rt = rt.clone();
                async move { rt.refresh_credential("codex.json").await }
            });
            tokio::time::timeout(Duration::from_secs(5), hit.recv())
                .await
                .expect("a refresh request");
            let mut patch = MetadataPatch::default();
            for (k, v) in edit.as_object().unwrap() {
                patch.set.insert(k.clone(), v.clone());
            }
            let before = rt.store.get("codex.json").unwrap().revision;
            rt.store.apply_patch("codex.json", before, &patch).unwrap();
            answer.add_permits(1);
            let answered = refresh.await.unwrap().expect("the refresh answers");
            let current = rt.store.get("codex.json").unwrap();
            let disk: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
            for meta in [
                &disk,
                &Value::Object(current.metadata.clone()),
                &Value::Object(answered.metadata.clone()),
            ] {
                assert_eq!(
                    (
                        meta["access_token"].as_str().unwrap(),
                        meta["refresh_token"].as_str().unwrap(),
                        meta["note"].as_str(),
                        meta["plan_type"].as_str().unwrap()
                    ),
                    want,
                    "{edit}: {meta}"
                );
            }
            std::fs::remove_dir_all(dir).unwrap();
        }
    }

    /// A runtime over Codex credential files in a private auth-dir, refreshing against a
    /// loopback mock that records each grant as (partition, refresh token, client ID).
    struct CodexDisk {
        rt: Arc<Runtime>,
        dir: std::path::PathBuf,
        grants: Arc<Mutex<Grants>>,
        /// Each grant takes a permit before the mock answers.
        gate: Arc<tokio::sync::Semaphore>,
        base: String,
    }

    type Grants = Vec<(&'static str, String, String)>;

    impl CodexDisk {
        async fn new(files: &[(&str, &Value)]) -> Self {
            Self::gated(files, 1000).await
        }

        async fn gated(files: &[(&str, &Value)], permits: usize) -> Self {
            let grants = Arc::new(Mutex::new(Vec::new()));
            let gate = Arc::new(tokio::sync::Semaphore::new(permits));
            let route = |partition: &'static str, answer: &'static str| {
                let (grants, gate) = (grants.clone(), gate.clone());
                axum::routing::post(move |body: String| async move {
                    let field = |key: &str| {
                        url::form_urlencoded::parse(body.as_bytes())
                            .find(|(k, _)| k == key)
                            .map(|(_, v)| v.into_owned())
                            .unwrap_or_default()
                    };
                    grants
                        .lock()
                        .unwrap()
                        .push((partition, field("refresh_token"), field("client_id")));
                    gate.acquire().await.unwrap().forget();
                    answer
                })
            };
            let app = axum::Router::new()
                .route(
                    "/oauth/token",
                    route(
                        "outer",
                        r#"{"access_token":"outer-access-refreshed","refresh_token":"outer-ref-refreshed","expires_in":864000}"#,
                    ),
                )
                .route(
                    "/siwc/token",
                    route(
                        "siwc",
                        r#"{"access_token":"siwc-access-refreshed","refresh_token":"siwc-ref-refreshed","scope":"openid chatgpt.tokens.use.direct","expires_in":3600}"#,
                    ),
                );
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let base = format!("http://{}", listener.local_addr().unwrap());
            tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
            let dir = std::env::temp_dir().join(format!("cpa-codex-disk-{}", uuid::Uuid::new_v4()));
            std::fs::create_dir_all(&dir).unwrap();
            for (name, body) in files {
                std::fs::write(dir.join(name), body.to_string()).unwrap();
            }
            let rt = Self::runtime(&dir, &base);
            Self {
                rt,
                dir,
                grants,
                gate,
                base,
            }
        }

        /// A runtime over the auth-dir as it is now, with its own refresh coordination:
        /// another process sharing the files and the mock.
        fn other_process(&self) -> Arc<Runtime> {
            Self::runtime(&self.dir, &self.base)
        }

        fn runtime(dir: &Path, base: &str) -> Arc<Runtime> {
            let mut cfg = Config::parse("").unwrap();
            cfg.auth_dir = dir.to_owned();
            let client = wreq::Client::new();
            let oauth = cpa_exec::codex_oauth::CodexOAuth::with_endpoints(
                client.clone(),
                &format!("{base}/oauth/token"),
                "",
                "",
            )
            .with_siwc_token_url(&format!("{base}/siwc/token"))
            .with_retry_delay(Duration::from_millis(1));
            Arc::new(crate::testing::runtime(
                cfg.clone(),
                cpa_core::config::credentials::from_auth_dir(&cfg)
                    .into_iter()
                    .map(crate::testing::local)
                    .collect(),
                Executors {
                    claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                    codex: cpa_exec::codex::CodexExecutor::with_client(client, oauth),
                    devices: Default::default(),
                    openai: Default::default(),
                    google: Default::default(),
                },
            ))
        }

        /// Waits until `n` refreshes in all went to lock this auth-dir's `name`.
        async fn lock_attempts(&self, name: &str, n: usize) {
            let path = self.dir.join(name);
            let attempted = async {
                while LOCK_ATTEMPTS.lock().unwrap().iter().filter(|p| **p == path).count() < n {
                    tokio::time::sleep(Duration::from_millis(5)).await;
                }
            };
            tokio::time::timeout(Duration::from_secs(5), attempted)
                .await
                .expect("the refresh went to lock the file");
        }

        /// Waits until a grant reached the mock.
        async fn granted(&self) {
            let granted = async {
                while self.grants.lock().unwrap().is_empty() {
                    tokio::time::sleep(Duration::from_millis(5)).await;
                }
            };
            tokio::time::timeout(Duration::from_secs(5), granted)
                .await
                .expect("a grant");
        }

        fn grants(&self) -> Grants {
            std::mem::take(&mut *self.grants.lock().unwrap())
        }

        /// The file and the stored credential, which must agree on `fields`.
        fn tokens(&self, name: &str, fields: &[&str]) -> Vec<Value> {
            let disk: Value = serde_json::from_slice(&std::fs::read(self.dir.join(name)).unwrap()).unwrap();
            let stored = Value::Object(self.rt.store.get(name).unwrap().metadata.clone());
            let pick = |m: &Value| {
                fields
                    .iter()
                    .map(|f| m.pointer(f).cloned().unwrap_or(Value::Null))
                    .collect()
            };
            let (disk, stored): (Vec<Value>, Vec<Value>) = (pick(&disk), pick(&stored));
            assert_eq!(disk, stored, "file and store differ");
            disk
        }
    }

    fn codex_file(outer: (&str, chrono::Duration), siwc: (&str, &str, chrono::Duration)) -> Value {
        let now = chrono::Utc::now();
        serde_json::json!({
            "type": "codex",
            "access_token": format!("outer-{}", outer.0),
            "refresh_token": format!("outer-ref-{}", outer.0),
            "expired": (now + outer.1).to_rfc3339(),
            "use_siwc": true,
            "siwc": {
                "access_token": format!("siwc-{}", siwc.0),
                "refresh_token": format!("siwc-ref-{}", siwc.0),
                "client_id": siwc.1,
                "device_id": "e61bbe28-07ef-466d-8e5d-a344f94ab305",
                "expired": (now + siwc.2).to_rfc3339(),
            },
        })
    }

    /// A shutdown that lands while a credential lock wait sleeps stops it, even when
    /// the lock comes free and the sleep ends at the same moment: no lock is taken (and
    /// no grant started) after shutdown. Polled by hand, so both are ready at once.
    #[tokio::test(start_paused = true)]
    async fn a_lock_wait_stops_at_shutdown_even_when_the_lock_frees() {
        let dir = std::env::temp_dir().join(format!("cpa-lock-wait-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("codex.json");
        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
        for _ in 0..32 {
            let held = cpa_exec::codex_siwc_bind::lock_file(&path).unwrap();
            let shutdown = tokio_util::sync::CancellationToken::new();
            let mut wait = std::pin::pin!(wait_codex_lock(&path, &shutdown));
            assert!(wait.as_mut().poll(&mut cx).is_pending(), "the lock is held");
            drop(held);
            tokio::time::advance(LOCK_POLL_CEILING).await;
            shutdown.cancel();
            let std::task::Poll::Ready(waited) = wait.as_mut().poll(&mut cx) else {
                panic!("the wait ends");
            };
            assert_eq!(waited.map(drop), Err(LOCK_WAIT_STOPPED.to_owned()));
        }
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// Go `TestCodexExecutorRefreshSerializesUnderFileLockAndSkipsAlreadyRotatedToken`
    /// (7b0319fb): a due refresh waits while another process holds the file's credential
    /// lock, then reads the file: the Sign in with ChatGPT partition that process rotated
    /// is adopted, in memory and on disk, and its refresh token is not spent again.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_waits_for_the_file_lock_and_adopts_what_another_process_rotated() {
        let (days, minutes) = (chrono::Duration::days(5), chrono::Duration::minutes(2));
        let f = CodexDisk::new(&[(
            "codex.json",
            &codex_file(("keep", days), ("old", "oaiapp_shared", minutes)),
        )])
        .await;
        let path = f.dir.join("codex.json");
        let (locked_tx, locked) = std::sync::mpsc::channel();
        let (release_tx, release) = std::sync::mpsc::channel::<()>();
        let other = std::thread::spawn({
            let path = path.clone();
            move || {
                let lock = cpa_exec::codex_siwc_bind::lock_file(&path).unwrap();
                locked_tx.send(()).unwrap();
                release.recv().unwrap();
                let rotated = codex_file(("keep", days), ("other", "oaiapp_shared", chrono::Duration::hours(1)));
                std::fs::write(&path, rotated.to_string()).unwrap();
                drop(lock);
            }
        });
        locked.recv().unwrap();
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.lock_attempts("codex.json", 1).await;
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(!refresh.is_finished(), "the refresh waits for the lock");
        assert_eq!(f.grants(), [], "nothing refreshes under another process's lock");
        release_tx.send(()).unwrap();
        other.join().unwrap();
        tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(f.grants(), [], "the rotated token is not refreshed again");
        assert_eq!(
            f.tokens(
                "codex.json",
                &["/access_token", "/siwc/access_token", "/siwc/refresh_token"]
            ),
            ["outer-keep", "siwc-other", "siwc-ref-other"]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// The A→B→C case of the same Go test: memory holds version A, the file version B,
    /// both due. The refresh spends B's refresh tokens (and B's client ID), and C reaches
    /// memory and disk.
    #[tokio::test]
    async fn a_codex_refresh_spends_the_tokens_on_disk_not_the_stale_snapshot() {
        let hour = chrono::Duration::hours(1);
        let minute = chrono::Duration::minutes(1);
        let f = CodexDisk::new(&[("codex.json", &codex_file(("A", hour), ("A", "oaiapp_A", minute)))]).await;
        let disk_b = codex_file(("B", hour), ("B", "oaiapp_B", minute));
        std::fs::write(f.dir.join("codex.json"), disk_b.to_string()).unwrap();
        f.rt.prepare_credential("codex.json", &f.rt.config(), None)
            .await
            .unwrap();
        assert_eq!(
            f.grants(),
            [
                (
                    "outer",
                    "outer-ref-B".to_owned(),
                    cpa_exec::codex_oauth::CLIENT_ID.to_owned()
                ),
                ("siwc", "siwc-ref-B".to_owned(), "oaiapp_B".to_owned()),
            ]
        );
        assert_eq!(
            f.tokens(
                "codex.json",
                &[
                    "/access_token",
                    "/refresh_token",
                    "/siwc/access_token",
                    "/siwc/client_id"
                ]
            ),
            [
                "outer-access-refreshed",
                "outer-ref-refreshed",
                "siwc-access-refreshed",
                "oaiapp_B"
            ]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// The A→B→C case when the watcher loads B while B refreshes: the commit merges
    /// against B, the tokens the refresh started from, so C is kept, not dropped as a
    /// stale refresh of A.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_keeps_its_result_when_the_watcher_loads_the_adopted_tokens() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::gated(
            &[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_A", minute)))],
            0,
        )
        .await;
        let disk_b = codex_file(("keep", days), ("B", "oaiapp_B", minute));
        std::fs::write(f.dir.join("codex.json"), disk_b.to_string()).unwrap();
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        // The watcher's reload of B, while the grant for B is in flight.
        let mut reload = MetadataPatch::default();
        reload.set.insert("siwc".into(), disk_b["siwc"].clone());
        let revision = f.rt.store.get("codex.json").unwrap().revision;
        f.rt.store.apply_patch("codex.json", revision, &reload).unwrap();
        f.gate.add_permits(1);
        tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(f.grants(), [("siwc", "siwc-ref-B".to_owned(), "oaiapp_B".to_owned())]);
        assert_eq!(
            f.tokens("codex.json", &["/siwc/access_token", "/siwc/refresh_token"]),
            ["siwc-access-refreshed", "siwc-ref-refreshed"]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A file whose `type` is spelled differently from the provider it loaded as
    /// (`Codex`) still takes an adopted outer partition: the stored spelling stays.
    #[tokio::test]
    async fn a_codex_refresh_adopts_a_rotated_file_whatever_its_type_spelling() {
        let (days, hour) = (chrono::Duration::days(5), chrono::Duration::hours(1));
        let mut file = codex_file(("A", days), ("keep", "oaiapp_x", hour));
        file["type"] = "Codex".into();
        file["use_siwc"] = false.into();
        let f = CodexDisk::new(&[("codex.json", &file)]).await;
        let mut rotated = file.clone();
        rotated["access_token"] = "outer-B".into();
        rotated["refresh_token"] = "outer-ref-B".into();
        std::fs::write(f.dir.join("codex.json"), rotated.to_string()).unwrap();
        let current = f.rt.store.get("codex.json").unwrap();
        let cfg = f.rt.config();
        assert!(f.rt.refresh_after_unauthorized(&current, &cfg).await.is_some());
        assert_eq!(f.grants(), []);
        assert_eq!(
            f.tokens("codex.json", &["/type", "/access_token", "/refresh_token"]),
            ["Codex", "outer-B", "outer-ref-B"]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// After a 401 on the Sign in with ChatGPT token, a file whose partition another
    /// process already rotated is adopted without forcing a refresh of the new token
    /// (Go `RejectedAccessToken` names the old one). A file that is not valid JSON fails
    /// the refresh before any grant (Go: "invalid credential JSON").
    #[tokio::test]
    async fn a_rejected_codex_token_adopts_a_rotated_file_and_a_corrupt_file_refreshes_nothing() {
        let (days, hour) = (chrono::Duration::days(5), chrono::Duration::hours(1));
        let f = CodexDisk::new(&[(
            "codex.json",
            &codex_file(("keep", days), ("rejected", "oaiapp_x", hour)),
        )])
        .await;
        let path = f.dir.join("codex.json");
        std::fs::write(
            &path,
            codex_file(("keep", days), ("other", "oaiapp_x", hour)).to_string(),
        )
        .unwrap();
        let cfg = f.rt.config();
        let current = f.rt.store.get("codex.json").unwrap();
        let refreshed = f.rt.refresh_after_unauthorized(&current, &cfg).await.expect("adopted");
        assert_eq!(f.grants(), []);
        assert_eq!(refreshed.metadata["siwc"]["access_token"], "siwc-other");
        assert_eq!(
            f.tokens("codex.json", &["/siwc/access_token", "/siwc/refresh_token"]),
            ["siwc-other", "siwc-ref-other"]
        );
        std::fs::write(&path, "{corrupt").unwrap();
        assert!(f.rt.refresh_after_unauthorized(&refreshed, &cfg).await.is_none());
        assert_eq!(f.grants(), []);
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// The commit takes the partition as the file held it under the lock as well as the
    /// snapshot's (Go `matchesBaselineOrAfter`): memory holds A and is edited while the
    /// refresh waits for another process, which rotates the file to B. C, refreshed from
    /// B, lands over B with the edit kept, instead of being dropped as a refresh of an A
    /// that changed meanwhile, which would leave B's spent refresh token on disk.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_of_an_adopted_partition_lands_after_an_edit_to_the_snapshot() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::new(&[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", minute)))]).await;
        let path = f.dir.join("codex.json");
        let (locked_tx, locked) = std::sync::mpsc::channel();
        let (release_tx, release) = std::sync::mpsc::channel::<()>();
        let other = std::thread::spawn({
            let path = path.clone();
            move || {
                let lock = cpa_exec::codex_siwc_bind::lock_file(&path).unwrap();
                locked_tx.send(()).unwrap();
                release.recv().unwrap();
                let mut rotated = codex_file(("keep", days), ("B", "oaiapp_x", minute));
                rotated["priority"] = 7.into();
                std::fs::write(&path, rotated.to_string()).unwrap();
                drop(lock);
            }
        });
        locked.recv().unwrap();
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.lock_attempts("codex.json", 1).await;
        // An edit of A that keeps its tokens (the watcher, a management save).
        let mut edit = MetadataPatch::default();
        edit.set.insert("priority".into(), 7.into());
        let revision = f.rt.store.get("codex.json").unwrap().revision;
        f.rt.store.apply_patch("codex.json", revision, &edit).unwrap();
        release_tx.send(()).unwrap();
        other.join().unwrap();
        tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(f.grants(), [("siwc", "siwc-ref-B".to_owned(), "oaiapp_x".to_owned())]);
        assert_eq!(
            f.tokens(
                "codex.json",
                &["/siwc/access_token", "/siwc/refresh_token", "/priority"]
            ),
            [
                Value::from("siwc-access-refreshed"),
                Value::from("siwc-ref-refreshed"),
                Value::from(7)
            ]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A refresh whose caller is cancelled once its grant is sent keeps the file's
    /// credential lock until the new tokens are written (Go `refreshLocked` writes before
    /// `WithFileLock` returns): another process waiting on the lock then reads them and
    /// does not spend the old refresh token again.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_cancelled_codex_refresh_writes_its_tokens_before_another_process_reads_the_file() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::gated(
            &[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", minute)))],
            0,
        )
        .await;
        let other = f.other_process();
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        refresh.abort();
        assert!(refresh.await.unwrap_err().is_cancelled());
        let waiting = tokio::spawn({
            let other = other.clone();
            async move { other.prepare_credential("codex.json", &other.config(), None).await }
        });
        f.lock_attempts("codex.json", 2).await;
        f.gate.add_permits(10);
        let adopted = tokio::time::timeout(Duration::from_secs(5), waiting)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(f.grants(), [("siwc", "siwc-ref-A".to_owned(), "oaiapp_x".to_owned())]);
        assert_eq!(adopted.metadata["siwc"]["refresh_token"], "siwc-ref-refreshed");
        assert_eq!(
            f.tokens("codex.json", &["/siwc/access_token", "/siwc/refresh_token"]),
            ["siwc-access-refreshed", "siwc-ref-refreshed"]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// Fields other than the refreshed tokens are written as the file holds them under
    /// the lock (Go applies the refresh patch to the file it reads again): a credential
    /// disabled in the file, not yet reloaded, stays disabled after a refresh of the
    /// tokens it adopted from that file.
    #[tokio::test]
    async fn a_codex_refresh_keeps_a_disabled_flag_it_finds_in_the_file() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::new(&[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", minute)))]).await;
        let mut disk_b = codex_file(("keep", days), ("B", "oaiapp_x", minute));
        disk_b["disabled"] = true.into();
        std::fs::write(f.dir.join("codex.json"), disk_b.to_string()).unwrap();
        let refreshed =
            f.rt.prepare_credential("codex.json", &f.rt.config(), None)
                .await
                .unwrap();
        assert_eq!(f.grants(), [("siwc", "siwc-ref-B".to_owned(), "oaiapp_x".to_owned())]);
        assert!(refreshed.disabled);
        assert_eq!(
            f.tokens("codex.json", &["/disabled", "/siwc/access_token"]),
            [Value::Bool(true), Value::from("siwc-access-refreshed")]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// After a 401, a file that rotated only the refresh token of the partition requests
    /// use still holds the rejected access token, so the refresh is forced, with the
    /// file's refresh token (Go compares the adopted access token with
    /// `RejectedAccessToken`). Both partitions.
    #[tokio::test]
    async fn a_rejected_codex_token_refreshes_when_the_file_rotated_only_its_refresh_token() {
        let (days, hour) = (chrono::Duration::days(5), chrono::Duration::hours(1));
        for use_siwc in [true, false] {
            let mut file = codex_file(("A", days), ("A", "oaiapp_x", hour));
            file["use_siwc"] = use_siwc.into();
            let f = CodexDisk::new(&[("codex.json", &file)]).await;
            let (prefix, client) = match use_siwc {
                true => ("siwc", "oaiapp_x"),
                false => ("outer", cpa_exec::codex_oauth::CLIENT_ID),
            };
            let pointer = if use_siwc {
                "/siwc/refresh_token"
            } else {
                "/refresh_token"
            };
            *file.pointer_mut(pointer).unwrap() = format!("{prefix}-ref-B").into();
            std::fs::write(f.dir.join("codex.json"), file.to_string()).unwrap();
            let current = f.rt.store.get("codex.json").unwrap();
            let cfg = f.rt.config();
            let refreshed = f.rt.refresh_after_unauthorized(&current, &cfg).await;
            assert_eq!(
                f.grants(),
                [(
                    if use_siwc { "siwc" } else { "outer" },
                    format!("{prefix}-ref-B"),
                    client.to_owned()
                )],
                "use_siwc {use_siwc}"
            );
            let access = if use_siwc {
                "/siwc/access_token"
            } else {
                "/access_token"
            };
            let refreshed = Value::Object(refreshed.expect("refreshed").metadata.clone());
            assert_eq!(
                refreshed.pointer(access).unwrap(),
                &format!("{prefix}-access-refreshed")
            );
            assert_eq!(
                f.tokens("codex.json", &[access]),
                [format!("{prefix}-access-refreshed")]
            );
            std::fs::remove_dir_all(&f.dir).unwrap();
        }
    }

    /// A credential file removed while the refresh waits for its lock fails the refresh
    /// before any grant (Go: "read credential file").
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_fails_when_its_file_is_removed_while_it_waits_for_the_lock() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::new(&[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", minute)))]).await;
        let path = f.dir.join("codex.json");
        let (locked_tx, locked) = std::sync::mpsc::channel();
        let (release_tx, release) = std::sync::mpsc::channel::<()>();
        let other = std::thread::spawn({
            let path = path.clone();
            move || {
                let lock = cpa_exec::codex_siwc_bind::lock_file(&path).unwrap();
                locked_tx.send(()).unwrap();
                release.recv().unwrap();
                std::fs::remove_file(&path).unwrap();
                drop(lock);
            }
        });
        locked.recv().unwrap();
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.lock_attempts("codex.json", 1).await;
        release_tx.send(()).unwrap();
        other.join().unwrap();
        let result = tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap();
        assert!(result.is_err(), "{result:?}");
        assert_eq!(f.grants(), []);
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// The commit applies a partition over the snapshot's version too (Go
    /// `matchesBaselineOrAfter`): memory holds A, the refresh reads B under the lock and
    /// spends B's outer refresh token, and a writer that does not take the lock puts A
    /// back meanwhile. B's adopted Sign in with ChatGPT partition then lands over A, its
    /// numbers written as Go's float64 reading of them, and legacy keys renamed.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_lands_over_the_snapshot_tokens_restored_while_it_ran() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let file_a = codex_file(("A", minute), ("A", "oaiapp_x", days));
        let f = CodexDisk::gated(&[("codex.json", &file_a)], 0).await;
        let path = f.dir.join("codex.json");
        let mut file_b = codex_file(("A", minute), ("B", "oaiapp_x", days));
        file_b["siwc"]["expired"] = serde_json::from_str("9007199254740993").unwrap();
        file_b["siwc"]["last_refresh"] = serde_json::from_str("2000000000.0").unwrap();
        std::fs::write(&path, serde_json::to_string(&file_b).unwrap()).unwrap();
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        let mut restored = file_a.clone();
        restored["openapi-location"] = "x".into();
        std::fs::write(&path, restored.to_string()).unwrap();
        f.gate.add_permits(1);
        tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(
            f.grants(),
            [(
                "outer",
                "outer-ref-A".to_owned(),
                cpa_exec::codex_oauth::CLIENT_ID.to_owned()
            )]
        );
        assert_eq!(
            f.tokens(
                "codex.json",
                &["/access_token", "/siwc/access_token", "/siwc/refresh_token"]
            ),
            ["outer-access-refreshed", "siwc-B", "siwc-ref-B"]
        );
        let written = std::fs::read_to_string(&path).unwrap();
        for want in [
            r#""expired":9007199254740992,"#,
            r#""last_refresh":2000000000,"#,
            r#""openapi_location":"x""#,
        ] {
            assert!(written.contains(want), "{want} in {written}");
        }
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A credential replaced in place while its refresh ran (same registration, other
    /// tokens) keeps the replacement: no refreshed partition applies over it, so the
    /// store discards the refresh without publishing anything (Go `updateInternal`).
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_is_discarded_when_the_credential_was_replaced_meanwhile() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::gated(
            &[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", minute)))],
            0,
        )
        .await;
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        let mut replace = MetadataPatch::default();
        replace.set.insert(
            "siwc".into(),
            codex_file(("keep", days), ("D", "oaiapp_x", days))["siwc"].clone(),
        );
        let before = f.rt.store.get("codex.json").unwrap().revision;
        let replaced = f.rt.store.apply_patch("codex.json", before, &replace).unwrap();
        f.gate.add_permits(1);
        let answered = tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(f.grants(), [("siwc", "siwc-ref-A".to_owned(), "oaiapp_x".to_owned())]);
        assert_eq!(answered.revision, replaced.revision);
        assert_eq!(f.rt.store.get("codex.json").unwrap().revision, replaced.revision);
        assert_eq!(
            f.tokens("codex.json", &["/siwc/access_token", "/siwc/refresh_token"]),
            ["siwc-D", "siwc-ref-D"]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A refresh is discarded when the credential version moved while it ran and no
    /// refreshed partition still matches (Go `updateInternal`), even though the tokens
    /// were put back: here the outer partition's account changed with its token, and
    /// only the token came back.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_is_discarded_when_the_credential_version_moved_meanwhile() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let mut file = codex_file(("A", minute), ("keep", "oaiapp_x", days));
        file["use_siwc"] = false.into();
        file["account_id"] = "acct-A".into();
        let f = CodexDisk::gated(&[("codex.json", &file)], 0).await;
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        let mut last = None;
        for edit in [
            serde_json::json!({"access_token": "outer-B", "account_id": "acct-X"}),
            serde_json::json!({"access_token": "outer-A"}),
        ] {
            let mut patch = MetadataPatch::default();
            for (k, v) in edit.as_object().unwrap() {
                patch.set.insert(k.clone(), v.clone());
            }
            let revision = f.rt.store.get("codex.json").unwrap().revision;
            last = Some(f.rt.store.apply_patch("codex.json", revision, &patch).unwrap());
        }
        let edited = last.unwrap();
        f.gate.add_permits(1);
        let answered = tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(f.grants().len(), 1);
        assert_eq!(answered.revision, edited.revision);
        assert_eq!(f.rt.store.get("codex.json").unwrap().revision, edited.revision);
        assert_eq!(
            f.tokens("codex.json", &["/access_token", "/account_id"]),
            ["outer-A", "acct-X"]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A refresh that only adopted tokens another process rotated on disk (no grant) and
    /// is then discarded leaves the file as it was, and the credential's cooldowns and
    /// refresh record too: Go writes such a refresh only through the persist of an
    /// admitted update.
    #[tokio::test]
    async fn a_discarded_adopt_only_codex_refresh_changes_nothing() {
        let (days, hour) = (chrono::Duration::days(5), chrono::Duration::hours(1));
        let f = CodexDisk::new(&[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", hour)))]).await;
        let path = f.dir.join("codex.json");
        let select = |model: &str| f.rt.store.select(Selection::new("codex", model)).unwrap();
        select("m").complete(Outcome::Failure(ExecError::local(
            401,
            FailureScope::Credential,
            "unauthorized",
        )));
        // Written after the 401, whose cooldown state is persisted too.
        let mut file_b = codex_file(("keep", days), ("B", "oaiapp_x", hour));
        file_b["request-retry"] = 2.into();
        let bytes_b = file_b.to_string();
        std::fs::write(&path, &bytes_b).unwrap();
        // The store takes other tokens without writing the file (a reload of another
        // copy), once the refresh adopted B.
        let cooldowns = Arc::new(Mutex::new(None));
        BEFORE_ADMIT.lock().unwrap().push((
            path.clone(),
            Box::new({
                let (store, dir, path, cooldowns) =
                    (f.rt.store.clone(), f.dir.clone(), path.clone(), cooldowns.clone());
                move || {
                    let d = codex_file(("keep", days), ("D", "oaiapp_x", days));
                    let d = Credential::from_file(&dir, &path, d.as_object().cloned().unwrap()).unwrap();
                    store.reconcile(vec![crate::testing::local(d)]);
                    // The reload's new tokens cleared the 401 (Go `updateInternalLocked`);
                    // upstream rejects D too (recorded without the file write a lease's
                    // result makes).
                    let rejected = Outcome::Failure(ExecError::local(401, FailureScope::Credential, "unauthorized"));
                    let (d, policy) = (store.get("codex.json").unwrap(), store.policy.read().unwrap().clone());
                    let mut scheduler = store.scheduler.lock().unwrap();
                    scheduler.record(&d, "m", &rejected, &policy, Instant::now());
                    drop(scheduler);
                    *cooldowns.lock().unwrap() = Some(store.cooldowns("codex.json").len());
                }
            }),
        ));
        let current = f.rt.store.get("codex.json").unwrap();
        let cfg = f.rt.config();
        assert!(f.rt.refresh_after_unauthorized(&current, &cfg).await.is_some());
        assert_eq!(f.grants(), []);
        let stored = f.rt.store.get("codex.json").unwrap();
        assert_eq!(stored.metadata["siwc"]["access_token"], "siwc-D");
        assert_ne!(stored.revision, current.revision);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), bytes_b);
        let before = cooldowns.lock().unwrap().expect("the hook ran");
        assert_eq!(before, 1, "the 401 cooldown is still there");
        assert_eq!(f.rt.store.cooldowns("codex.json").len(), before);
        assert!(
            !f.rt
                .store
                .unauthorized
                .lock()
                .unwrap()
                .refreshed
                .contains_key("codex.json")
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// Tokens replaced and put back while the grant ran (A→D→A) move the credential
    /// version, but the refreshed partition still holds the version it started from, so
    /// the refresh is admitted (Go `CanApplyTo`).
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_is_admitted_over_tokens_put_back_meanwhile() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let file_a = codex_file(("keep", days), ("A", "oaiapp_x", minute));
        let f = CodexDisk::gated(&[("codex.json", &file_a)], 0).await;
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        let version = || f.rt.store.get_registered("codex.json").unwrap().1.credential_version;
        let started = version();
        for siwc in [
            codex_file(("keep", days), ("D", "oaiapp_x", days))["siwc"].clone(),
            file_a["siwc"].clone(),
        ] {
            let mut patch = MetadataPatch::default();
            patch.set.insert("siwc".into(), siwc);
            let revision = f.rt.store.get("codex.json").unwrap().revision;
            f.rt.store.apply_patch("codex.json", revision, &patch).unwrap();
        }
        assert_ne!(version(), started, "the put-back moved the credential version");
        f.gate.add_permits(1);
        let answered = tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(answered.metadata["siwc"]["access_token"], "siwc-access-refreshed");
        assert_eq!(
            f.tokens("codex.json", &["/siwc/access_token", "/siwc/refresh_token"]),
            ["siwc-access-refreshed", "siwc-ref-refreshed"]
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A save that fails after the grant (a program that does not take the lock removed
    /// or truncated the file) does not fail the refresh: Go logs it and publishes the new
    /// tokens, writing a removed file again from memory, so the spent refresh token is
    /// never kept in memory.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_publishes_its_tokens_when_the_save_fails() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        for truncate in [false, true] {
            let f = CodexDisk::gated(
                &[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", minute)))],
                0,
            )
            .await;
            let path = f.dir.join("codex.json");
            BEFORE_ADMIT.lock().unwrap().push((
                path.clone(),
                Box::new({
                    let path = path.clone();
                    move || match truncate {
                        true => std::fs::write(&path, r#"{"type":"#).unwrap(),
                        false => std::fs::remove_file(&path).unwrap(),
                    }
                }),
            ));
            let refresh = tokio::spawn({
                let rt = f.rt.clone();
                async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
            });
            f.granted().await;
            f.gate.add_permits(1);
            let answered = tokio::time::timeout(Duration::from_secs(5), refresh)
                .await
                .unwrap()
                .unwrap()
                .expect("the refresh succeeds");
            assert_eq!(answered.metadata["siwc"]["refresh_token"], "siwc-ref-refreshed");
            let stored = f.rt.store.get("codex.json").unwrap();
            assert_eq!(stored.metadata["siwc"]["refresh_token"], "siwc-ref-refreshed");
            let disk = std::fs::read_to_string(&path).unwrap();
            if truncate {
                assert_eq!(disk, r#"{"type":"#);
            } else {
                let disk: Value = serde_json::from_str(&disk).unwrap();
                assert_eq!(
                    (&disk["siwc"]["refresh_token"], &disk["disabled"]),
                    (&"siwc-ref-refreshed".into(), &false.into())
                );
            }
            std::fs::remove_dir_all(&f.dir).unwrap();
        }
    }

    /// At shutdown, a Codex refresh still waiting for the file's lock (another process
    /// holds it) gives up without a grant, and one whose grant is in flight is waited for
    /// until its tokens are written: an exit cannot strand a spent refresh token.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn shutdown_stops_codex_lock_waits_and_drains_started_grants() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::gated(
            &[
                ("locked.json", &codex_file(("keep", days), ("L", "oaiapp_x", minute))),
                ("granting.json", &codex_file(("keep", days), ("G", "oaiapp_x", minute))),
            ],
            0,
        )
        .await;
        let held = cpa_exec::codex_siwc_bind::lock_file(&f.dir.join("locked.json")).unwrap();
        let refresh = |id: &'static str| {
            let rt = f.rt.clone();
            tokio::spawn(async move { rt.prepare_credential(id, &rt.config(), None).await })
        };
        let (waiting, granting) = (refresh("locked.json"), refresh("granting.json"));
        f.lock_attempts("locked.json", 1).await;
        f.granted().await;
        let shutdown = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.shutdown_codex_refreshes().await }
        });
        let waited = tokio::time::timeout(Duration::from_secs(5), waiting)
            .await
            .unwrap()
            .unwrap();
        assert!(waited.is_err(), "{waited:?}");
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(!shutdown.is_finished(), "shutdown waits for the started grant");
        f.gate.add_permits(1);
        tokio::time::timeout(Duration::from_secs(5), shutdown)
            .await
            .unwrap()
            .unwrap();
        assert!(granting.await.unwrap().is_ok());
        assert_eq!(f.grants(), [("siwc", "siwc-ref-G".to_owned(), "oaiapp_x".to_owned())]);
        assert_eq!(
            f.tokens("granting.json", &["/siwc/refresh_token"]),
            ["siwc-ref-refreshed"]
        );
        drop(held);
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// The new tokens reach the file even when the store refuses the refresh: here the
    /// file was removed and created again with the spent tokens, and the ID registered
    /// again, while the grant ran. Go writes under the lock before its manager refuses
    /// the stale registration, so the next load reads the new tokens, not spent ones.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_writes_its_tokens_when_the_id_was_registered_again_meanwhile() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let mut file_a = codex_file(("keep", days), ("A", "oaiapp_x", minute));
        file_a["request-retry"] = 2.into();
        let f = CodexDisk::gated(&[("codex.json", &file_a)], 0).await;
        let path = f.dir.join("codex.json");
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        std::fs::remove_file(&path).unwrap();
        std::fs::write(&path, file_a.to_string()).unwrap();
        let cfg = f.rt.config();
        let load = || {
            cpa_core::config::credentials::from_auth_dir(&cfg)
                .into_iter()
                .map(crate::testing::local)
                .collect::<Vec<_>>()
        };
        f.rt.store.reconcile(vec![]);
        f.rt.store.reconcile(load());
        f.gate.add_permits(1);
        let answered = tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap();
        assert!(answered.is_err(), "{answered:?}");
        let disk: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(disk["siwc"]["refresh_token"], "siwc-ref-refreshed");
        // Go's write after a grant keeps the file's keys as written.
        assert_eq!(
            (&disk["request-retry"], &disk["request_retry"]),
            (&2.into(), &Value::Null)
        );
        assert_eq!(
            f.rt.store.get("codex.json").unwrap().metadata["siwc"]["refresh_token"],
            "siwc-ref-A"
        );
        // The watcher's next reload takes the new tokens.
        f.rt.store.reconcile(load());
        assert_eq!(
            f.rt.store.get("codex.json").unwrap().metadata["siwc"]["refresh_token"],
            "siwc-ref-refreshed"
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A refresh publishes the proxy of the file it adopted, as requests route through
    /// it: a changed proxy replaces the loaded one, and a removed one is gone.
    #[tokio::test]
    async fn a_codex_refresh_routes_through_the_proxy_of_the_file_it_adopted() {
        let (days, hour) = (chrono::Duration::days(5), chrono::Duration::hours(1));
        let mut file = codex_file(("keep", days), ("A", "oaiapp_x", hour));
        file["proxy_url"] = "http://127.0.0.1:9/".into();
        let f = CodexDisk::new(&[("codex.json", &file)]).await;
        let cfg = f.rt.config();
        let route = || cpa_exec::proxy::Proxy::effective_url(&f.rt.store.get("codex.json").unwrap(), &cfg);
        assert_eq!(route(), "http://127.0.0.1:9/");
        for (version, proxy) in [("B", Some("http://127.0.0.1:8/")), ("C", None)] {
            let mut rotated = codex_file(("keep", days), (version, "oaiapp_x", hour));
            if let Some(proxy) = proxy {
                rotated["proxy_url"] = proxy.into();
            }
            std::fs::write(f.dir.join("codex.json"), rotated.to_string()).unwrap();
            let current = f.rt.store.get("codex.json").unwrap();
            assert!(f.rt.refresh_after_unauthorized(&current, &cfg).await.is_some());
            assert_eq!(route(), proxy.unwrap_or(""), "version {version}");
        }
        assert_eq!(f.grants(), []);
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// A credential file emptied to `{}` while the grant ran fails the refresh at the
    /// write (Go: "invalid credential JSON ... before write"): nothing is written or
    /// published.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_codex_refresh_fails_when_its_file_is_emptied_while_the_grant_runs() {
        let (days, minute) = (chrono::Duration::days(5), chrono::Duration::minutes(1));
        let f = CodexDisk::gated(
            &[("codex.json", &codex_file(("keep", days), ("A", "oaiapp_x", minute)))],
            0,
        )
        .await;
        let path = f.dir.join("codex.json");
        let refresh = tokio::spawn({
            let rt = f.rt.clone();
            async move { rt.prepare_credential("codex.json", &rt.config(), None).await }
        });
        f.granted().await;
        std::fs::write(&path, "{}").unwrap();
        f.gate.add_permits(1);
        let answered = tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .unwrap()
            .unwrap();
        assert!(answered.is_err(), "{answered:?}");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{}");
        assert_eq!(
            f.rt.store.get("codex.json").unwrap().metadata["siwc"]["refresh_token"],
            "siwc-ref-A"
        );
        std::fs::remove_dir_all(&f.dir).unwrap();
    }

    /// Go 50d5fe18 and feb63984 (conductor_issue6415_test, conductor_issue6742_test): a
    /// 401 on a Codex token that is not due schedules a background refresh at once, which
    /// rotates it and clears the unauthorized cooldown, not another model's quota. A 401
    /// right after that refresh waits `refreshFailureBackoff`.
    #[tokio::test]
    async fn a_rejected_token_is_refreshed_in_the_background() {
        let (hit_tx, mut hit) = tokio::sync::mpsc::unbounded_channel();
        let app = axum::Router::new().route(
            "/oauth/token",
            axum::routing::post(move || async move {
                hit_tx.send(()).unwrap();
                r#"{"access_token":"rotated","refresh_token":"rotated-rt","expires_in":864000}"#
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let token_url = format!("http://{}/oauth/token", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!("cpa-refresh-401-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let expires = (chrono::Utc::now() + chrono::Duration::days(9)).to_rfc3339();
        std::fs::write(
            dir.join("codex.json"),
            serde_json::json!({"type": "codex", "access_token": "outer", "refresh_token": "outer-rt", "expired": expires})
                .to_string(),
        )
        .unwrap();
        let mut cfg = Config::parse("").unwrap();
        cfg.auth_dir = dir.clone();
        let client = wreq::Client::new();
        let oauth =
            cpa_exec::codex_oauth::CodexOAuth::with_endpoints(client.clone(), &token_url, &token_url, &token_url);
        let rt = Arc::new(crate::testing::runtime(
            cfg.clone(),
            cpa_core::config::credentials::from_auth_dir(&cfg)
                .into_iter()
                .map(crate::testing::local)
                .collect(),
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: cpa_exec::codex::CodexExecutor::with_client(client, oauth),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        rt.start_auto_refresh();
        async fn quiet(hit: &mut tokio::sync::mpsc::UnboundedReceiver<()>) {
            let pending = tokio::time::timeout(Duration::from_millis(1500), hit.recv());
            assert!(pending.await.is_err(), "no refresh");
        }
        quiet(&mut hit).await; // Nine days left: not due under the 96h lead.
        let mut quota = ExecError::local(429, FailureScope::Model, "rate limited");
        quota.retry_after = Some(Duration::from_secs(3600));
        let select = |model: &str| rt.store.select(Selection::new("codex", model)).unwrap();
        select("q").complete(Outcome::Failure(quota));
        let unauthorized = || Outcome::Failure(ExecError::local(401, FailureScope::Credential, "unauthorized"));
        select("m").complete(unauthorized());
        assert_eq!(rt.store.cooldowns("codex.json").len(), 2);
        tokio::time::timeout(Duration::from_secs(5), hit.recv())
            .await
            .expect("a refresh of the rejected token");
        let rotated = async {
            loop {
                let c = rt.store.get("codex.json").unwrap();
                if c.str("access_token") == Some("rotated") {
                    break c;
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        };
        let rotated = tokio::time::timeout(Duration::from_secs(5), rotated).await.unwrap();
        let left = rt.store.cooldowns("codex.json");
        assert_eq!(
            left.iter().map(|c| (c.model.as_str(), c.status)).collect::<Vec<_>>(),
            [("q", 429)]
        );
        // Rejected again right after: the refresh waits out the backoff.
        rt.store
            .select(Selection::new("codex", "m"))
            .unwrap()
            .complete(unauthorized());
        assert_eq!(
            rt.store.unauthorized().pending.get("codex.json").map(|(r, _)| *r),
            Some(rotated.revision)
        );
        quiet(&mut hit).await;
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// Which 401s schedule a background refresh: Codex ones that cool the credential,
    /// including a request-scoped 401 a `*-and-cooldown` rule cools; not Claude's (that
    /// waits for the post-replay port). A scan whose snapshot predates a newer revision
    /// keeps the 401 recorded on it.
    #[test]
    fn which_401s_schedule_a_background_refresh() {
        let codex = |note: &str| {
            let mut c = cred("codex.json", "codex", false);
            c.metadata.insert("refresh_token".into(), "rt".into());
            c.metadata.insert("note".into(), note.into());
            c.metadata.insert(
                "request_scoped_errors".into(),
                serde_json::json!([{"status": 401, "match": ["revoked"], "action": "stop-and-cooldown"}]),
            );
            c
        };
        let mut claude = cred("claude.json", "claude", false);
        claude.metadata.insert("refresh_token".into(), "rt".into());
        let store = CredentialStore::new(vec![codex("a"), claude]);
        let fail = |provider: &str, model: &str, scope, text: &str| {
            store
                .select(Selection::new(provider, model))
                .unwrap()
                .complete(Outcome::Failure(ExecError::local(401, scope, text)));
        };
        let pending = || {
            let mut ids: Vec<_> = store
                .unauthorized()
                .pending
                .into_iter()
                .map(|(id, (r, _))| (id, r))
                .collect();
            ids.sort();
            ids
        };
        fail("claude", "m", FailureScope::Credential, "unauthorized");
        fail("codex", "m", FailureScope::Request, "bad request");
        assert_eq!(pending(), [], "Claude, and an unforced request-scoped 401");
        fail("codex", "m", FailureScope::Request, "token revoked");
        let first = store.get("codex.json").unwrap().revision;
        assert_eq!(pending(), [("codex.json".to_owned(), first)], "a forced cooldown");
        // The scan's snapshot holds the first revision; a refresh commits a newer one,
        // which an upstream rejects too, before the scan reads the rejections.
        let old = store.snapshot();
        store.reconcile(vec![
            codex("b"),
            store.get("claude.json").map(|c| (*c).clone()).unwrap(),
        ]);
        let second = store.get("codex.json").unwrap().revision;
        assert!(second > first);
        fail("codex", "n", FailureScope::Request, "token revoked");
        store.forget_stale_unauthorized(&store.unauthorized(), &old);
        assert_eq!(
            pending(),
            [("codex.json".to_owned(), second)],
            "a stale snapshot keeps it"
        );
        store.forget_stale_unauthorized(&store.unauthorized(), &store.snapshot());
        assert_eq!(pending(), [("codex.json".to_owned(), second)], "still current");
        let seen = store.unauthorized();
        store.reconcile(vec![
            codex("c"),
            store.get("claude.json").map(|c| (*c).clone()).unwrap(),
        ]);
        store.forget_stale_unauthorized(&seen, &store.snapshot());
        assert_eq!(pending(), [], "replaced");
    }

    /// Go `mergeAuthContent` and `CredentialRefreshPatch.Apply` for a refresh that lost
    /// the race to another edit (metadata_merge_test.go, refresh_patch_test.go).
    #[test]
    fn a_stale_refresh_merges_like_go() {
        use serde_json::json;
        let map = |v: Value| v.as_object().unwrap().clone();
        let codex = json!({"type": "codex", "access_token": "a", "refresh_token": "r", "account_id": "acct", "email": "e@x", "plan_type": "plus"});
        let refresh = |plan: &str, email: &str| json!({"type": "codex", "access_token": "a2", "refresh_token": "r2", "account_id": "acct", "email": email, "plan_type": plan});
        let edit = |base: &Value, k: &str, v: Value| {
            let mut m = map(base.clone());
            m.insert(k.into(), v);
            Value::Object(m)
        };
        let kimi = json!({"type": "kimi", "note": "a", "expired": "t0", "gone": "a"});
        let siwc = json!({"type": "codex", "access_token": "a", "refresh_token": "r", "account_id": "acct",
            "siwc": {"access_token": "s", "refresh_token": "sr", "client_id": "c", "expired": "t0", "note": "n"}});
        let siwc_refresh = json!({"siwc": {"access_token": "s2", "refresh_token": "sr2", "client_id": "c", "expired": "t1", "note": "n"}});
        let siwc_edit = |k: &str, v: Value| {
            let mut m = map(siwc.clone());
            m["siwc"][k] = v;
            Value::Object(m)
        };
        for (name, provider, base, user, set, remove, want_set, want_remove) in [
            (
                "an unchanged value keeps the edit, a changed token is applied",
                "kimi",
                &kimi,
                edit(&kimi, "note", json!("b")),
                json!({"type": "kimi", "note": "a", "access_token": "new"}),
                vec![],
                json!({"access_token": "new"}),
                vec![],
            ),
            (
                "both changed a normal field: the edit wins",
                "kimi",
                &kimi,
                edit(&kimi, "note", json!("b")),
                json!({"note": "x"}),
                vec![],
                json!({}),
                vec![],
            ),
            (
                "both changed a token payload: the refresh wins",
                "kimi",
                &kimi,
                edit(&kimi, "expired", json!("t2")),
                json!({"expired": "t1"}),
                vec![],
                json!({"expired": "t1"}),
                vec![],
            ),
            (
                "a removal of an edited key is dropped, of an untouched key kept",
                "kimi",
                &kimi,
                edit(&kimi, "expired", json!("t2")),
                json!({}),
                vec!["expired", "gone"],
                json!({}),
                vec!["gone"],
            ),
            (
                "JSON null is an edit of a missing key",
                "kimi",
                &kimi,
                edit(&kimi, "fresh", Value::Null),
                json!({"fresh": "x"}),
                vec![],
                json!({}),
                vec![],
            ),
            (
                "Codex: an unchanged plan and email keep the edit",
                "codex",
                &codex,
                edit(&codex, "plan_type", json!("team")),
                refresh("plus", "e@x"),
                vec![],
                json!({"access_token": "a2", "refresh_token": "r2"}),
                vec![],
            ),
            (
                "Codex: a changed plan and email are applied over the edit",
                "codex",
                &codex,
                edit(&edit(&codex, "plan_type", json!("team")), "email", json!("u@x")),
                refresh("pro", "n@x"),
                vec![],
                json!({"access_token": "a2", "refresh_token": "r2", "plan_type": "pro", "email": "n@x"}),
                vec![],
            ),
            (
                "Codex SIWC: the refreshed fields land over an edit inside the partition",
                "codex",
                &siwc,
                siwc_edit("note", json!("edited")),
                siwc_refresh.clone(),
                vec![],
                json!({"siwc": {"access_token": "s2", "refresh_token": "sr2", "client_id": "c", "expired": "t1", "note": "edited"}}),
                vec![],
            ),
            (
                "Codex SIWC: another client drops the partition",
                "codex",
                &siwc,
                siwc_edit("client_id", json!("other")),
                siwc_refresh.clone(),
                vec![],
                json!({}),
                vec![],
            ),
            (
                "Codex SIWC: an edit already holding the result keeps it",
                "codex",
                &siwc,
                siwc_edit("access_token", json!("s2")),
                json!({"siwc": {"access_token": "s2", "refresh_token": "sr", "client_id": "c", "expired": "t0", "note": "n"}}),
                vec![],
                json!({}),
                vec![],
            ),
            (
                "Codex: another account drops the whole partition",
                "codex",
                &codex,
                edit(&codex, "account_id", json!("other")),
                refresh("pro", "n@x"),
                vec![],
                json!({}),
                vec![],
            ),
        ] {
            let patch = MetadataPatch {
                set: map(set),
                remove: remove.into_iter().map(str::to_owned).collect(),
            };
            let (out, _) = rebase_patch(provider, &map(base.clone()), &map(user), &patch);
            assert_eq!(Value::Object(out.set), want_set, "{name}");
            assert_eq!(out.remove, want_remove, "{name}");
        }
    }

    /// Go `CredentialRefreshPatch.CanApplyTo`: a refreshed partition that still matches
    /// the stored version applies even after the other partition's tokens changed.
    #[test]
    fn a_matching_codex_partition_applies_after_the_other_changed() {
        use serde_json::json;
        let map = |v: Value| v.as_object().unwrap().clone();
        let base = json!({"type": "codex", "access_token": "a", "refresh_token": "r",
            "siwc": {"access_token": "s", "refresh_token": "sr", "client_id": "c"}});
        let patch = MetadataPatch {
            set: map(json!({"siwc": {"access_token": "s2", "refresh_token": "sr2", "client_id": "c"}})),
            remove: vec![],
        };
        let mut outer_changed = map(base.clone());
        outer_changed.insert("access_token".into(), "other".into());
        let (out, applies) = rebase_patch("codex", &map(base.clone()), &outer_changed, &patch);
        assert!(applies);
        assert_eq!(out.set["siwc"]["access_token"], "s2");
        let mut siwc_changed = map(base.clone());
        siwc_changed["siwc"]["refresh_token"] = "rotated-elsewhere".into();
        let (out, applies) = rebase_patch("codex", &map(base.clone()), &siwc_changed, &patch);
        assert!(!applies && out.set.is_empty());
        // Only Codex partitions qualify.
        assert!(!rebase_patch("claude", &map(base.clone()), &outer_changed, &patch).1);
    }

    /// Go `CredentialsChanged` compares the token requests use, which a `use_siwc`
    /// attribute alone can switch.
    #[test]
    fn switching_to_the_siwc_token_changes_the_credentials() {
        let mut a = cred("codex.json", "codex", false);
        a.metadata.insert("access_token".into(), "outer".into());
        a.metadata
            .insert("siwc".into(), serde_json::json!({"access_token": "nested"}));
        let mut b = a.clone();
        assert!(!credentials_changed(&a, &b));
        b.attributes.insert("use_siwc".into(), "true".into());
        assert!(credentials_changed(&a, &b));
    }

    /// Log lines written on this thread while the guard lives.
    #[derive(Clone, Default)]
    struct Logs(Arc<Mutex<Vec<u8>>>);
    impl std::io::Write for Logs {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    impl Logs {
        fn install(&self) -> tracing::subscriber::DefaultGuard {
            let writer = self.clone();
            let subscriber = tracing_subscriber::fmt()
                .with_ansi(false)
                .without_time()
                .with_writer(move || writer.clone())
                .finish();
            tracing::subscriber::set_default(subscriber)
        }
        fn text(&self) -> String {
            String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
        }
        async fn wait_for(&self, needle: &str, count: usize) {
            let found = tokio::time::timeout(Duration::from_secs(10), async {
                while self.text().matches(needle).count() < count {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            });
            found
                .await
                .unwrap_or_else(|_| panic!("{needle:?} not logged {count} times:\n{}", self.text()));
        }
    }

    /// A due Claude refresh that fails logs one warning with the status, the OAuth error
    /// and the next attempt, and is tried again when its backoff ends: invalid_grant
    /// after Go's 1 min, a 5xx (retried in place twice) after 5 min. A job that panics
    /// fails alone, a scan that panics restarts the loop, and the next success commits.
    /// Backoffs are ended by hand ([`RefreshState::expire`]) instead of waited for.
    #[tokio::test]
    async fn a_failed_background_refresh_is_logged_and_retried_after_its_backoff() {
        let answers = Arc::new(Mutex::new(std::collections::VecDeque::from([
            (
                400,
                r#"{"error":"invalid_grant","error_description":"Refresh token sk-ant-ort01-leaked is invalid"}"#,
            ),
            (500, r#"{"error":"server_error"}"#),
            (500, r#"{"error":"server_error"}"#),
            (500, r#"{"error":"server_error"}"#),
            (
                200,
                r#"{"access_token":"sk-ant-oat-new-fake","refresh_token":"fake-rt-2","expires_in":28800}"#,
            ),
        ])));
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let app = axum::Router::new().route(
            "/token",
            axum::routing::post({
                let (answers, calls) = (answers.clone(), calls.clone());
                move || async move {
                    calls.fetch_add(1, Ordering::SeqCst);
                    let (status, body) = answers.lock().unwrap().pop_front().expect("an unexpected exchange");
                    (axum::http::StatusCode::from_u16(status).unwrap(), body)
                }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!("cpa-refresh-fail-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("claude-backoff.json");
        std::fs::write(
            &path,
            serde_json::json!({"type": "claude", "access_token": "sk-ant-oat-old-fake", "refresh_token": "fake-rt-1",
                "expired": (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339(),
                "account_uuid": "acct-fake", "claude_device_ids": ["b".repeat(64)]})
            .to_string(),
        )
        .unwrap();
        let mut cfg = Config::parse("").unwrap();
        cfg.auth_dir = dir.clone();
        let (token, profile) = (format!("{base}/token"), format!("{base}/profile"));
        let oauth = cpa_exec::oauth::OAuth::with_endpoints(wreq::Client::new(), &token, &profile, &profile);
        let rt = Arc::new(crate::testing::runtime(
            cfg.clone(),
            cpa_core::config::credentials::from_auth_dir(&cfg)
                .into_iter()
                .map(crate::testing::local)
                .collect(),
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1")
                    .unwrap()
                    .with_oauth(oauth),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        let logs = Logs::default();
        let _guard = logs.install();
        let failed = "credential refresh failed for claude (claude-backoff.json): status";
        let retry_in = |rt: &Runtime| {
            let c = rt.store.get("claude-backoff.json").unwrap();
            let at = rt.refresh_state.lock().unwrap().retry_at(&c).unwrap();
            at.saturating_duration_since(Instant::now())
        };
        // Ends the current backoff and wakes the loop.
        let expire = |rt: &Runtime| {
            let c = rt.store.get("claude-backoff.json").unwrap();
            rt.refresh_state.lock().unwrap().expire(&c);
            rt.config_changed.send_replace(());
        };
        rt.start_auto_refresh();
        logs.wait_for(failed, 1).await;
        assert!(
            logs.text().contains(&format!(
                "{failed} 400: Claude OAuth acquisition failed: invalid_grant; next attempt in 60s"
            )),
            "{}",
            logs.text()
        );
        assert!(
            (55..=60).contains(&retry_in(&rt).as_secs()),
            "Go invalidGrantBackoffBase"
        );
        // A job that panics is that job's failure; the loop goes on.
        tests::arm_panic("prepare", "claude-backoff.json");
        expire(&rt);
        logs.wait_for(failed, 2).await;
        assert!(
            logs.text()
                .contains(&format!("{failed} 500: refresh panicked: injected prepare panic"))
        );
        expire(&rt);
        logs.wait_for(failed, 3).await;
        assert!(
            logs.text().contains(&format!(
                "{failed} 500: Claude OAuth acquisition failed: server_error; next attempt in 300s"
            )),
            "{}",
            logs.text()
        );
        assert!(
            (295..=300).contains(&retry_in(&rt).as_secs()),
            "Go refreshFailureBackoff"
        );
        assert_eq!(
            calls.load(Ordering::SeqCst),
            4,
            "one invalid_grant, then three 5xx tries in place"
        );
        // A scan that panics restarts the loop, which then refreshes.
        tests::arm_panic("scan", "claude-backoff.json");
        expire(&rt);
        logs.wait_for("credential auto-refresh loop panicked (injected scan panic)", 1)
            .await;
        let committed = tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let c = rt.store.get("claude-backoff.json").unwrap();
                if c.str("access_token") == Some("sk-ant-oat-new-fake") {
                    break c;
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        })
        .await
        .expect("the retry after the backoff commits");
        assert_eq!(committed.str("refresh_token"), Some("fake-rt-2"));
        let saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
        assert_eq!(saved["access_token"], "sk-ant-oat-new-fake");
        assert_eq!(logs.text().matches(failed).count(), 3, "{}", logs.text());
        let text = logs.text();
        assert!(
            !text.contains("fake-rt") && !text.contains("sk-ant-o"),
            "no token in the logs: {text}"
        );
        rt.stop_auto_refresh();
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// Claude credential files `ids` due for a refresh within the hour (each with its own
    /// refresh token, `fake-rt-<id>`), with a token endpoint answering each request body
    /// by `answer` on loopback, and their runtime under config `yaml`. Test hooks are keyed by credential ID, so each test uses its own IDs.
    async fn claude_refresh_fixture<F, Fut>(ids: &[&str], yaml: &str, answer: F) -> (Arc<Runtime>, std::path::PathBuf)
    where
        F: Fn(String) -> Fut + Clone + Send + Sync + 'static,
        Fut: std::future::Future<Output = (axum::http::StatusCode, &'static str)> + Send + 'static,
    {
        let app = axum::Router::new().route("/token", axum::routing::post(move |body: String| answer(body)));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!("cpa-refresh-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&dir).unwrap();
        for id in ids {
            std::fs::write(
                dir.join(id),
                serde_json::json!({"type": "claude", "access_token": "sk-ant-oat-old-fake",
                    "refresh_token": format!("fake-rt-{id}"),
                    "expired": (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339(),
                    "account_uuid": "acct-fake", "claude_device_ids": ["b".repeat(64)]})
                .to_string(),
            )
            .unwrap();
        }
        let mut cfg = Config::parse(yaml).unwrap();
        cfg.auth_dir = dir.clone();
        let (token, profile) = (format!("{base}/token"), format!("{base}/profile"));
        let oauth = cpa_exec::oauth::OAuth::with_endpoints(wreq::Client::new(), &token, &profile, &profile);
        let rt = Arc::new(crate::testing::runtime(
            cfg.clone(),
            cpa_core::config::credentials::from_auth_dir(&cfg)
                .into_iter()
                .map(crate::testing::local)
                .collect(),
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1")
                    .unwrap()
                    .with_oauth(oauth),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        (rt, dir)
    }

    /// Waits until credential `id` holds the refreshed access token.
    async fn refreshed(rt: &Runtime, id: &str) -> Arc<Credential> {
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let c = rt.store.get(id).unwrap();
                if c.str("access_token") == Some("sk-ant-oat-new-fake") {
                    break c;
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        })
        .await
        .unwrap_or_else(|_| panic!("{id} was not refreshed"))
    }

    /// Go `markRefreshPending`: a job past [`REFRESH_JOB_BOUND`] (2 s under test, counted
    /// from when it got a worker) keeps its credential reserved, so no second job starts
    /// while it runs, even after the backoff ends, but gives up its worker: with one
    /// worker, another credential that comes due meanwhile refreshes while the first's
    /// token call is still held. The held job's own result, a failure, is recorded when
    /// it ends, and that wakes the loop: with no event after it, the rejected credential
    /// (whose scan sets no other timer) is retried once its backoff ends, and commits.
    #[tokio::test]
    async fn a_job_past_its_bound_stays_the_only_one_and_wakes_the_loop_when_it_ends() {
        let (slow, quick) = ("claude-slow.json", "claude-quick.json");
        let release = Arc::new(tokio::sync::Notify::new());
        let slow_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let answer = {
            let (release, slow_calls) = (release.clone(), slow_calls.clone());
            move |body: String| {
                let (release, slow_calls) = (release.clone(), slow_calls.clone());
                async move {
                    if body.contains(&format!("fake-rt-{slow}")) && slow_calls.fetch_add(1, Ordering::SeqCst) == 0 {
                        release.notified().await;
                        return (axum::http::StatusCode::BAD_REQUEST, r#"{"error":"invalid_request"}"#);
                    }
                    let ok = r#"{"access_token":"sk-ant-oat-new-fake","refresh_token":"fake-rt-2","expires_in":28800}"#;
                    (axum::http::StatusCode::OK, ok)
                }
            }
        };
        let workers = "oauth:\n  auth-auto-refresh-workers: 1\n";
        let (rt, dir) = claude_refresh_fixture(&[slow, quick], workers, answer).await;
        // Neither is due on its own: an upstream 401 is what schedules the slow one.
        let set_expiry = |id: &str, ahead: chrono::Duration| {
            let mut patch = MetadataPatch::default();
            patch
                .set
                .insert("expired".into(), (chrono::Utc::now() + ahead).to_rfc3339().into());
            let c = rt.store.get(id).unwrap();
            rt.store.apply_patch(id, c.revision, &patch).unwrap()
        };
        set_expiry(quick, chrono::Duration::days(9));
        let c = set_expiry(slow, chrono::Duration::days(9));
        rt.store
            .unauthorized
            .lock()
            .unwrap()
            .pending
            .insert(slow.into(), (c.revision, Instant::now()));
        crate::refresh::override_backoff(slow, Duration::from_secs(1));
        let logs = Logs::default();
        let _guard = logs.install();
        rt.start_auto_refresh();
        logs.wait_for(
            &format!("credential refresh for claude ({slow}) still running after 2s"),
            1,
        )
        .await;
        // The only worker is free again: a credential that comes due now refreshes.
        set_expiry(quick, chrono::Duration::hours(1));
        refreshed(&rt, quick).await;
        // The backoff ends twice while the job runs; neither forced scan starts another.
        for _ in 0..2 {
            let scans = tests::reached("scan", slow);
            rt.refresh_state.lock().unwrap().expire(&c);
            rt.config_changed.send_replace(());
            tokio::time::timeout(Duration::from_secs(10), async {
                while tests::reached("scan", slow) == scans {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
            })
            .await
            .expect("a forced scan");
        }
        assert_eq!(slow_calls.load(Ordering::SeqCst), 1);
        assert_eq!(tests::reached("prepare", slow), 1, "one job while it runs");
        release.notify_one();
        logs.wait_for(
            &format!("credential refresh failed for claude ({slow}) after an upstream 401: status 400"),
            1,
        )
        .await;
        // No event from here on: only the ended job can wake the loop.
        let committed = refreshed(&rt, slow).await;
        assert_eq!(slow_calls.load(Ordering::SeqCst), 2);
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert!(!rt.refresh_state.lock().unwrap().running(&committed));
        let text = logs.text();
        assert_eq!(text.matches("still running after").count(), 1, "{text}");
        assert_eq!(
            text.matches("its previous refresh is still running").count(),
            1,
            "{text}"
        );
        assert_eq!(text.matches("credential refresh failed").count(), 1, "{text}");
        rt.stop_auto_refresh();
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// Every reservation belongs to a spawned job from the moment it is made, and the job
    /// ends it on every path: a scan that panics after reserving a credential restarts
    /// the loop without stranding that credential, whose job then panics in preparation
    /// (after the loop that started it is gone), backs off and is retried.
    #[tokio::test]
    async fn no_reservation_is_stranded_by_a_panicking_scan_or_job() {
        let ids = ["claude-strand-a.json", "claude-strand-b.json"];
        let answer = |_| async {
            let ok = r#"{"access_token":"sk-ant-oat-new-fake","refresh_token":"fake-rt-2","expires_in":28800}"#;
            (axum::http::StatusCode::OK, ok)
        };
        let (rt, dir) = claude_refresh_fixture(&ids, "", answer).await;
        let order: Vec<String> = rt.store.snapshot().iter().map(|c| c.id.clone()).collect();
        let (first, second) = (order[0].as_str(), order[1].as_str());
        crate::refresh::override_backoff(first, Duration::from_secs(1));
        tests::arm_panic("scan", second);
        tests::arm_panic("prepare", first);
        let logs = Logs::default();
        let _guard = logs.install();
        rt.start_auto_refresh();
        refreshed(&rt, first).await;
        refreshed(&rt, second).await;
        assert_eq!(tests::reached("prepare", first), 2, "the panicked job, then its retry");
        assert!(
            logs.text()
                .contains("credential auto-refresh loop panicked (injected scan panic)")
        );
        assert!(logs.text().contains(&format!(
            "credential refresh failed for claude ({first}): status 500: refresh panicked"
        )));
        rt.stop_auto_refresh();
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// A plugin-routed refresh job that panics records no deadline of the plugin's, so
    /// the refresh state backs it off like any failure instead of starting it again on
    /// the next scan.
    #[cfg(unix)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[cfg_attr(feature = "media-relay", ignore = "needs the Go plugin toolchain")]
    async fn a_panicking_plugin_refresh_backs_off() {
        let tmp = std::env::temp_dir();
        let Some(built) = cpa_plugin::testing::built_plugins(&tmp, "a_panicking_plugin_refresh") else {
            return;
        };
        let dir = cpa_plugin::testing::scratch(&tmp, "plugin-refresh-panic");
        let (auths, plugins, records) = (dir.join("auths"), dir.join("plugins"), dir.join("records"));
        for d in [&auths, &plugins, &records] {
            std::fs::create_dir_all(d).unwrap();
        }
        std::fs::copy(built.join("recorder.so"), plugins.join("acme.so")).unwrap();
        std::fs::write(
            auths.join("p.json"),
            r#"{"type":"acme","access_token":"p","refresh_interval":"1h"}"#,
        )
        .unwrap();
        let yaml = format!(
            "auth-dir: {}\nplugins:\n  enabled: true\n  dir: {}\n  configs:\n    acme:\n      enabled: true\n      label: acme\n      record: {}\n      caps: auth_provider\n",
            auths.display(),
            plugins.display(),
            records.display()
        );
        let cfg = Config::parse(&yaml).unwrap();
        let credentials = cpa_core::config::credentials::load(&cfg);
        let rt = Arc::new(crate::testing::runtime(
            cfg,
            credentials,
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        crate::plugins::start(&rt).await;
        // As after the first plugin-aware load.
        rt.store.end_bootstrap();
        let c = rt.store.get("p.json").unwrap();
        assert!(
            crate::plugins::refresh::route(&rt, &c, &rt.config()).is_some(),
            "plugin-routed"
        );
        tests::arm_panic("prepare", "p.json");
        rt.start_auto_refresh();
        let backed_off = tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let c = rt.store.get("p.json").unwrap();
                let retry = rt.refresh_state.lock().unwrap().retry_at(&c);
                if retry.is_some_and(|at| at > Instant::now() + Duration::from_secs(250)) {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        });
        if backed_off.await.is_err() {
            let c = rt.store.get("p.json").unwrap();
            panic!(
                "no backoff: reached {}, retry {:?}, due {:?}, schedule {:?}",
                tests::reached("prepare", "p.json"),
                rt.refresh_state
                    .lock()
                    .unwrap()
                    .retry_at(&c)
                    .map(|at| at.saturating_duration_since(Instant::now())),
                crate::plugins::refresh::due_at(&rt, &c, &rt.config()),
                rt.store.refresh_schedules().lock().unwrap().get("p.json").copied()
            );
        }
        tokio::time::sleep(Duration::from_millis(1500)).await;
        assert_eq!(
            tests::reached("prepare", "p.json"),
            1,
            "no second attempt before the backoff"
        );
        rt.stop_auto_refresh();
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// Of a plugin's refresh failure only the status and a known error code are logged:
    /// its free message may hold anything, an unlabelled token included, which the
    /// pattern-based sanitizer cannot see.
    #[test]
    fn a_plugin_refresh_failure_logs_no_plugin_message() {
        let logs = Logs::default();
        let _guard = logs.install();
        let c = cred("p.json", "acme", false);
        for code in ["invalid_grant", "rejected"] {
            let error = crate::plugins::refresh::call_error(cpa_plugin::rpc::CallError::Rpc {
                code: code.into(),
                message: "rejected abc123xyz456opaque".into(),
                status: 401,
            });
            warn_refresh_failed(&c, "", &error, None);
        }
        let text = logs.text();
        assert!(
            text.contains(
                "credential refresh failed for acme (p.json): status 401: plugin refresh failed: invalid_grant;"
            ),
            "{text}"
        );
        assert!(
            text.contains("status 401: plugin refresh failed; next attempt"),
            "an unknown code, which could be a token, is left out: {text}"
        );
        assert!(!text.contains("abc123"), "{text}");
    }

    /// The loop sets no timer while nothing can come due, and a credential added later
    /// is tried after the store change, not on a schedule.
    #[tokio::test]
    async fn refresh_loop_sleeps_until_the_store_changes() {
        let unreachable = "http://127.0.0.1:1/token";
        let oauth = cpa_exec::oauth::OAuth::with_endpoints(wreq::Client::new(), unreachable, unreachable, unreachable);
        let rt = Arc::new(crate::testing::runtime(
            Config::parse("").unwrap(),
            Vec::new(),
            Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1")
                    .unwrap()
                    .with_oauth(oauth),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        ));
        rt.start_auto_refresh();
        tokio::time::sleep(Duration::from_millis(50)).await;
        let mut due = cred("a.json", "claude", false);
        due.metadata.insert("refresh_token".into(), "fake-refresh".into());
        due.metadata.insert(
            "expired".into(),
            (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339().into(),
        );
        rt.store.reconcile(vec![due]);
        let added = rt.store.get("a.json").unwrap();
        // The refresh fails (no token endpoint), which backs off for five minutes.
        tokio::time::timeout(Duration::from_secs(20), async {
            loop {
                let retry = rt.refresh_state.lock().unwrap().retry_at(&added);
                if retry.is_some_and(|at| at > Instant::now() + Duration::from_secs(200)) {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        })
        .await
        .expect("the added credential was tried and backed off");
        rt.stop_auto_refresh();
    }

    #[tokio::test]
    async fn every_lease_reports_exactly_once() {
        let store = CredentialStore::new(vec![cred("a.json", "claude", false)]);
        let stats = |s, f, c| AttemptStats {
            success: s,
            failure: f,
            cancelled: c,
        };

        // Dropped without completing (client gone mid-execute): cancelled.
        drop(store.select(sel("claude")).unwrap());
        assert_eq!(store.stats(), stats(0, 0, 1));
        // Completed explicitly: the drop that follows does not report again.
        store.select(sel("claude")).unwrap().complete(Outcome::Success);
        assert_eq!(store.stats(), stats(1, 0, 1));

        // A stream that errors and would then hang forever: the wrapper stops after Err.
        let err = ExecError::local(502, FailureScope::Transport, "boom");
        let inner = futures_util::stream::iter(vec![Ok(Bytes::from_static(b"a")), Err(err)])
            .chain(futures_util::stream::pending())
            .boxed();
        let mut s = Completing::new(inner, store.select(sel("claude")).unwrap());
        assert!(s.next().await.unwrap().is_ok());
        assert!(s.next().await.unwrap().is_err());
        assert!(s.next().await.is_none(), "fused after the first error");
        drop(s);
        assert_eq!(store.stats(), stats(1, 1, 1));

        let mut done = Completing::new(
            futures_util::stream::empty().boxed(),
            store.select(sel("claude")).unwrap(),
        );
        assert!(done.next().await.is_none());
        drop(done);
        assert_eq!(store.stats(), stats(2, 1, 1));

        // Dropped mid-stream: cancelled.
        let mut mid = Completing::new(
            futures_util::stream::iter(vec![Ok(Bytes::new())])
                .chain(futures_util::stream::pending())
                .boxed(),
            store.select(sel("claude")).unwrap(),
        );
        assert!(mid.next().await.is_some());
        drop(mid);
        assert_eq!(store.stats(), stats(2, 1, 2));
    }

    /// A remote lease ends once, never through the local scheduler, and only after the
    /// upstream body it was streaming has been dropped.
    #[tokio::test]
    async fn remote_leases_end_after_the_upstream_body_closes() {
        use std::sync::atomic::AtomicBool;
        struct Probe(Arc<AtomicBool>);
        impl Drop for Probe {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }
        let store = CredentialStore::new(vec![cred("a.json", "claude", false)]);
        let dropped = Arc::new(AtomicBool::new(false));
        let observed = Arc::new(Mutex::new(Vec::new()));
        let mut lease = store.select(sel("claude")).unwrap();
        let (seen, probe) = (observed.clone(), dropped.clone());
        lease.remote = Some(crate::remote::RemoteEnd {
            end: Some(Box::new(move || {
                seen.lock().unwrap().push(probe.load(Ordering::SeqCst));
                None
            })),
            releases: Default::default(),
            cancel: None,
            private: Default::default(),
        });
        let guard = Probe(dropped.clone());
        let err = ExecError::local(502, FailureScope::Transport, "boom");
        let inner = futures_util::stream::iter(vec![Ok(Bytes::from_static(b"a")), Err(err)])
            .chain(futures_util::stream::pending())
            .map(move |item| {
                let _ = &guard;
                item
            })
            .boxed();
        let mut stream = Completing::new(inner, lease);
        assert!(stream.next().await.unwrap().is_ok());
        assert!(observed.lock().unwrap().is_empty(), "still streaming");
        assert!(stream.next().await.unwrap().is_err());
        assert_eq!(
            *observed.lock().unwrap(),
            vec![true],
            "body dropped first, then one end"
        );
        drop(stream);
        assert_eq!(observed.lock().unwrap().len(), 1);
        assert_eq!(
            store.stats(),
            AttemptStats::default(),
            "the local scheduler saw nothing"
        );
    }
    /// Go binds the attempt's cancellation to the Home selection: a drain closes the
    /// upstream body and ends the lease while the client has stopped reading
    /// (backpressure), and the reader then sees the cancellation once.
    #[tokio::test]
    async fn a_drain_ends_a_remote_stream_the_client_stopped_reading() {
        use std::sync::atomic::AtomicBool;
        struct Probe(Arc<AtomicBool>);
        impl Drop for Probe {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }
        let store = CredentialStore::new(vec![cred("a.json", "claude", false)]);
        let dropped = Arc::new(AtomicBool::new(false));
        let observed = Arc::new(Mutex::new(Vec::new()));
        let mut lease = store.select(sel("claude")).unwrap();
        let (seen, probe) = (observed.clone(), dropped.clone());
        let (cancel_tx, cancel) = tokio::sync::watch::channel(false);
        lease.remote = Some(crate::remote::RemoteEnd {
            end: Some(Box::new(move || {
                seen.lock().unwrap().push(probe.load(Ordering::SeqCst));
                None
            })),
            releases: Default::default(),
            cancel: Some(cancel),
            private: Default::default(),
        });
        let guard = Probe(dropped.clone());
        let inner = futures_util::stream::iter(vec![Ok(Bytes::from_static(b"a"))])
            .chain(futures_util::stream::pending())
            .map(move |item| {
                let _ = &guard;
                item
            })
            .boxed();
        let mut stream = Completing::new(inner, lease);
        assert!(stream.next().await.unwrap().is_ok());
        // The client stops polling; the dispatcher drains.
        cancel_tx.send(true).unwrap();
        for _ in 0..100 {
            if !observed.lock().unwrap().is_empty() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(
            *observed.lock().unwrap(),
            vec![true],
            "body dropped first, then one end, without a poll"
        );
        let error = stream.next().await.unwrap().unwrap_err();
        assert_eq!(String::from_utf8_lossy(&error.body), "context canceled");
        assert!(stream.next().await.is_none());
        drop(stream);
        assert_eq!(observed.lock().unwrap().len(), 1);
    }
}