synaps-core 0.11.0

Foundation types, config, session, auth, protocol — leaf crate for agent-runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
//! G5 — pure capacity-selection policy for multi-account OAuth providers.
//!
//! This module has **no I/O, no clock and no network**. Every decision is a
//! deterministic function of `now_ms` and the caller-supplied per-account
//! capacity views ([`AccountCapacity`]), so it is trivially testable with a
//! synthetic clock and can be shared by the broker (`AccountSelector::Auto`),
//! the Codex stream failover and the quota keeper.
//!
//! ## Invariants
//!
//! * **Fail closed.** Stale, unknown, malformed, unsupported or auth-errored
//!   quota is *not* capacity. An account is only advertised as ready when a
//!   fresh observation shows headroom on every applicable limit.
//! * **All applicable limits count.** Every window that applies to the
//!   requested model (account-wide windows plus model-scoped windows naming
//!   that model) must have headroom. A window with no usable evidence makes
//!   the account ineligible.
//! * **Exclusions are absolute.** Cooling-down, exhausted, excluded and
//!   auth-errored accounts are never selected.
//! * **Explicit never falls back.** When a specific account is requested only
//!   that account is considered; it is selected or the request fails.
//! * **Deterministic preference.** Ties are broken by the operator's
//!   preference order, then by storage key, so equal inputs always yield the
//!   same seat.
//! * **One bounded failover.** [`failover`] permits a single switch to a
//!   different eligible seat, only on a recognized pre-output quota failure,
//!   never after any output or tool activity and never on an ordinary 429.
//! * **Perishable capacity first.** [`Strategy::SoonestReset`] ranks eligible
//!   seats by tier — urgent anchored, then unanchored (first use starts the
//!   clock), then far anchored, then no reset evidence — soonest budget reset
//!   first, so capacity about to expire is burned before it is lost.
//!   Stickiness keeps the currently pinned seat unless a candidate sits in a
//!   strictly higher tier (or, within tier 1, resets strictly sooner); an
//!   ineligible current seat is never kept and an excluded one never re-picked.

use serde::{Deserialize, Serialize};

use super::account::CredentialRef;
use super::provider::OAuthProviderId;

/// Serde shim: [`CredentialRef`] round-trips as its storage key
/// (`"openai-codex@astra2"`), which is already validated text.
pub mod cred_serde {
    use super::CredentialRef;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(c: &CredentialRef, s: S) -> Result<S::Ok, S::Error> {
        c.storage_key().serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<CredentialRef, D::Error> {
        let raw = String::deserialize(d)?;
        CredentialRef::parse_storage_key(&raw)
            .ok_or_else(|| serde::de::Error::custom(format!("invalid credential key '{raw}'")))
    }
}

/// Lower bound (inclusive) for classifying a window as "weekly" from its
/// provider-reported duration. Six days leaves room for providers that report
/// approximate durations; never infer weekliness from a name like `primary`.
pub const WEEKLY_WINDOW_MIN_MS: u64 = 6 * 24 * 60 * 60 * 1000;
/// Upper bound (inclusive) for the weekly classification.
pub const WEEKLY_WINDOW_MAX_MS: u64 = 8 * 24 * 60 * 60 * 1000;
/// Observation timestamps further in the future than this are malformed
/// (a small allowance for clock skew between the provider and this host).
pub const MAX_FUTURE_OBSERVATION_SKEW_MS: u64 = 5 * 60 * 1000;
/// Default utilization percentage at/above which a window is exhausted.
pub const DEFAULT_EXHAUSTED_AT_PERCENT: f64 = 100.0;
/// Default [`SelectionRequest::urgent_horizon_ms`]: an anchored budget window
/// resetting within this horizon is "urgent" — its unused capacity is about
/// to be lost, so it ranks first under [`Strategy::SoonestReset`].
pub const DEFAULT_URGENT_HORIZON_MS: u64 = 24 * 60 * 60 * 1000;
/// Tolerance for [`is_unanchored`]: a window whose reported reset is within
/// this distance of `observed_at + duration` is sliding with the observation
/// rather than fixed on the provider's calendar. Absorbs poll latency and
/// clock skew between the provider and this host.
pub const UNANCHORED_TOLERANCE_MS: u64 = 5 * 60 * 1000;
/// Maximum `used_percent` (inclusive) for a window to count as "≈0 % used"
/// in [`is_unanchored`]. A window with real consumption has, by definition,
/// already been anchored by that first use.
pub const UNANCHORED_MAX_USED_PERCENT: f64 = 0.5;

// ── Inputs ───────────────────────────────────────────────────────────────────

/// One provider-reported rate-limit window, normalized by the usage adapter.
///
/// `models == None` means the window applies to every model on the account;
/// `Some(list)` scopes it to exactly those model ids.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WindowLimit {
    /// Provider-side identifier (e.g. `primary`, `seven_day_sonnet`). Display only.
    pub id: String,
    /// Window length as reported by the provider, if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
    /// Utilization in percent (`0..=100`), if reported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub used_percent: Option<f64>,
    /// Provider's explicit "limit reached" flag, if reported. Adapters must
    /// set `Some(false)` ONLY when the provider asserts it (it counts as
    /// headroom evidence when no percentage is available); an absent flag
    /// must be `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit_reached: Option<bool>,
    /// Provider-reported reset instant (epoch ms), if reported. Authoritative.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resets_at_ms: Option<u64>,
    /// Model scope. `None` = account-wide.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub models: Option<Vec<String>>,
}

/// Fail-closed verdict for one window.
#[derive(Debug, Clone, PartialEq)]
pub enum WindowVerdict {
    /// Evidence of remaining capacity.
    Headroom { used_percent: Option<f64> },
    /// Evidence the window is used up (or reports contradictory/past data).
    Exhausted { resets_at_ms: Option<u64> },
    /// No usable evidence (missing or malformed fields).
    Unknown,
}

/// Whether a provider availability/window entry (`sonnet`, `gpt-6-astra`)
/// names the requested model id (`claude-sonnet-4-6`). Exact
/// (case-insensitive) match, or the entry equals one `-`/`_`/`/`/`:`/`.`
/// separated token of the request — the same rule the usage adapter uses.
pub fn model_matches(entry: &str, requested: &str) -> bool {
    let entry = entry.trim().to_ascii_lowercase();
    let req = requested.trim().to_ascii_lowercase();
    if entry.is_empty() || req.is_empty() {
        return false;
    }
    if entry == req {
        return true;
    }
    req.split(['-', '_', '/', ':', '.']).any(|tok| tok == entry)
}

impl WindowLimit {
    /// Whether this window constrains `model` (`None` = any model).
    pub fn applies_to(&self, model: Option<&str>) -> bool {
        match (&self.models, model) {
            (None, _) => true,
            // A model-scoped window cannot be matched without a model; treat
            // it as applicable so an unknown model never bypasses a limit.
            (Some(_), None) => true,
            (Some(list), Some(m)) => list.iter().any(|x| model_matches(x, m)),
        }
    }

    /// Weekly classification from the reported duration only.
    pub fn is_weekly(&self) -> bool {
        matches!(self.duration_ms, Some(d) if (WEEKLY_WINDOW_MIN_MS..=WEEKLY_WINDOW_MAX_MS).contains(&d))
    }

    /// Capacity verdict. Exhaustion threshold is inclusive. A provider
    /// `limit_reached: true` flag always wins; malformed percentages are
    /// unknown (never capacity). An invalid threshold (non-finite or outside
    /// `0..=100`) fails closed: the verdict is `Unknown`.
    pub fn verdict(&self, exhausted_at_percent: f64) -> WindowVerdict {
        if !valid_threshold(exhausted_at_percent) {
            return WindowVerdict::Unknown;
        }
        if self.limit_reached == Some(true) {
            return WindowVerdict::Exhausted {
                resets_at_ms: self.resets_at_ms,
            };
        }
        let used = match self.used_percent {
            // An overrun (> 100, bounded) is a spent window, not unknown.
            Some(p) if p > 100.0 && p <= super::usage::OVERRUN_PERCENT_MAX => Some(100.0),
            Some(p) if !p.is_finite() || !(0.0..=100.0).contains(&p) => {
                return WindowVerdict::Unknown
            }
            other => other,
        };
        match used {
            Some(p) if p >= exhausted_at_percent => WindowVerdict::Exhausted {
                resets_at_ms: self.resets_at_ms,
            },
            Some(p) => WindowVerdict::Headroom {
                used_percent: Some(p),
            },
            None if self.limit_reached == Some(false) => {
                WindowVerdict::Headroom { used_percent: None }
            }
            None => WindowVerdict::Unknown,
        }
    }
}

/// Whether an exhaustion threshold is usable (finite, `0..=100`).
pub fn valid_threshold(percent: f64) -> bool {
    percent.is_finite() && (0.0..=100.0).contains(&percent)
}

/// Tri-state model availability. `Unknown` is preserved as unknown — it is
/// never coerced to "available".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelState {
    Available,
    Exhausted,
    Unknown,
}

/// Provider-reported model availability for an account.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelAvailability {
    pub model: String,
    pub state: ModelState,
}

/// What the usage adapter learned about one account.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum QuotaObservation {
    /// A well-formed reading.
    Ok {
        windows: Vec<WindowLimit>,
        /// `None` = the provider exposes no per-model availability.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        models: Option<Vec<ModelAvailability>>,
    },
    /// Credential rejected (401/403) — never capacity, needs re-login.
    AuthError,
    /// Provider has no usage endpoint / adapter — unknown, never capacity.
    Unsupported,
    /// Response could not be parsed — never capacity.
    Malformed,
    /// No reading available (transport failure, never fetched, …).
    Unknown,
}

/// Per-account capacity view supplied by the caller.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccountCapacity {
    #[serde(with = "cred_serde")]
    pub credential: CredentialRef,
    /// Snapshot time (epoch ms). `None` = never observed → not capacity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed_at_ms: Option<u64>,
    pub observation: QuotaObservation,
    /// Client-side cooldown (e.g. after a provider limit response). Epoch ms.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cooldown_until_ms: Option<u64>,
    /// Why there is no reading, when the read itself failed (a usage 429,
    /// a refresh timeout, …). Never capacity; carried into the rejection
    /// so the failure can be named instead of a bare "quota unknown".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure: Option<ObservationFailure>,
}

impl AccountCapacity {
    /// Convenience constructor for an account with no observation yet.
    pub fn unobserved(credential: CredentialRef) -> Self {
        Self {
            credential,
            observed_at_ms: None,
            observation: QuotaObservation::Unknown,
            cooldown_until_ms: None,
            failure: None,
        }
    }

    /// An account whose observation failed with `failure`.
    pub fn failed(credential: CredentialRef, failure: ObservationFailure) -> Self {
        Self {
            observation: failure.observation(),
            failure: Some(failure),
            ..Self::unobserved(credential)
        }
    }
}

// ── Typed failure kinds ──────────────────────────────────────────────────────

/// Why one account could not serve a request, as a stable snake_case kind:
/// a failed observation (usage read, token refresh, credential store) or
/// the policy verdict on a good one. Secret-free; safe for logs and users.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccountFailureKind {
    /// A provider limit was reported for the account (client cooldown).
    CoolingDown,
    /// A usage window is at its limit.
    Exhausted,
    /// The provider reports the requested model as used up.
    ModelUnavailable,
    /// The usage endpoint itself answered 429. Not proof of exhaustion.
    UsageRateLimited,
    UsageTimeout,
    /// The usage endpoint answered another non-2xx status (or a redirect).
    UsageUpstream,
    UsageTransport,
    /// The usage response could not be parsed (or was too large).
    UsageMalformed,
    /// The usage endpoint rejected the access token (401/403).
    UsageUnauthorized,
    /// The token refresh failed for a network/provider reason (5xx, 429,
    /// timeout).
    RefreshTransient,
    /// Another refresh of the account was still running.
    RefreshLockBusy,
    /// A local refresh failure (lock file I/O, the refresh task, a forced-
    /// refresh cooldown).
    RefreshOther,
    /// The token endpoint rejected the login (e.g. `invalid_grant`).
    RefreshRejected,
    /// The user must act outside synaps (corrupt store, billing).
    RefreshActionRequired,
    /// The slot disappeared between listing and reading.
    CredentialMissing,
    /// The credential store could not be read.
    CredentialStore,
    /// The credential was rejected; no finer cause recorded.
    AuthError,
    /// No usage adapter for the provider.
    Unsupported,
    /// No reading and no recorded cause.
    QuotaUnknown,
    StaleSnapshot,
    WindowUnknown,
    ModelUnknown,
    NoLimitEvidence,
    /// Excluded by the caller (e.g. a duplicate of another slot's seat).
    Excluded,
    NotPresent,
    InvalidLabel,
    /// A kind this build does not know (from a newer daemon). Claims no
    /// remedy: not transient, not a login, not an action, not limited.
    #[serde(other)]
    Unknown,
}

impl AccountFailureKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::CoolingDown => "cooling_down",
            Self::Exhausted => "exhausted",
            Self::ModelUnavailable => "model_unavailable",
            Self::UsageRateLimited => "usage_rate_limited",
            Self::UsageTimeout => "usage_timeout",
            Self::UsageUpstream => "usage_upstream",
            Self::UsageTransport => "usage_transport",
            Self::UsageMalformed => "usage_malformed",
            Self::UsageUnauthorized => "usage_unauthorized",
            Self::RefreshTransient => "refresh_transient",
            Self::RefreshLockBusy => "refresh_lock_busy",
            Self::RefreshOther => "refresh_other",
            Self::RefreshRejected => "refresh_rejected",
            Self::RefreshActionRequired => "refresh_action_required",
            Self::CredentialMissing => "credential_missing",
            Self::CredentialStore => "credential_store",
            Self::AuthError => "auth_error",
            Self::Unsupported => "unsupported",
            Self::QuotaUnknown => "quota_unknown",
            Self::StaleSnapshot => "stale_snapshot",
            Self::WindowUnknown => "window_unknown",
            Self::ModelUnknown => "model_unknown",
            Self::NoLimitEvidence => "no_limit_evidence",
            Self::Excluded => "excluded",
            Self::NotPresent => "not_present",
            Self::InvalidLabel => "invalid_label",
            Self::Unknown => "unknown",
        }
    }

    /// Only a new login for the account can fix it.
    pub fn needs_login(self) -> bool {
        matches!(
            self,
            Self::UsageUnauthorized
                | Self::RefreshRejected
                | Self::CredentialMissing
                | Self::AuthError
        )
    }

    /// Capacity is unproven, not absent: the same request can succeed later
    /// without the user doing anything.
    pub fn is_transient(self) -> bool {
        matches!(
            self,
            Self::UsageRateLimited
                | Self::UsageTimeout
                | Self::UsageUpstream
                | Self::UsageTransport
                | Self::RefreshTransient
                | Self::RefreshLockBusy
                | Self::RefreshOther
        )
    }

    /// The account is at a provider limit (reported or measured).
    pub fn is_limited(self) -> bool {
        matches!(
            self,
            Self::CoolingDown | Self::Exhausted | Self::ModelUnavailable
        )
    }

    /// Only an action outside synaps fixes it (a corrupt or missing store,
    /// a billing requirement); neither a retry nor a login does.
    pub fn needs_action(self) -> bool {
        matches!(self, Self::RefreshActionRequired | Self::CredentialStore)
    }
}

impl std::fmt::Display for AccountFailureKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A failed observation: its kind plus the HTTP status and `Retry-After`
/// the provider sent, when there were any. Never token material or body
/// bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObservationFailure {
    pub kind: AccountFailureKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_after_s: Option<u64>,
}

impl ObservationFailure {
    pub fn new(kind: AccountFailureKind) -> Self {
        Self {
            kind,
            http_status: None,
            retry_after_s: None,
        }
    }

    pub fn with_status(mut self, status: u16) -> Self {
        self.http_status = Some(status);
        self
    }

    pub fn with_retry_after(mut self, secs: Option<u64>) -> Self {
        self.retry_after_s = secs;
        self
    }

    /// The (never-capacity) observation this failure stands for.
    pub fn observation(&self) -> QuotaObservation {
        match self.kind {
            k if k.needs_login() => QuotaObservation::AuthError,
            AccountFailureKind::UsageMalformed => QuotaObservation::Malformed,
            AccountFailureKind::Unsupported => QuotaObservation::Unsupported,
            _ => QuotaObservation::Unknown,
        }
    }
}

impl std::fmt::Display for ObservationFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.kind)?;
        if let Some(status) = self.http_status {
            write!(f, ", HTTP {status}")?;
        }
        if let Some(secs) = self.retry_after_s {
            write!(f, ", retry after {secs}s")?;
        }
        Ok(())
    }
}

/// Ordering strategy among eligible accounts. All are deterministic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Strategy {
    /// First eligible account in the operator's preference list; unlisted
    /// accounts follow in storage-key order.
    PreferenceOrder,
    /// Lowest maximum utilization across applicable windows; ties broken by
    /// preference order, then storage key. Accounts whose utilization is
    /// unknown (but proven not limit-reached) sort after known ones.
    LowestUtilization,
    /// Perishable capacity first. Eligible seats are ranked by
    /// [`Eligible::tier`] (1 = urgent anchored, 2 = unanchored, 3 = anchored
    /// but not urgent, 4 = no reset evidence); tiers 1 and 3 order by soonest
    /// budget reset, tier 2 by preference then storage key, tier 4 by lowest
    /// utilization. Remaining ties: lowest utilization → preference → storage
    /// key. The only strategy to which [`SelectionRequest::sticky`] applies.
    SoonestReset,
}

/// A selection request. All times are epoch milliseconds.
#[derive(Debug, Clone)]
pub struct SelectionRequest<'a> {
    pub provider: OAuthProviderId,
    /// Model the request is for; `None` = any (model-scoped windows still apply).
    pub model: Option<&'a str>,
    pub now_ms: u64,
    /// Observations older than this are stale (not capacity).
    pub max_snapshot_age_ms: u64,
    /// Operator preference (labels, `default` for the bare slot).
    pub preference: &'a [String],
    /// Explicit account label; when set no other account is considered.
    pub explicit_account: Option<&'a str>,
    /// Accounts that must not be selected (e.g. a seat that just failed).
    pub exclude: &'a [CredentialRef],
    pub strategy: Strategy,
    /// Utilization percent at/above which a window counts as exhausted.
    pub exhausted_at_percent: f64,
    /// The seat currently pinned for this provider, if any. Only consulted
    /// when [`sticky`](Self::sticky) is set under [`Strategy::SoonestReset`];
    /// it never bypasses eligibility or exclusion.
    pub current: Option<&'a CredentialRef>,
    /// An anchored budget window resetting within this many ms of `now_ms`
    /// is urgent (tier 1). Default [`DEFAULT_URGENT_HORIZON_MS`].
    pub urgent_horizon_ms: u64,
    /// Keep [`current`](Self::current) when it is still eligible unless a
    /// candidate sits in a strictly higher tier (or both are tier 1 and the
    /// candidate resets strictly sooner). Avoids seat thrash and prompt-cache
    /// loss. Applies to [`Strategy::SoonestReset`] only; `false` in
    /// [`new`](Self::new) so other strategies are unaffected.
    pub sticky: bool,
    /// Last successful readings for accounts whose current usage read
    /// failed transiently (usage-endpoint 429, 5xx, timeout, transport).
    /// Such an account (observation [`QuotaObservation::Unknown`]) is
    /// evaluated on its reading here instead: strictly younger than
    /// [`grace_max_age_ms`](Self::grace_max_age_ms), never past an exhausted
    /// window, an exclusion or a cooldown. Graced seats rank after every
    /// fresh one, but a graced sticky seat stays (a read failure alone is no
    /// reason to switch: the sticky rule judges the graced reading exactly
    /// as it would a fresh one). Empty in [`new`](Self::new).
    pub grace: &'a [AccountCapacity],
    /// Oldest graced reading that still counts. Default
    /// [`USAGE_READ_GRACE`](super::usage_reads::USAGE_READ_GRACE).
    pub grace_max_age_ms: u64,
}

impl<'a> SelectionRequest<'a> {
    /// Minimal request with defaults: any model, no preference/exclusions,
    /// lowest-utilization strategy, 100 % exhaustion threshold, no current
    /// seat, default urgent horizon, not sticky.
    pub fn new(provider: OAuthProviderId, now_ms: u64, max_snapshot_age_ms: u64) -> Self {
        Self {
            provider,
            model: None,
            now_ms,
            max_snapshot_age_ms,
            preference: &[],
            explicit_account: None,
            exclude: &[],
            strategy: Strategy::LowestUtilization,
            exhausted_at_percent: DEFAULT_EXHAUSTED_AT_PERCENT,
            current: None,
            urgent_horizon_ms: DEFAULT_URGENT_HORIZON_MS,
            sticky: false,
            grace: &[],
            grace_max_age_ms: super::usage_reads::USAGE_READ_GRACE.as_millis() as u64,
        }
    }

    /// Like [`new`](Self::new) but with [`Strategy::SoonestReset`], sticky
    /// selection and the default urgent horizon. Set
    /// [`current`](Self::current) for stickiness to have any effect.
    pub fn soonest_reset(provider: OAuthProviderId, now_ms: u64, max_snapshot_age_ms: u64) -> Self {
        Self {
            strategy: Strategy::SoonestReset,
            sticky: true,
            ..Self::new(provider, now_ms, max_snapshot_age_ms)
        }
    }
}

// ── Outputs ──────────────────────────────────────────────────────────────────

/// Why an account was not selected. Secret-free, display-ready.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "reason", rename_all = "snake_case")]
pub enum RejectReason {
    /// Snapshot missing or older than the allowed age.
    Stale {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        age_ms: Option<u64>,
    },
    /// Observation timestamp is implausibly in the future or fields invalid.
    Malformed,
    Unknown,
    Unsupported,
    AuthError,
    CoolingDown {
        until_ms: u64,
    },
    Exhausted {
        window: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        resets_at_ms: Option<u64>,
    },
    /// An applicable window carries no usable evidence.
    WindowUnknown {
        window: String,
    },
    /// The reading has no applicable window at all — no limit evidence.
    NoLimitEvidence,
    ModelUnavailable {
        model: String,
    },
    /// The provider lists the model with unknown availability — not capacity.
    ModelUnknown {
        model: String,
    },
    /// Present in `exclude`.
    Excluded,
    /// The explicitly requested account is not among the candidates.
    NotPresent,
    /// The explicitly requested label fails the label grammar.
    InvalidLabel {
        label: String,
    },
    /// Eligible, but another eligible account ranked higher. `rank` is the
    /// 1-based position in the final ranking (the winner is rank 1), so
    /// callers can print the full ordered table.
    Outranked {
        #[serde(default)]
        rank: u32,
    },
}

impl std::fmt::Display for RejectReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Stale { age_ms: Some(a) } => write!(f, "stale snapshot ({}s old)", a / 1000),
            Self::Stale { age_ms: None } => write!(f, "no snapshot"),
            Self::Malformed => write!(f, "malformed snapshot"),
            Self::Unknown => write!(f, "quota unknown"),
            Self::Unsupported => write!(f, "usage unsupported"),
            Self::AuthError => write!(f, "auth error"),
            Self::CoolingDown { until_ms } => write!(f, "cooling down until {until_ms}"),
            Self::Exhausted {
                window,
                resets_at_ms: Some(r),
            } => write!(f, "window '{window}' exhausted, resets at {r}"),
            Self::Exhausted { window, .. } => write!(f, "window '{window}' exhausted"),
            Self::WindowUnknown { window } => write!(f, "window '{window}' has no evidence"),
            Self::NoLimitEvidence => write!(f, "no applicable limit evidence"),
            Self::ModelUnavailable { model } => write!(f, "model '{model}' unavailable"),
            Self::ModelUnknown { model } => write!(f, "model '{model}' availability unknown"),
            Self::Excluded => write!(f, "excluded"),
            Self::NotPresent => write!(f, "account not present"),
            Self::InvalidLabel { label } => write!(f, "invalid account label '{label}'"),
            Self::Outranked { rank } => write!(f, "eligible; outranked (rank {rank})"),
        }
    }
}

/// One rejected candidate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Rejection {
    #[serde(with = "cred_serde")]
    pub credential: CredentialRef,
    pub reason: RejectReason,
    /// The failed observation behind the verdict, when it is known: for an
    /// observation verdict (`unknown`, `auth_error`, `malformed`,
    /// `unsupported`) and for a cooldown, which does not erase what the
    /// account's last read or refresh said.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cause: Option<ObservationFailure>,
    /// Diagnostics only: when this account can be used again as far as its
    /// cooldown and its exhausted applicable windows know, i.e. the LATEST
    /// of them (every exhausted window must reset). `None` when it has
    /// neither, or an exhausted window has no future reset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usable_after_ms: Option<u64>,
}

impl Rejection {
    /// `reason`, plus the cause in parentheses when there is one.
    pub fn describe(&self) -> String {
        match &self.cause {
            Some(cause) => format!("{} ({cause})", self.reason),
            None => self.reason.to_string(),
        }
    }
}

/// One account's part in a failed selection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountFailure {
    /// Account label (`default` for the bare slot). Never an identity.
    pub account: String,
    pub kind: AccountFailureKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_after_s: Option<u64>,
    /// Cooldown end or exhausted-window reset, epoch ms, when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub until_ms: Option<u64>,
    /// The account is cooling down (a reported provider limit), whatever
    /// `kind` says about its last observation.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub cooling_down: bool,
}

impl AccountFailure {
    /// The account's failure for a rejection; `None` for an account that
    /// was eligible but outranked (not a failure). A cooling account keeps
    /// the kind of its last failed read or refresh, with `cooling_down` set
    /// beside it; `until_ms` is the rejection's `usable_after_ms`.
    pub fn from_rejection(rejection: &Rejection) -> Option<Self> {
        use AccountFailureKind as K;
        let mut out = Self {
            account: rejection.credential.account.label_str().to_string(),
            kind: K::QuotaUnknown,
            http_status: None,
            retry_after_s: None,
            until_ms: rejection.usable_after_ms,
            cooling_down: matches!(rejection.reason, RejectReason::CoolingDown { .. }),
        };
        if let RejectReason::Outranked { .. } = rejection.reason {
            return None;
        }
        if let Some(cause) = &rejection.cause {
            out.kind = cause.kind;
            out.http_status = cause.http_status;
            out.retry_after_s = cause.retry_after_s;
            return Some(out);
        }
        out.kind = match &rejection.reason {
            RejectReason::Outranked { .. } => return None,
            RejectReason::CoolingDown { .. } => K::CoolingDown,
            RejectReason::Exhausted { .. } => K::Exhausted,
            RejectReason::Stale { .. } => K::StaleSnapshot,
            RejectReason::Malformed => K::UsageMalformed,
            RejectReason::Unknown => K::QuotaUnknown,
            RejectReason::Unsupported => K::Unsupported,
            RejectReason::AuthError => K::AuthError,
            RejectReason::WindowUnknown { .. } => K::WindowUnknown,
            RejectReason::NoLimitEvidence => K::NoLimitEvidence,
            RejectReason::ModelUnavailable { .. } => K::ModelUnavailable,
            RejectReason::ModelUnknown { .. } => K::ModelUnknown,
            RejectReason::Excluded => K::Excluded,
            RejectReason::NotPresent => K::NotPresent,
            RejectReason::InvalidLabel { .. } => K::InvalidLabel,
        };
        Some(out)
    }

    /// Cooling down or at a provider limit: the account counts as limited
    /// for the top-level kind, whatever its last read said.
    pub fn is_limited(&self) -> bool {
        self.cooling_down || self.kind.is_limited()
    }

    /// Counts toward the headline: not limited, and not an excluded slot
    /// (a duplicate of a seat that is already counted).
    pub fn is_live(&self) -> bool {
        !self.is_limited() && self.kind != AccountFailureKind::Excluded
    }

    /// `label:kind[:status][:cooling]`, the log form; `:cooling` marks a
    /// cooling account whose kind is its last failed read or refresh.
    pub fn log_form(&self) -> String {
        let mut out = format!("{}:{}", self.account, self.kind);
        if let Some(status) = self.http_status {
            out.push_str(&format!(":{status}"));
        }
        if self.cooling_down && self.kind != AccountFailureKind::CoolingDown {
            out.push_str(":cooling");
        }
        out
    }
}

/// The one kind that explains a failed automatic selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SelectionFailureKind {
    /// No account is logged in for the provider.
    NoCredentials,
    /// At least one account's usage read or token refresh failed for a
    /// transient reason: capacity is unproven, not absent.
    UsageReadFailed,
    /// Every account that is not cooling down needs a new login.
    CredentialRejected,
    /// Every account is cooling down or at a usage limit.
    AllCoolingDown,
    /// The readings succeeded but proved no capacity.
    QuotaUnknown,
    /// The chosen slot kept changing while its capacity was being proven.
    SeatChurn,
    /// A remote broker answered "no account available" (its own log has
    /// the reason).
    RemoteNoCapacity,
    /// Every account that is not limited needs a login or an action outside
    /// synaps (a corrupt or missing store, a billing requirement), and at
    /// least one needs the action.
    ActionRequired,
    /// The credential store could not be listed, so no account was read.
    CredentialStore,
    /// A kind this build does not know (from a newer daemon).
    #[serde(other)]
    Unknown,
}

impl SelectionFailureKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NoCredentials => "no_credentials",
            Self::UsageReadFailed => "usage_read_failed",
            Self::CredentialRejected => "credential_rejected",
            Self::AllCoolingDown => "all_cooling_down",
            Self::QuotaUnknown => "quota_unknown",
            Self::SeatChurn => "seat_churn",
            Self::RemoteNoCapacity => "remote_no_capacity",
            Self::ActionRequired => "action_required",
            Self::CredentialStore => "credential_store",
            Self::Unknown => "unknown",
        }
    }
}

impl std::fmt::Display for SelectionFailureKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A failed automatic selection: the top-level kind, every account's part
/// in it, and the earliest known reset among limited accounts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SelectionFailure {
    pub kind: SelectionFailureKind,
    #[serde(default)]
    pub accounts: Vec<AccountFailure>,
    /// Earliest future cooldown end or exhausted-window reset, epoch ms.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub earliest_reset_ms: Option<u64>,
    /// For `usage_read_failed`: when the held usage reads go to the network
    /// again (epoch ms), i.e. the earliest time a new selection reads usage.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage_read_retry_ms: Option<u64>,
}

impl SelectionFailure {
    /// A failure with no per-account detail.
    pub fn new(kind: SelectionFailureKind) -> Self {
        Self {
            kind,
            accounts: Vec::new(),
            earliest_reset_ms: None,
            usage_read_retry_ms: None,
        }
    }

    /// Classify a `NoCapacity` result. The headline is what the user can act
    /// on now: it is classified over accounts that aren't cooling down. A
    /// cooling account's read failure is shown per account. An account
    /// counts as limited when it is cooling down or at a provider limit,
    /// whatever its last read said; only the other accounts' kinds pick the
    /// headline; an `excluded` account (a duplicate of a counted seat) never
    /// does. First match wins: no accounts → `no_credentials`; a
    /// transient failure on an account that is not limited →
    /// `usage_read_failed`; every account limited → `all_cooling_down`;
    /// every account not limited needs a login → `credential_rejected`; each
    /// needs a login or an action outside synaps (at least one an action) →
    /// `action_required`; else `quota_unknown`. The earliest reset is the
    /// earliest time some limited account is usable again: the minimum of
    /// their `until`, skipping accounts that also need a login or an action
    /// (their cooldown's end alone won't make them usable).
    pub fn from_rejections(rejections: &[Rejection], now_ms: u64) -> Self {
        use SelectionFailureKind as K;
        let accounts: Vec<_> = rejections
            .iter()
            .filter_map(AccountFailure::from_rejection)
            .collect();
        // An excluded slot duplicates a seat that is already counted (it is
        // excluded before its cooldown is checked), so it never picks the
        // headline.
        let live: Vec<_> = accounts.iter().filter(|a| a.is_live()).collect();
        let kind = if accounts.is_empty() {
            K::NoCredentials
        } else if live.iter().any(|a| a.kind.is_transient()) {
            K::UsageReadFailed
        } else if live.is_empty() && accounts.iter().any(AccountFailure::is_limited) {
            K::AllCoolingDown
        } else if live.is_empty() {
            K::QuotaUnknown
        } else if live.iter().all(|a| a.kind.needs_login()) {
            K::CredentialRejected
        } else if live
            .iter()
            .all(|a| a.kind.needs_login() || a.kind.needs_action())
        {
            K::ActionRequired
        } else {
            K::QuotaUnknown
        };
        let earliest_reset_ms = accounts
            .iter()
            .filter(|a| a.is_limited() && !a.kind.needs_login() && !a.kind.needs_action())
            .filter_map(|a| a.until_ms)
            .filter(|t| *t > now_ms)
            .min();
        Self {
            kind,
            accounts,
            earliest_reset_ms,
            usage_read_retry_ms: None,
        }
    }

    /// The shortest `Retry-After` among the live transient failures, when
    /// every one of them carries one: sending again sooner only repeats
    /// them. `None` when there is no live transient failure or one has no
    /// `Retry-After`.
    pub fn transient_retry_after_s(&self) -> Option<u64> {
        let waits: Option<Vec<u64>> = self
            .accounts
            .iter()
            .filter(|a| a.is_live() && a.kind.is_transient())
            .map(|a| a.retry_after_s)
            .collect();
        waits?.into_iter().min()
    }

    /// Labels whose failure only a new login fixes, in order.
    pub fn login_labels(&self) -> Vec<&str> {
        self.accounts
            .iter()
            .filter(|a| a.kind.needs_login())
            .map(|a| a.account.as_str())
            .collect()
    }

    /// Labels whose failure needs an action outside synaps, in order.
    pub fn action_labels(&self) -> Vec<&str> {
        self.accounts
            .iter()
            .filter(|a| a.kind.needs_action())
            .map(|a| a.account.as_str())
            .collect()
    }

    /// `label:kind[:status][:cooling],…` — one log field, secret-free.
    pub fn accounts_field(&self) -> String {
        self.accounts
            .iter()
            .map(AccountFailure::log_form)
            .collect::<Vec<_>>()
            .join(",")
    }
}

/// Result of [`select`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum Selection {
    Selected {
        #[serde(with = "cred_serde")]
        credential: CredentialRef,
        /// Maximum utilization across the applicable windows, if known.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        utilization: Option<f64>,
        /// The winner's [`Eligible::tier`] (`1..=4`; `0` only when decoded
        /// from a record written before tiers existed). Computed under every
        /// strategy so the pick can always be explained.
        #[serde(default)]
        tier: u8,
        /// The winner's [`Eligible::budget_reset_ms`], if it has one.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        budget_reset_ms: Option<u64>,
        /// Candidates that lost — informational.
        rejections: Vec<Rejection>,
    },
    NoCapacity {
        rejections: Vec<Rejection>,
        /// Earliest *future* provider-reported reset among exhausted
        /// candidates, if any. Past resets are never reported here: a passed
        /// reset is not evidence of a new window.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        earliest_reset_ms: Option<u64>,
    },
}

impl Selection {
    pub fn selected(&self) -> Option<&CredentialRef> {
        match self {
            Self::Selected { credential, .. } => Some(credential),
            Self::NoCapacity { .. } => None,
        }
    }
}

// ── Eligibility ──────────────────────────────────────────────────────────────

/// Eligible-account summary produced by [`evaluate`].
#[derive(Debug, Clone, PartialEq)]
pub struct Eligible {
    /// Max utilization over applicable windows (`None` = proven-not-limited only).
    pub utilization: Option<f64>,
    /// Reset instant of the budget window (see [`budget_window`]), if the
    /// provider reports one that lies in the future. A reset at or before
    /// `now_ms` is not evidence of a new window and is reported as `None`.
    pub budget_reset_ms: Option<u64>,
    /// Whether the budget window's reset is a fixed instant (`Some(true)`)
    /// or slides with the observation because the window has not been
    /// started by a first use yet (`Some(false)`, see [`is_unanchored`]).
    /// `None` when there is no budget reset to classify.
    pub anchored: Option<bool>,
    /// Priority tier under [`Strategy::SoonestReset`], computed for every
    /// eligible seat regardless of strategy so any ranking can be explained:
    /// 1 = anchored and resetting within the urgent horizon (capacity about
    /// to be lost), 2 = unanchored (using it starts the clock), 3 = anchored
    /// beyond the horizon (earliest deadline first), 4 = no reset evidence
    /// (headroom proven, deadline unknown). Unknown anchoring with a known
    /// reset is treated as anchored.
    pub tier: u8,
    /// Eligible on a last good reading because its current usage read
    /// failed transiently (see [`SelectionRequest::grace`]).
    pub graced: bool,
}

/// Tier for an eligible seat; see [`Eligible::tier`].
fn tier_for(
    anchored: Option<bool>,
    budget_reset_ms: Option<u64>,
    now_ms: u64,
    urgent_horizon_ms: u64,
) -> u8 {
    match (anchored, budget_reset_ms) {
        (_, None) => 4,
        (Some(false), Some(_)) => 2,
        (_, Some(reset)) if reset.saturating_sub(now_ms) <= urgent_horizon_ms => 1,
        (_, Some(_)) => 3,
    }
}

/// Evaluate a single account against the request. Pure; ignores
/// `explicit_account` and provider matching (the caller filters those).
pub fn evaluate(
    req: &SelectionRequest<'_>,
    cap: &AccountCapacity,
) -> Result<Eligible, RejectReason> {
    if req
        .exclude
        .iter()
        .any(|c| c.storage_key() == cap.credential.storage_key())
    {
        return Err(RejectReason::Excluded);
    }
    if let Some(until) = cap.cooldown_until_ms {
        if until > req.now_ms {
            return Err(RejectReason::CoolingDown { until_ms: until });
        }
    }
    let (windows, models) = match &cap.observation {
        QuotaObservation::Ok { windows, models } => (windows, models),
        QuotaObservation::AuthError => return Err(RejectReason::AuthError),
        QuotaObservation::Unsupported => return Err(RejectReason::Unsupported),
        QuotaObservation::Malformed => return Err(RejectReason::Malformed),
        QuotaObservation::Unknown => return evaluate_graced(req, cap),
    };
    let observed = cap
        .observed_at_ms
        .ok_or(RejectReason::Stale { age_ms: None })?;
    if observed > req.now_ms.saturating_add(MAX_FUTURE_OBSERVATION_SKEW_MS) {
        return Err(RejectReason::Malformed);
    }
    let age = req.now_ms.saturating_sub(observed);
    if age > req.max_snapshot_age_ms {
        return Err(RejectReason::Stale { age_ms: Some(age) });
    }
    if let (Some(model), Some(list)) = (req.model, models) {
        for m in list.iter().filter(|m| model_matches(&m.model, model)) {
            match m.state {
                ModelState::Available => {}
                ModelState::Exhausted => {
                    return Err(RejectReason::ModelUnavailable {
                        model: model.to_string(),
                    })
                }
                ModelState::Unknown => {
                    return Err(RejectReason::ModelUnknown {
                        model: model.to_string(),
                    })
                }
            }
        }
    }
    let mut applicable = 0usize;
    let mut utilization: Option<f64> = None;
    for w in windows.iter().filter(|w| w.applies_to(req.model)) {
        applicable += 1;
        match w.verdict(req.exhausted_at_percent) {
            WindowVerdict::Headroom { used_percent } => {
                if let Some(p) = used_percent {
                    utilization = Some(utilization.map_or(p, |u| u.max(p)));
                }
            }
            WindowVerdict::Exhausted { resets_at_ms } => {
                return Err(RejectReason::Exhausted {
                    window: w.id.clone(),
                    resets_at_ms,
                });
            }
            WindowVerdict::Unknown => {
                return Err(RejectReason::WindowUnknown {
                    window: w.id.clone(),
                });
            }
        }
    }
    if applicable == 0 {
        return Err(RejectReason::NoLimitEvidence);
    }
    // Perishable-capacity evidence. Only a future reset counts: a reset at or
    // before `now_ms` on a still-fresh reading is not evidence of a new
    // window (the same rule `NoCapacity::earliest_reset_ms` applies).
    let budget = budget_window(windows, req.model);
    let budget_reset_ms = budget
        .and_then(|w| w.resets_at_ms)
        .filter(|t| *t > req.now_ms);
    let anchored = match (budget, budget_reset_ms) {
        (Some(w), Some(_)) => is_unanchored(w, observed).map(|u| !u),
        _ => None,
    };
    let tier = tier_for(anchored, budget_reset_ms, req.now_ms, req.urgent_horizon_ms);
    Ok(Eligible {
        utilization,
        budget_reset_ms,
        anchored,
        tier,
        graced: false,
    })
}

/// An account whose current read gave no reading: eligible only on its
/// last good reading in [`SelectionRequest::grace`], judged by the same
/// rules (windows, models) against the grace age, with the account's own
/// cooldown (already checked by the caller, kept for the re-check). Any
/// rejection of that reading reports the read failure, not the old reading.
fn evaluate_graced(
    req: &SelectionRequest<'_>,
    cap: &AccountCapacity,
) -> Result<Eligible, RejectReason> {
    let key = cap.credential.storage_key();
    let Some(good) = req
        .grace
        .iter()
        .find(|g| g.credential.storage_key() == key)
        .filter(|g| matches!(g.observation, QuotaObservation::Ok { .. }))
    else {
        return Err(RejectReason::Unknown);
    };
    // Strictly younger than the grace age (a reading exactly that old no
    // longer counts); `evaluate` below re-checks with its inclusive bound.
    let young = good
        .observed_at_ms
        .is_some_and(|t| req.now_ms.saturating_sub(t) < req.grace_max_age_ms);
    if !young {
        return Err(RejectReason::Unknown);
    }
    let graced_req = SelectionRequest {
        max_snapshot_age_ms: req.grace_max_age_ms,
        grace: &[],
        ..req.clone()
    };
    let reading = AccountCapacity {
        cooldown_until_ms: cap.cooldown_until_ms,
        ..good.clone()
    };
    evaluate(&graced_req, &reading)
        .map(|e| Eligible { graced: true, ..e })
        .map_err(|_| RejectReason::Unknown)
}

/// Lowest-utilization ordering: known before unknown, then ascending.
fn utilization_cmp(a: Option<f64>, b: Option<f64>) -> std::cmp::Ordering {
    a.is_none().cmp(&b.is_none()).then_with(|| {
        a.unwrap_or(0.0)
            .partial_cmp(&b.unwrap_or(0.0))
            .unwrap_or(std::cmp::Ordering::Equal)
    })
}

fn preference_rank(req: &SelectionRequest<'_>, cred: &CredentialRef) -> usize {
    let label = cred.account.label_str();
    req.preference
        .iter()
        .position(|p| p == label)
        .unwrap_or(usize::MAX)
}

/// The recorded observation failure behind a verdict: an observation
/// verdict, or a cooldown (checked first, so it would otherwise hide what
/// the account's last read or refresh said). The other policy verdicts
/// (exhausted, …) come from a good reading and need no cause.
fn observation_cause(reason: &RejectReason, cap: &AccountCapacity) -> Option<ObservationFailure> {
    match reason {
        RejectReason::Unknown
        | RejectReason::AuthError
        | RejectReason::Malformed
        | RejectReason::Unsupported
        | RejectReason::CoolingDown { .. } => cap.failure.clone(),
        _ => None,
    }
}

/// Diagnostics only (never eligibility): when `cap` can be used again as
/// far as its cooldown and its reading know: the latest of its future
/// cooldown end and the resets of every applicable exhausted window, since
/// all of them must be over. `None` when it has neither, or an exhausted
/// window has no future reset (the time is unknown).
fn usable_after_ms(req: &SelectionRequest<'_>, cap: &AccountCapacity) -> Option<u64> {
    let mut latest = cap.cooldown_until_ms.filter(|t| *t > req.now_ms);
    if let QuotaObservation::Ok { windows, .. } = &cap.observation {
        for w in windows.iter().filter(|w| w.applies_to(req.model)) {
            if let WindowVerdict::Exhausted { resets_at_ms } = w.verdict(req.exhausted_at_percent) {
                let reset = resets_at_ms.filter(|t| *t > req.now_ms)?;
                latest = Some(latest.map_or(reset, |l| l.max(reset)));
            }
        }
    }
    latest
}

/// Pick the best eligible account for `req` among `candidates`.
///
/// Candidates for other providers are ignored. See module docs for the rules.
pub fn select(req: &SelectionRequest<'_>, candidates: &[AccountCapacity]) -> Selection {
    let mut rejections: Vec<Rejection> = Vec::new();
    let mut eligible: Vec<(&AccountCapacity, Eligible)> = Vec::new();
    let mut explicit_seen = false;

    for cap in candidates
        .iter()
        .filter(|c| c.credential.provider == req.provider)
    {
        if let Some(label) = req.explicit_account {
            if cap.credential.account.label_str() != label {
                continue;
            }
            explicit_seen = true;
        }
        match evaluate(req, cap) {
            Ok(e) => eligible.push((cap, e)),
            Err(reason) => rejections.push(Rejection {
                credential: cap.credential.clone(),
                cause: observation_cause(&reason, cap),
                usable_after_ms: usable_after_ms(req, cap),
                reason,
            }),
        }
    }

    if let (Some(label), false) = (req.explicit_account, explicit_seen) {
        // An unparseable label cannot be represented as a credential; report
        // it distinctly (against the provider's default slot) so callers never
        // mistake it for a missing valid account.
        let (credential, reason) = match super::account::Account::parse(label) {
            Ok(account) => (
                CredentialRef::new(req.provider, account),
                RejectReason::NotPresent,
            ),
            Err(_) => (
                CredentialRef::default_for(req.provider),
                RejectReason::InvalidLabel {
                    label: label.to_string(),
                },
            ),
        };
        return Selection::NoCapacity {
            rejections: vec![Rejection {
                credential,
                reason,
                cause: None,
                usable_after_ms: None,
            }],
            earliest_reset_ms: None,
        };
    }

    // Deterministic ordering. Fresh readings first: a graced seat (last good
    // reading, current read failed) never outranks a fresh one when choosing
    // anew; stickiness below may still keep a graced current seat.
    eligible.sort_by(|(a, ea), (b, eb)| {
        let ka = a.credential.storage_key();
        let kb = b.credential.storage_key();
        let pa = preference_rank(req, &a.credential);
        let pb = preference_rank(req, &b.credential);
        ea.graced.cmp(&eb.graced).then_with(|| match req.strategy {
            Strategy::PreferenceOrder => pa.cmp(&pb).then_with(|| ka.cmp(&kb)),
            Strategy::LowestUtilization => utilization_cmp(ea.utilization, eb.utilization)
                .then_with(|| pa.cmp(&pb))
                .then_with(|| ka.cmp(&kb)),
            Strategy::SoonestReset => ea
                .tier
                .cmp(&eb.tier)
                .then_with(|| match ea.tier {
                    // Soonest deadline first; both resets are `Some` here.
                    1 | 3 => ea.budget_reset_ms.cmp(&eb.budget_reset_ms),
                    // Unanchored seats have no deadline yet: operator order.
                    2 => pa.cmp(&pb).then_with(|| ka.cmp(&kb)),
                    // No reset evidence: fall back to headroom.
                    _ => utilization_cmp(ea.utilization, eb.utilization),
                })
                .then_with(|| utilization_cmp(ea.utilization, eb.utilization))
                .then_with(|| pa.cmp(&pb))
                .then_with(|| ka.cmp(&kb)),
        })
    });

    // Stickiness (SoonestReset only): keep the pinned seat unless a candidate
    // is in a strictly higher tier, or both are urgent and the candidate's
    // reset is strictly sooner. An ineligible/excluded current seat is not in
    // `eligible`, so it can never be kept. A graced current seat is judged on
    // its graced reading exactly as a fresh one: ranking graced after fresh
    // never moves off it by itself, so a read failure alone never switches.
    if req.sticky && req.strategy == Strategy::SoonestReset {
        if let Some(current) = req.current {
            let key = current.storage_key();
            let at = eligible
                .iter()
                .position(|(c, _)| c.credential.storage_key() == key);
            if let Some(i) = at.filter(|i| *i > 0) {
                let best = &eligible[0].1;
                let cur = &eligible[i].1;
                let switch = best.tier < cur.tier
                    || (best.tier == 1
                        && cur.tier == 1
                        && best.budget_reset_ms < cur.budget_reset_ms);
                if !switch {
                    eligible[..=i].rotate_right(1);
                }
            }
        }
    }

    match eligible.first() {
        Some((cap, e)) => {
            let winner = cap.credential.clone();
            for (i, (other, _)) in eligible.iter().enumerate().skip(1) {
                rejections.push(Rejection {
                    credential: other.credential.clone(),
                    reason: RejectReason::Outranked {
                        rank: (i + 1) as u32,
                    },
                    cause: None,
                    usable_after_ms: None,
                });
            }
            Selection::Selected {
                credential: winner,
                utilization: e.utilization,
                tier: e.tier,
                budget_reset_ms: e.budget_reset_ms,
                rejections,
            }
        }
        None => {
            let earliest_reset_ms = rejections
                .iter()
                .filter_map(|r| match &r.reason {
                    RejectReason::Exhausted {
                        resets_at_ms: Some(t),
                        ..
                    } if *t > req.now_ms => Some(*t),
                    _ => None,
                })
                .min();
            Selection::NoCapacity {
                rejections,
                earliest_reset_ms,
            }
        }
    }
}

// ── Bounded failover ─────────────────────────────────────────────────────────

/// Classification of the failure that triggered a failover request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FailureKind {
    /// Provider explicitly reported the account's quota as exhausted before
    /// any output was produced (e.g. Codex `usage_limit_reached`).
    QuotaExhaustedPreOutput,
    /// Ordinary rate limiting (429 / overloaded). Not proof of exhaustion.
    RateLimited,
    /// Anything else (network, 5xx, parse, cancel).
    Other,
}

/// Evidence about the failed attempt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailureEvidence {
    pub kind: FailureKind,
    /// Any model output (text/thinking/tool_use) reached the caller.
    pub output_started: bool,
    /// Any tool executed, or tool results were fed back, for this turn.
    pub tool_activity: bool,
    /// Failovers already performed for this request.
    pub failovers_so_far: u32,
}

/// Maximum number of account switches for one request.
pub const MAX_FAILOVERS: u32 = 1;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "decision", rename_all = "snake_case")]
pub enum FailoverDecision {
    Failover {
        #[serde(with = "cred_serde")]
        credential: CredentialRef,
    },
    NoFailover {
        reason: String,
    },
}

/// Decide whether the request may be retried on another seat.
///
/// Never replays after output or tool activity, never on an ordinary 429,
/// never for an explicitly requested account, and at most [`MAX_FAILOVERS`]
/// times. The failed seat is excluded from the fresh selection.
pub fn failover(
    req: &SelectionRequest<'_>,
    failed: &CredentialRef,
    evidence: &FailureEvidence,
    candidates: &[AccountCapacity],
) -> FailoverDecision {
    let no = |reason: &str| FailoverDecision::NoFailover {
        reason: reason.to_string(),
    };
    if evidence.output_started {
        return no("output already started; never replay on another account");
    }
    if evidence.tool_activity {
        return no("tool activity occurred; never replay on another account");
    }
    if evidence.failovers_so_far >= MAX_FAILOVERS {
        return no("failover budget exhausted");
    }
    if evidence.kind != FailureKind::QuotaExhaustedPreOutput {
        return no("not a recognized pre-output quota failure");
    }
    if req.explicit_account.is_some() {
        return no("explicit account requested; no silent fallback");
    }
    let mut exclude: Vec<CredentialRef> = req.exclude.to_vec();
    exclude.push(failed.clone());
    let retry = SelectionRequest {
        exclude: &exclude,
        ..req.clone()
    };
    match select(&retry, candidates) {
        Selection::Selected { credential, .. } => FailoverDecision::Failover { credential },
        Selection::NoCapacity { .. } => no("no other eligible account"),
    }
}

// ── Helpers shared with the keeper ───────────────────────────────────────────

/// Weekly pick over an arbitrary set of windows: account-wide first, then `id`.
fn pick_weekly<'w>(windows: impl Iterator<Item = &'w WindowLimit>) -> Option<&'w WindowLimit> {
    let mut weekly: Vec<&WindowLimit> = windows.filter(|w| w.is_weekly()).collect();
    weekly.sort_by(|a, b| {
        a.models
            .is_some()
            .cmp(&b.models.is_some())
            .then_with(|| a.id.cmp(&b.id))
    });
    weekly.into_iter().next()
}

/// The account-wide weekly window of a reading, if the provider reports one.
///
/// Prefers account-wide (`models == None`) weekly windows; falls back to a
/// model-scoped weekly window only when no account-wide one exists. Order is
/// deterministic (first by scope, then by `id`).
pub fn weekly_window(windows: &[WindowLimit]) -> Option<&WindowLimit> {
    pick_weekly(windows.iter())
}

/// The *budget window* of a reading for `model`: the window whose reset
/// decides when unused capacity is lost.
///
/// Among the windows that [`apply to`](WindowLimit::applies_to) `model`,
/// prefers the weekly window with the same preference as [`weekly_window`]
/// (account-wide before model-scoped, then `id`); otherwise the window with
/// the longest reported `duration_ms` (ties: account-wide first, then `id`).
/// `None` when no applicable window reports a duration — a window of unknown
/// length cannot be a deadline.
pub fn budget_window<'w>(
    windows: &'w [WindowLimit],
    model: Option<&str>,
) -> Option<&'w WindowLimit> {
    let applicable = || windows.iter().filter(|w| w.applies_to(model));
    if let Some(weekly) = pick_weekly(applicable()) {
        return Some(weekly);
    }
    applicable()
        .filter(|w| w.duration_ms.is_some())
        .min_by(|a, b| {
            b.duration_ms
                .cmp(&a.duration_ms)
                .then_with(|| a.models.is_some().cmp(&b.models.is_some()))
                .then_with(|| a.id.cmp(&b.id))
        })
}

/// Whether `window`'s reset slides with the observation instead of being a
/// fixed instant — the signature of a seat whose window has not been started
/// by a first use (Codex anchors a window at first use after a reset; an
/// idle seat therefore keeps reporting `reset ≈ observed_at + duration`).
///
/// * `Some(true)`: `used_percent` is reported and at most
///   [`UNANCHORED_MAX_USED_PERCENT`], **and** both `duration_ms` and
///   `resets_at_ms` are present, **and**
///   `|resets_at_ms − (observed_at_ms + duration_ms)| ≤ UNANCHORED_TOLERANCE_MS`.
/// * `Some(false)`: duration and reset are present but the window has been
///   used, its utilization is unreported, or its reset does not track the
///   observation (e.g. an Anthropic 7-day window at 0 % still reports the
///   provider's fixed calendar reset).
/// * `None`: duration or reset missing — anchoring cannot be judged.
pub fn is_unanchored(window: &WindowLimit, observed_at_ms: u64) -> Option<bool> {
    let (Some(duration), Some(reset)) = (window.duration_ms, window.resets_at_ms) else {
        return None;
    };
    let near_zero = matches!(
        window.used_percent,
        Some(p) if (0.0..=UNANCHORED_MAX_USED_PERCENT).contains(&p)
    );
    if !near_zero {
        return Some(false);
    }
    let expected = observed_at_ms.saturating_add(duration);
    Some(expected.abs_diff(reset) <= UNANCHORED_TOLERANCE_MS)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::account::Account;

    const HOUR: u64 = 3_600_000;
    const DAY: u64 = 24 * HOUR;
    const NOW: u64 = 1_800_000_000_000;

    fn cred(label: &str) -> CredentialRef {
        CredentialRef::new(OAuthProviderId::OpenAiCodex, Account::parse(label).unwrap())
    }

    fn win(id: &str, dur: u64, used: f64, resets: u64) -> WindowLimit {
        WindowLimit {
            id: id.into(),
            duration_ms: Some(dur),
            used_percent: Some(used),
            limit_reached: Some(used >= 100.0),
            resets_at_ms: Some(resets),
            models: None,
        }
    }

    fn ok(label: &str, windows: Vec<WindowLimit>) -> AccountCapacity {
        AccountCapacity {
            credential: cred(label),
            observed_at_ms: Some(NOW - 1000),
            observation: QuotaObservation::Ok {
                windows,
                models: None,
            },
            cooldown_until_ms: None,
            failure: None,
        }
    }

    fn req() -> SelectionRequest<'static> {
        SelectionRequest::new(OAuthProviderId::OpenAiCodex, NOW, 30 * 60 * 1000)
    }

    #[test]
    fn window_verdicts_fail_closed() {
        let mut w = win("primary", 7 * DAY, 20.0, NOW + DAY);
        assert_eq!(
            w.verdict(100.0),
            WindowVerdict::Headroom {
                used_percent: Some(20.0)
            }
        );
        w.used_percent = Some(100.0);
        w.limit_reached = Some(false);
        assert!(matches!(w.verdict(100.0), WindowVerdict::Exhausted { .. }));
        w.used_percent = Some(50.0);
        w.limit_reached = Some(true);
        assert!(matches!(w.verdict(100.0), WindowVerdict::Exhausted { .. }));
        w.used_percent = None;
        w.limit_reached = None;
        assert_eq!(w.verdict(100.0), WindowVerdict::Unknown);
        w.limit_reached = Some(false);
        assert_eq!(
            w.verdict(100.0),
            WindowVerdict::Headroom { used_percent: None }
        );
        w.used_percent = Some(f64::NAN);
        assert_eq!(w.verdict(100.0), WindowVerdict::Unknown);
        // An overrun window is exhausted, not unknown.
        w.used_percent = Some(140.0);
        assert!(matches!(w.verdict(100.0), WindowVerdict::Exhausted { .. }));
        w.used_percent = Some(1000.5);
        assert_eq!(w.verdict(100.0), WindowVerdict::Unknown);
        // A provider `limit_reached: true` wins over any malformed percent.
        let saved = w.limit_reached;
        w.limit_reached = Some(true);
        for p in [1500.0, f64::NAN, -3.0] {
            w.used_percent = Some(p);
            assert!(
                matches!(w.verdict(100.0), WindowVerdict::Exhausted { .. }),
                "{p}"
            );
        }
        w.limit_reached = saved;
        w.used_percent = Some(-1.0);
        assert_eq!(w.verdict(100.0), WindowVerdict::Unknown);
        // invalid thresholds fail closed
        w.used_percent = Some(1.0);
        assert_eq!(w.verdict(f64::NAN), WindowVerdict::Unknown);
        assert_eq!(w.verdict(101.0), WindowVerdict::Unknown);
        assert_eq!(w.verdict(-0.5), WindowVerdict::Unknown);
        assert_eq!(w.verdict(f64::INFINITY), WindowVerdict::Unknown);
        let r = SelectionRequest {
            exhausted_at_percent: f64::NAN,
            ..SelectionRequest::new(OAuthProviderId::OpenAiCodex, NOW, HOUR)
        };
        assert!(select(
            &r,
            &[ok("a", vec![win("primary", 7 * DAY, 1.0, NOW + DAY)])]
        )
        .selected()
        .is_none());
    }

    #[test]
    fn weekly_is_from_duration_not_name() {
        let primary_5h = win("primary", 5 * HOUR, 0.0, NOW + HOUR);
        let primary_week = win("primary", 7 * DAY, 0.0, NOW + DAY);
        let no_dur = WindowLimit {
            duration_ms: None,
            ..win("seven_day", 0, 0.0, NOW)
        };
        assert!(!primary_5h.is_weekly());
        assert!(primary_week.is_weekly());
        assert!(!no_dur.is_weekly());
        assert_eq!(
            weekly_window(&[primary_5h.clone(), primary_week.clone()]).map(|w| w.duration_ms),
            Some(Some(7 * DAY))
        );
        assert!(weekly_window(&[primary_5h, no_dur]).is_none());
        // account-wide weekly preferred over model-scoped weekly
        let scoped = WindowLimit {
            id: "aaa_scoped".into(),
            models: Some(vec!["m".into()]),
            ..primary_week.clone()
        };
        assert_eq!(
            weekly_window(&[scoped, primary_week]).map(|w| w.id.as_str()),
            Some("primary")
        );
    }

    #[test]
    fn selects_lowest_utilization_deterministically() {
        let a = ok("a", vec![win("primary", 7 * DAY, 60.0, NOW + DAY)]);
        let b = ok("b", vec![win("primary", 7 * DAY, 10.0, NOW + DAY)]);
        let c = ok("c", vec![win("primary", 7 * DAY, 10.0, NOW + DAY)]);
        let sel = select(&req(), &[a.clone(), c.clone(), b.clone()]);
        assert_eq!(sel.selected().unwrap().storage_key(), "openai-codex@b");
        // identical inputs in another order → same answer
        let sel2 = select(&req(), &[c, b, a]);
        assert_eq!(sel2.selected().unwrap().storage_key(), "openai-codex@b");
    }

    #[test]
    fn preference_breaks_ties_and_orders() {
        let b = ok("b", vec![win("primary", 7 * DAY, 10.0, NOW + DAY)]);
        let c = ok("c", vec![win("primary", 7 * DAY, 10.0, NOW + DAY)]);
        let pref = vec!["c".to_string(), "b".to_string()];
        let r = SelectionRequest {
            preference: &pref,
            ..req()
        };
        assert_eq!(
            select(&r, &[b.clone(), c.clone()])
                .selected()
                .unwrap()
                .storage_key(),
            "openai-codex@c"
        );
        let a = ok("a", vec![win("primary", 7 * DAY, 90.0, NOW + DAY)]);
        let pref2 = vec!["a".to_string()];
        let r2 = SelectionRequest {
            preference: &pref2,
            strategy: Strategy::PreferenceOrder,
            ..req()
        };
        assert_eq!(
            select(&r2, &[b, c, a]).selected().unwrap().storage_key(),
            "openai-codex@a"
        );
    }

    /// Grace: a failed read (`Unknown`) counts on its last good reading only
    /// under the grace age and never past an exhausted window or a cooldown;
    /// graced seats rank after fresh ones, but a graced sticky seat stays.
    #[test]
    fn graced_readings_are_bounded_rank_after_fresh_and_keep_a_sticky_seat() {
        let grace_ms = super::super::usage_reads::USAGE_READ_GRACE.as_millis() as u64;
        let failed = |label: &str| AccountCapacity::unobserved(cred(label));
        let good = |label: &str, age: u64, used: f64, reset: u64| AccountCapacity {
            observed_at_ms: Some(NOW - age),
            ..ok(label, vec![win("primary", 7 * DAY, used, reset)])
        };
        let fresh_req = || SelectionRequest::soonest_reset(OAuthProviderId::OpenAiCodex, NOW, 60_000);
        let winner = |sel: Selection| match sel {
            Selection::Selected { credential, .. } => credential.account.label_str().to_string(),
            Selection::NoCapacity { rejections, .. } => panic!("no capacity: {rejections:?}"),
        };
        let one = |grace: &[AccountCapacity], cap: &AccountCapacity| {
            evaluate(&SelectionRequest { grace, ..fresh_req() }, cap)
        };

        let young = [good("a", grace_ms - 60_000, 20.0, NOW + DAY)];
        assert!(one(&young, &failed("a")).unwrap().graced);
        let old = [good("a", grace_ms + 60_000, 20.0, NOW + DAY)];
        assert_eq!(one(&old, &failed("a")), Err(RejectReason::Unknown), "past the grace age");
        // Strictly under the grace age: a reading exactly that old is out.
        let edge = [good("a", grace_ms, 20.0, NOW + DAY)];
        assert_eq!(one(&edge, &failed("a")), Err(RejectReason::Unknown), "at the grace age");
        let inside = [good("a", grace_ms - 1, 20.0, NOW + DAY)];
        assert!(one(&inside, &failed("a")).unwrap().graced, "just under it");
        let exhausted = [good("a", 60_000, 100.0, NOW + HOUR)];
        assert_eq!(one(&exhausted, &failed("a")), Err(RejectReason::Unknown), "exhausted window");
        let cooling = AccountCapacity {
            cooldown_until_ms: Some(NOW + HOUR),
            ..failed("a")
        };
        assert!(matches!(one(&young, &cooling), Err(RejectReason::CoolingDown { .. })));
        let auth = AccountCapacity {
            observation: QuotaObservation::AuthError,
            ..failed("a")
        };
        assert_eq!(one(&young, &auth), Err(RejectReason::AuthError), "only a failed read is graced");

        // a: graced, urgent; b: fresh, far. Choosing anew: fresh b first.
        let grace = [good("a", 60_000, 20.0, NOW + HOUR)];
        let b = good("b", 1000, 20.0, NOW + 3 * DAY);
        let anew = SelectionRequest { grace: &grace, ..fresh_req() };
        assert_eq!(winner(select(&anew, &[failed("a"), b.clone()])), "b");
        assert_eq!(winner(select(&anew, &[failed("a")])), "a", "alone, the graced seat serves");
        // Sticky on graced a: stays (a read failure alone is no reason to switch).
        let current = cred("a");
        let sticky = SelectionRequest {
            current: Some(&current),
            ..anew.clone()
        };
        assert_eq!(winner(select(&sticky, &[failed("a"), b])), "a");

        // A graced sticky seat is judged exactly as a fresh one would be: it
        // stays wherever a fresh reading would stay and yields only where a
        // fresh reading yields too (a strictly higher tier, or a strictly
        // sooner urgent reset), never because its read failed.
        let mut switched = 0;
        for a_reset in [NOW + HOUR, NOW + 2 * DAY, NOW + 10 * HOUR] {
            for b_reset in [NOW + HOUR / 2, NOW + 3 * DAY, NOW + 12 * HOUR, NOW + 5 * DAY] {
                let a_good = good("a", 1000, 20.0, a_reset);
                let b = good("b", 1000, 20.0, b_reset);
                let graced = [a_good.clone()];
                let on_grace = SelectionRequest {
                    grace: &graced,
                    current: Some(&current),
                    ..fresh_req()
                };
                let on_fresh = SelectionRequest {
                    current: Some(&current),
                    ..fresh_req()
                };
                let g = winner(select(&on_grace, &[failed("a"), b.clone()]));
                let f = winner(select(&on_fresh, &[a_good, b]));
                assert_eq!(g, f, "a resets at {a_reset}, b at {b_reset}");
                switched += usize::from(g == "b");
            }
        }
        assert!(switched > 0 && switched < 12, "the cases cover staying and switching: {switched}");
    }

    #[test]
    fn stale_unknown_malformed_auth_are_not_capacity() {
        let mut stale = ok("s", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        stale.observed_at_ms = Some(NOW - 2 * HOUR);
        let mut never = ok("n", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        never.observed_at_ms = None;
        let mut future = ok("f", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        future.observed_at_ms = Some(NOW + HOUR);
        let mut auth = ok("x", vec![]);
        auth.observation = QuotaObservation::AuthError;
        let mut unk = ok("u", vec![]);
        unk.observation = QuotaObservation::Unknown;
        let mut mal = ok("m", vec![]);
        mal.observation = QuotaObservation::Malformed;
        let mut uns = ok("v", vec![]);
        uns.observation = QuotaObservation::Unsupported;
        let none = ok("e", vec![]);
        let sel = select(&req(), &[stale, never, future, auth, unk, mal, uns, none]);
        let Selection::NoCapacity {
            rejections,
            earliest_reset_ms,
        } = sel
        else {
            panic!("expected no capacity");
        };
        assert_eq!(earliest_reset_ms, None);
        let reasons: Vec<(String, RejectReason)> = rejections
            .into_iter()
            .map(|r| (r.credential.account.label_str().to_string(), r.reason))
            .collect();
        assert!(reasons.contains(&(
            "s".into(),
            RejectReason::Stale {
                age_ms: Some(2 * HOUR)
            }
        )));
        assert!(reasons.contains(&("n".into(), RejectReason::Stale { age_ms: None })));
        assert!(reasons.contains(&("f".into(), RejectReason::Malformed)));
        assert!(reasons.contains(&("x".into(), RejectReason::AuthError)));
        assert!(reasons.contains(&("u".into(), RejectReason::Unknown)));
        assert!(reasons.contains(&("m".into(), RejectReason::Malformed)));
        assert!(reasons.contains(&("v".into(), RejectReason::Unsupported)));
        assert!(reasons.contains(&("e".into(), RejectReason::NoLimitEvidence)));
    }

    #[test]
    fn exhausted_cooldown_and_unknown_window_excluded() {
        let exhausted = ok("x", vec![win("primary", 7 * DAY, 100.0, NOW + 2 * DAY)]);
        let mut cooling = ok("c", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        cooling.cooldown_until_ms = Some(NOW + HOUR);
        let mut cooled = ok("d", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        cooled.cooldown_until_ms = Some(NOW - 1);
        let unknown_window = ok(
            "w",
            vec![WindowLimit {
                used_percent: None,
                limit_reached: None,
                ..win("primary", 7 * DAY, 0.0, NOW + DAY)
            }],
        );
        let past_exhausted = ok("p", vec![win("primary", 7 * DAY, 100.0, NOW - DAY)]);
        let sel = select(
            &req(),
            &[exhausted, cooling, unknown_window, past_exhausted],
        );
        let Selection::NoCapacity {
            earliest_reset_ms, ..
        } = &sel
        else {
            panic!("no capacity expected");
        };
        // past reset never reported as the earliest reset
        assert_eq!(*earliest_reset_ms, Some(NOW + 2 * DAY));
        let sel = select(&req(), &[cooled]);
        assert_eq!(sel.selected().unwrap().storage_key(), "openai-codex@d");
    }

    #[test]
    fn all_applicable_limits_including_model_scoped_count() {
        let model_win = WindowLimit {
            id: "weekly_sonnet".into(),
            models: Some(vec!["sonnet".into()]),
            ..win("weekly_sonnet", 7 * DAY, 100.0, NOW + DAY)
        };
        let five_h = win("five_hour", 5 * HOUR, 99.0, NOW + HOUR);
        let acct = ok(
            "a",
            vec![
                win("seven_day", 7 * DAY, 10.0, NOW + DAY),
                five_h,
                model_win,
            ],
        );
        // sonnet request hits the exhausted model window
        let r = SelectionRequest {
            model: Some("sonnet"),
            ..req()
        };
        assert!(select(&r, std::slice::from_ref(&acct)).selected().is_none());
        // opus request ignores the sonnet window and takes max utilization (99)
        let r = SelectionRequest {
            model: Some("opus"),
            ..req()
        };
        match select(&r, std::slice::from_ref(&acct)) {
            Selection::Selected { utilization, .. } => assert_eq!(utilization, Some(99.0)),
            other => panic!("unexpected {other:?}"),
        }
        // no model given: scoped windows still apply (never bypass a limit)
        assert!(select(&req(), std::slice::from_ref(&acct))
            .selected()
            .is_none());
        // model listed as unavailable
        let mut unavailable = acct;
        if let QuotaObservation::Ok { models, .. } = &mut unavailable.observation {
            *models = Some(vec![ModelAvailability {
                model: "opus".into(),
                state: ModelState::Exhausted,
            }]);
        }
        let r = SelectionRequest {
            model: Some("opus"),
            ..req()
        };
        let sel = select(&r, &[unavailable.clone()]);
        match sel {
            Selection::NoCapacity { rejections, .. } => assert_eq!(
                rejections[0].reason,
                RejectReason::ModelUnavailable {
                    model: "opus".into()
                }
            ),
            other => panic!("unexpected {other:?}"),
        }
        // unknown availability is preserved as unknown → not capacity
        let mut unknown = unavailable;
        if let QuotaObservation::Ok { models, .. } = &mut unknown.observation {
            *models = Some(vec![ModelAvailability {
                model: "opus".into(),
                state: ModelState::Unknown,
            }]);
        }
        match select(&r, &[unknown]) {
            Selection::NoCapacity { rejections, .. } => assert_eq!(
                rejections[0].reason,
                RejectReason::ModelUnknown {
                    model: "opus".into()
                }
            ),
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn explicit_account_never_falls_back() {
        let a = ok("a", vec![win("primary", 7 * DAY, 100.0, NOW + DAY)]);
        let b = ok("b", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        let r = SelectionRequest {
            explicit_account: Some("a"),
            ..req()
        };
        let sel = select(&r, &[a.clone(), b.clone()]);
        assert!(sel.selected().is_none());
        let r = SelectionRequest {
            explicit_account: Some("zzz"),
            ..req()
        };
        match select(&r, &[a.clone(), b.clone()]) {
            Selection::NoCapacity { rejections, .. } => {
                assert_eq!(rejections.len(), 1);
                assert_eq!(rejections[0].reason, RejectReason::NotPresent);
                assert_eq!(rejections[0].credential.storage_key(), "openai-codex@zzz");
            }
            other => panic!("unexpected {other:?}"),
        }
        let r = SelectionRequest {
            explicit_account: Some("Bad Label"),
            ..req()
        };
        match select(&r, &[a, b]) {
            Selection::NoCapacity { rejections, .. } => assert_eq!(
                rejections[0].reason,
                RejectReason::InvalidLabel {
                    label: "Bad Label".into()
                }
            ),
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn other_providers_and_exclusions_are_ignored() {
        let mut other = ok("a", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        other.credential =
            CredentialRef::new(OAuthProviderId::Anthropic, Account::parse("a").unwrap());
        let b = ok("b", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        let excl = vec![cred("b")];
        let r = SelectionRequest {
            exclude: &excl,
            ..req()
        };
        let sel = select(&r, &[other, b]);
        match sel {
            Selection::NoCapacity { rejections, .. } => {
                assert_eq!(rejections.len(), 1);
                assert_eq!(rejections[0].reason, RejectReason::Excluded);
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn failover_is_bounded_and_never_after_output() {
        let a = ok("a", vec![win("primary", 7 * DAY, 100.0, NOW + DAY)]);
        let b = ok("b", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)]);
        let c = ok("c", vec![win("primary", 7 * DAY, 100.0, NOW + DAY)]);
        let cands = [a, b, c];
        let ev = FailureEvidence {
            kind: FailureKind::QuotaExhaustedPreOutput,
            output_started: false,
            tool_activity: false,
            failovers_so_far: 0,
        };
        match failover(&req(), &cred("a"), &ev, &cands) {
            FailoverDecision::Failover { credential } => {
                assert_eq!(credential.storage_key(), "openai-codex@b")
            }
            other => panic!("unexpected {other:?}"),
        }
        // second failover denied
        let ev2 = FailureEvidence {
            failovers_so_far: 1,
            ..ev.clone()
        };
        assert!(matches!(
            failover(&req(), &cred("b"), &ev2, &cands),
            FailoverDecision::NoFailover { .. }
        ));
        // output started → never
        let ev3 = FailureEvidence {
            output_started: true,
            ..ev.clone()
        };
        assert!(matches!(
            failover(&req(), &cred("a"), &ev3, &cands),
            FailoverDecision::NoFailover { .. }
        ));
        // tool activity → never
        let ev4 = FailureEvidence {
            tool_activity: true,
            ..ev.clone()
        };
        assert!(matches!(
            failover(&req(), &cred("a"), &ev4, &cands),
            FailoverDecision::NoFailover { .. }
        ));
        // ordinary 429 → never
        let ev5 = FailureEvidence {
            kind: FailureKind::RateLimited,
            ..ev.clone()
        };
        assert!(matches!(
            failover(&req(), &cred("a"), &ev5, &cands),
            FailoverDecision::NoFailover { .. }
        ));
        // explicit account → never
        let r = SelectionRequest {
            explicit_account: Some("a"),
            ..req()
        };
        assert!(matches!(
            failover(&r, &cred("a"), &ev, &cands),
            FailoverDecision::NoFailover { .. }
        ));
        // no other eligible seat → NoFailover, and the failed seat is excluded
        // even if its snapshot still claims headroom.
        let only = [ok("a", vec![win("primary", 7 * DAY, 0.0, NOW + DAY)])];
        assert!(matches!(
            failover(&req(), &cred("a"), &ev, &only),
            FailoverDecision::NoFailover { .. }
        ));
    }

    #[test]
    fn unknown_utilization_sorts_after_known() {
        let proven = ok(
            "p",
            vec![WindowLimit {
                used_percent: None,
                limit_reached: Some(false),
                ..win("primary", 7 * DAY, 0.0, NOW + DAY)
            }],
        );
        let known = ok("k", vec![win("primary", 7 * DAY, 95.0, NOW + DAY)]);
        assert_eq!(
            select(&req(), &[proven.clone(), known])
                .selected()
                .unwrap()
                .storage_key(),
            "openai-codex@k"
        );
        assert_eq!(
            select(&req(), &[proven]).selected().unwrap().storage_key(),
            "openai-codex@p"
        );
    }

    #[test]
    fn model_matching_uses_family_tokens() {
        assert!(model_matches("sonnet", "claude-sonnet-4-6"));
        assert!(model_matches("Sonnet", "CLAUDE-SONNET-4-6"));
        assert!(model_matches("gpt-6-astra", "gpt-6-astra"));
        assert!(!model_matches("opus", "claude-sonnet-4-6"));
        assert!(!model_matches("", "x") && !model_matches("x", ""));
        let w = WindowLimit {
            models: Some(vec!["sonnet".into()]),
            ..win("seven_day_sonnet", 7 * DAY, 100.0, NOW + DAY)
        };
        assert!(w.applies_to(Some("claude-sonnet-4-6")));
        assert!(!w.applies_to(Some("claude-opus-4-6")));
        assert!(w.applies_to(None));
        let acct = ok("a", vec![win("seven_day", 7 * DAY, 1.0, NOW + DAY), w]);
        let r = SelectionRequest {
            model: Some("claude-sonnet-4-6"),
            ..req()
        };
        assert!(select(&r, std::slice::from_ref(&acct)).selected().is_none());
        let r = SelectionRequest {
            model: Some("claude-opus-4-6"),
            ..req()
        };
        assert!(select(&r, std::slice::from_ref(&acct)).selected().is_some());
    }

    #[test]
    fn serde_round_trip_is_secret_free() {
        let a = ok("a", vec![win("primary", 7 * DAY, 100.0, NOW + DAY)]);
        let sel = select(&req(), &[a]);
        let json = serde_json::to_string(&sel).unwrap();
        assert!(json.contains("no_capacity"));
        let back: Selection = serde_json::from_str(&json).unwrap();
        assert_eq!(back, sel);
    }

    // ── SoonestReset ─────────────────────────────────────────────────────────

    /// Request under [`Strategy::SoonestReset`] with the constructor defaults
    /// (sticky, default horizon, no current seat).
    fn sr_req() -> SelectionRequest<'static> {
        SelectionRequest::soonest_reset(OAuthProviderId::OpenAiCodex, NOW, 30 * 60 * 1000)
    }

    /// Observation instant used by [`ok`].
    const OBSERVED: u64 = NOW - 1000;

    /// Anchored weekly window: reset is a fixed instant unrelated to the
    /// observation (Anthropic-like, or a Codex seat already in use).
    fn anchored(used: f64, resets: u64) -> WindowLimit {
        win("primary", 7 * DAY, used, resets)
    }

    /// Unanchored weekly window: idle Codex-like seat reporting 0 % and a
    /// reset exactly one duration after the observation.
    fn unanchored() -> WindowLimit {
        win("primary", 7 * DAY, 0.0, OBSERVED + 7 * DAY)
    }

    /// Headroom proven but no reset instant reported.
    fn no_reset(used: f64) -> WindowLimit {
        WindowLimit {
            resets_at_ms: None,
            ..win("primary", 7 * DAY, used, 0)
        }
    }

    fn label_of(sel: &Selection) -> &str {
        sel.selected().expect("a selection").account.label_str()
    }

    fn ranks(sel: &Selection) -> Vec<(String, u32)> {
        let (Selection::Selected { rejections, .. } | Selection::NoCapacity { rejections, .. }) =
            sel;
        rejections
            .iter()
            .filter_map(|r| match r.reason {
                RejectReason::Outranked { rank } => {
                    Some((r.credential.account.label_str().to_string(), rank))
                }
                _ => None,
            })
            .collect()
    }

    #[test]
    fn soonest_reset_beats_lower_utilization_where_lowest_utilization_does_not() {
        // `a` is busier but its capacity expires sooner.
        let a = ok("a", vec![anchored(60.0, NOW + 2 * DAY)]);
        let b = ok("b", vec![anchored(10.0, NOW + 5 * DAY)]);
        let cands = [b.clone(), a.clone()];
        match select(&sr_req(), &cands) {
            Selection::Selected {
                credential,
                tier,
                budget_reset_ms,
                utilization,
                ..
            } => {
                assert_eq!(credential.storage_key(), "openai-codex@a");
                assert_eq!(tier, 3);
                assert_eq!(budget_reset_ms, Some(NOW + 2 * DAY));
                assert_eq!(utilization, Some(60.0));
            }
            other => panic!("unexpected {other:?}"),
        }
        // Same input, previous strategy: spreads load to the emptier seat.
        assert_eq!(label_of(&select(&req(), &cands)), "b");
        // `new` keeps its defaults byte-for-byte: not sticky, no current.
        let r = req();
        assert_eq!(r.strategy, Strategy::LowestUtilization);
        assert!(!r.sticky && r.current.is_none());
        assert_eq!(r.urgent_horizon_ms, DEFAULT_URGENT_HORIZON_MS);
        let s = sr_req();
        assert_eq!(s.strategy, Strategy::SoonestReset);
        assert!(s.sticky && s.current.is_none());
        assert_eq!(s.urgent_horizon_ms, DEFAULT_URGENT_HORIZON_MS);
    }

    #[test]
    fn tiers_order_urgent_then_unanchored_then_far_then_no_reset() {
        let urgent = ok("u", vec![anchored(50.0, NOW + 6 * HOUR)]);
        let sliding = ok("s", vec![unanchored()]);
        let far = ok("f", vec![anchored(0.0, NOW + 5 * DAY)]);
        let none = ok("n", vec![no_reset(0.0)]);
        let r = sr_req();
        for (cap, tier, anch) in [
            (&urgent, 1u8, Some(true)),
            (&sliding, 2, Some(false)),
            (&far, 3, Some(true)),
            (&none, 4, None),
        ] {
            let e = evaluate(&r, cap).unwrap();
            assert_eq!(e.tier, tier, "{}", cap.credential.storage_key());
            assert_eq!(e.anchored, anch, "{}", cap.credential.storage_key());
        }
        // Tier is computed regardless of strategy (for `auth plan`).
        assert_eq!(evaluate(&req(), &sliding).unwrap().tier, 2);
        // Lower utilization/preference never beats a higher tier.
        let cands = [none.clone(), far.clone(), sliding.clone(), urgent.clone()];
        let sel = select(&r, &cands);
        assert_eq!(label_of(&sel), "u");
        assert_eq!(
            ranks(&sel),
            vec![
                ("s".to_string(), 2),
                ("f".to_string(), 3),
                ("n".to_string(), 4)
            ]
        );
        assert_eq!(
            label_of(&select(&r, &[none.clone(), far.clone(), sliding])),
            "s"
        );
        assert_eq!(label_of(&select(&r, &[none.clone(), far])), "f");
        assert_eq!(label_of(&select(&r, &[none])), "n");
        // Urgency is horizon-relative: with a 1 h horizon the 6 h seat is tier 3
        // and loses to the unanchored seat.
        let short = SelectionRequest {
            urgent_horizon_ms: HOUR,
            ..sr_req()
        };
        assert_eq!(evaluate(&short, &urgent).unwrap().tier, 3);
        assert_eq!(
            label_of(&select(&short, &[urgent, ok("s", vec![unanchored()])])),
            "s"
        );
        // Exactly at the horizon is still urgent (inclusive).
        let edge = ok("e", vec![anchored(0.0, NOW + DEFAULT_URGENT_HORIZON_MS)]);
        assert_eq!(evaluate(&sr_req(), &edge).unwrap().tier, 1);
    }

    #[test]
    fn within_tier_orders_by_reset_preference_or_utilization() {
        // Tier 1: soonest reset wins even with higher utilization.
        let a = ok("a", vec![anchored(90.0, NOW + 2 * HOUR)]);
        let b = ok("b", vec![anchored(1.0, NOW + 3 * HOUR)]);
        assert_eq!(label_of(&select(&sr_req(), &[b, a])), "a");
        // Tier 2: preference, then storage key; utilization is irrelevant.
        let s1 = ok("s1", vec![unanchored()]);
        let s2 = ok("s2", vec![unanchored()]);
        assert_eq!(
            label_of(&select(&sr_req(), &[s2.clone(), s1.clone()])),
            "s1"
        );
        let pref = vec!["s2".to_string()];
        let r = SelectionRequest {
            preference: &pref,
            ..sr_req()
        };
        assert_eq!(label_of(&select(&r, &[s1, s2])), "s2");
        // Tier 4: lowest utilization, unknown last.
        let n1 = ok("n1", vec![no_reset(40.0)]);
        let n2 = ok("n2", vec![no_reset(5.0)]);
        let n3 = ok(
            "n3",
            vec![WindowLimit {
                used_percent: None,
                limit_reached: Some(false),
                ..no_reset(0.0)
            }],
        );
        let sel = select(&sr_req(), &[n3, n1, n2]);
        assert_eq!(label_of(&sel), "n2");
        assert_eq!(
            ranks(&sel),
            vec![("n1".to_string(), 2), ("n3".to_string(), 3)]
        );
        // Equal resets in tier 3: lowest utilization breaks the tie.
        let t1 = ok("t1", vec![anchored(30.0, NOW + 3 * DAY)]);
        let t2 = ok("t2", vec![anchored(20.0, NOW + 3 * DAY)]);
        assert_eq!(label_of(&select(&sr_req(), &[t1, t2])), "t2");
    }

    #[test]
    fn exhausted_soonest_seat_is_skipped_to_next_soonest() {
        let x = ok("x", vec![anchored(100.0, NOW + HOUR)]);
        let a = ok("a", vec![anchored(20.0, NOW + 2 * DAY)]);
        let b = ok("b", vec![anchored(20.0, NOW + 3 * DAY)]);
        let sel = select(&sr_req(), &[b, x.clone(), a]);
        assert_eq!(label_of(&sel), "a");
        let Selection::Selected { rejections, .. } = &sel else {
            panic!("expected selection");
        };
        assert!(rejections
            .iter()
            .any(|r| r.credential.account.label_str() == "x"
                && r.reason
                    == RejectReason::Exhausted {
                        window: "primary".into(),
                        resets_at_ms: Some(NOW + HOUR),
                    }));
        // Everything exhausted: earliest *future* reset is reported.
        let y = ok("y", vec![anchored(100.0, NOW + 2 * DAY)]);
        let past = ok("p", vec![anchored(100.0, NOW - HOUR)]);
        match select(&sr_req(), &[y, past, x]) {
            Selection::NoCapacity {
                earliest_reset_ms, ..
            } => assert_eq!(earliest_reset_ms, Some(NOW + HOUR)),
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn five_hour_throttle_rejects_then_reenters_after_reset() {
        let throttled = ok(
            "t",
            vec![
                win("five_hour", 5 * HOUR, 100.0, NOW + HOUR),
                win("seven_day", 7 * DAY, 30.0, NOW + 2 * DAY),
            ],
        );
        let other = ok("o", vec![win("seven_day", 7 * DAY, 10.0, NOW + 4 * DAY)]);
        let sel = select(&sr_req(), &[throttled, other.clone()]);
        assert_eq!(label_of(&sel), "o");
        let Selection::Selected { rejections, .. } = &sel else {
            panic!("expected selection");
        };
        assert_eq!(
            rejections[0].reason,
            RejectReason::Exhausted {
                window: "five_hour".into(),
                resets_at_ms: Some(NOW + HOUR),
            }
        );
        // Clock past the 5 h reset, fresh observations: the 5 h window is
        // empty again and the seat wins on its sooner 7 d deadline.
        let now2 = NOW + HOUR + 1;
        let mut throttled2 = ok(
            "t",
            vec![
                win("five_hour", 5 * HOUR, 0.0, now2 + 5 * HOUR),
                win("seven_day", 7 * DAY, 30.0, NOW + 2 * DAY),
            ],
        );
        throttled2.observed_at_ms = Some(now2 - 1000);
        let mut other2 = other;
        other2.observed_at_ms = Some(now2 - 1000);
        let r = SelectionRequest {
            now_ms: now2,
            ..sr_req()
        };
        match select(&r, &[other2, throttled2]) {
            Selection::Selected {
                credential,
                tier,
                budget_reset_ms,
                ..
            } => {
                assert_eq!(credential.storage_key(), "openai-codex@t");
                assert_eq!(tier, 3);
                assert_eq!(budget_reset_ms, Some(NOW + 2 * DAY));
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn is_unanchored_classifies_sliding_resets_only() {
        let obs = NOW - 90_000;
        // Codex-like idle seat: reset == observed + duration.
        let codex_idle = win("primary", 7 * DAY, 0.0, obs + 7 * DAY);
        assert_eq!(is_unanchored(&codex_idle, obs), Some(true));
        // One minute of skew either way is within tolerance.
        let skewed = win("primary", 7 * DAY, 0.0, obs + 7 * DAY + 60_000);
        assert_eq!(is_unanchored(&skewed, obs), Some(true));
        let skewed = win("primary", 7 * DAY, 0.0, obs + 7 * DAY - 60_000);
        assert_eq!(is_unanchored(&skewed, obs), Some(true));
        // Just beyond tolerance → anchored.
        let beyond = win(
            "primary",
            7 * DAY,
            0.0,
            obs + 7 * DAY + UNANCHORED_TOLERANCE_MS + 1,
        );
        assert_eq!(is_unanchored(&beyond, obs), Some(false));
        // Anthropic-like: 0 % but the calendar reset is 5 days out.
        let anthropic = win("seven_day", 7 * DAY, 0.0, obs + 5 * DAY);
        assert_eq!(is_unanchored(&anthropic, obs), Some(false));
        // Real consumption means the window has already been anchored.
        let used = win("primary", 7 * DAY, 40.0, obs + 7 * DAY);
        assert_eq!(is_unanchored(&used, obs), Some(false));
        // Threshold is inclusive.
        let half = win(
            "primary",
            7 * DAY,
            UNANCHORED_MAX_USED_PERCENT,
            obs + 7 * DAY,
        );
        assert_eq!(is_unanchored(&half, obs), Some(true));
        // Unreported utilization is never evidence of idleness.
        let unreported = WindowLimit {
            used_percent: None,
            limit_reached: Some(false),
            ..codex_idle.clone()
        };
        assert_eq!(is_unanchored(&unreported, obs), Some(false));
        // Missing duration or reset → unknown.
        let no_dur = WindowLimit {
            duration_ms: None,
            ..codex_idle.clone()
        };
        assert_eq!(is_unanchored(&no_dur, obs), None);
        let no_reset = WindowLimit {
            resets_at_ms: None,
            ..codex_idle
        };
        assert_eq!(is_unanchored(&no_reset, obs), None);
    }

    #[test]
    fn budget_window_prefers_weekly_then_longest() {
        let five_h = win("five_hour", 5 * HOUR, 0.0, NOW + HOUR);
        let one_h = win("one_hour", HOUR, 0.0, NOW + HOUR);
        let thirty_d = win("thirty_day", 30 * DAY, 0.0, NOW + 20 * DAY);
        let weekly_wide = win("weekly", 7 * DAY, 0.0, NOW + 3 * DAY);
        let weekly_scoped = WindowLimit {
            id: "aaa_weekly_scoped".into(),
            models: Some(vec!["m".into()]),
            ..weekly_wide.clone()
        };
        // Account-wide weekly beats model-scoped weekly beats longest other.
        let all = [
            thirty_d.clone(),
            weekly_scoped.clone(),
            five_h.clone(),
            weekly_wide.clone(),
        ];
        assert_eq!(
            budget_window(&all, Some("m")).map(|w| w.id.as_str()),
            Some("weekly")
        );
        assert_eq!(
            budget_window(&all, None).map(|w| w.id.as_str()),
            Some("weekly")
        );
        let no_wide = [thirty_d.clone(), weekly_scoped.clone(), five_h.clone()];
        assert_eq!(
            budget_window(&no_wide, Some("m")).map(|w| w.id.as_str()),
            Some("aaa_weekly_scoped")
        );
        // Scoped weekly does not apply to another model → longest applicable.
        assert_eq!(
            budget_window(&no_wide, Some("other")).map(|w| w.id.as_str()),
            Some("thirty_day")
        );
        // No weekly at all → longest duration.
        assert_eq!(
            budget_window(&[five_h.clone(), one_h.clone()], None).map(|w| w.id.as_str()),
            Some("five_hour")
        );
        // Equal durations: account-wide first, then id.
        let b5 = WindowLimit {
            id: "b5".into(),
            ..five_h.clone()
        };
        let a5_scoped = WindowLimit {
            id: "a5".into(),
            models: Some(vec!["m".into()]),
            ..five_h.clone()
        };
        assert_eq!(
            budget_window(&[b5.clone(), a5_scoped.clone()], Some("m")).map(|w| w.id.as_str()),
            Some("b5")
        );
        let a5 = WindowLimit {
            id: "a5".into(),
            ..five_h.clone()
        };
        assert_eq!(
            budget_window(&[b5, a5], None).map(|w| w.id.as_str()),
            Some("a5")
        );
        // No durations → no budget window.
        let no_dur = WindowLimit {
            duration_ms: None,
            ..five_h
        };
        assert!(budget_window(&[no_dur.clone(), no_dur], None).is_none());
        assert!(budget_window(&[], None).is_none());
        // `weekly_window` is unchanged by the shared picker.
        assert_eq!(weekly_window(&all).map(|w| w.id.as_str()), Some("weekly"));
    }

    #[test]
    fn past_reset_with_headroom_is_not_reset_evidence() {
        // Fresh reading, headroom, but the reported reset already passed: no
        // deadline can be inferred → tier 4, not tier 1 with a zero horizon.
        let stale_reset = ok("p", vec![anchored(20.0, NOW - 1)]);
        let e = evaluate(&sr_req(), &stale_reset).unwrap();
        assert_eq!(e.budget_reset_ms, None);
        assert_eq!(e.anchored, None);
        assert_eq!(e.tier, 4);
        let far = ok("f", vec![anchored(80.0, NOW + 6 * DAY)]);
        assert_eq!(label_of(&select(&sr_req(), &[stale_reset, far])), "f");
    }

    #[test]
    fn sticky_keeps_current_within_tier_3() {
        let cur = cred("cur");
        let current = ok("cur", vec![anchored(30.0, NOW + 5 * DAY)]);
        let sooner = ok("soon", vec![anchored(10.0, NOW + 2 * DAY)]);
        let r = SelectionRequest {
            current: Some(&cur),
            ..sr_req()
        };
        let sel = select(&r, &[sooner.clone(), current.clone()]);
        assert_eq!(label_of(&sel), "cur");
        assert_eq!(ranks(&sel), vec![("soon".to_string(), 2)]);
        // Without a current seat the sooner deadline wins.
        assert_eq!(
            label_of(&select(&sr_req(), &[sooner.clone(), current.clone()])),
            "soon"
        );
        // sticky = false ignores `current`.
        let r = SelectionRequest { sticky: false, ..r };
        assert_eq!(label_of(&select(&r, &[sooner, current])), "soon");
    }

    #[test]
    fn sticky_yields_to_strictly_higher_tier() {
        let cur = cred("cur");
        let current = ok("cur", vec![anchored(10.0, NOW + 5 * DAY)]);
        let urgent = ok("urg", vec![anchored(90.0, NOW + 6 * HOUR)]);
        let r = SelectionRequest {
            current: Some(&cur),
            ..sr_req()
        };
        assert_eq!(label_of(&select(&r, &[current.clone(), urgent])), "urg");
        // Tier 2 also outranks a tier-3 current seat.
        let sliding = ok("sld", vec![unanchored()]);
        assert_eq!(label_of(&select(&r, &[current, sliding])), "sld");
        // But a tier-2 current seat is kept over another tier-2 seat that
        // would otherwise sort first, and over any tier-3 seat.
        let cur_sliding = ok("cur", vec![unanchored()]);
        let a_sliding = ok("a", vec![unanchored()]);
        let far = ok("far", vec![anchored(0.0, NOW + 2 * DAY)]);
        assert_eq!(label_of(&select(&r, &[a_sliding, far, cur_sliding])), "cur");
    }

    #[test]
    fn sticky_tier1_yields_only_to_strictly_sooner_reset() {
        let cur = cred("cur");
        let current = ok("cur", vec![anchored(50.0, NOW + 10 * HOUR)]);
        let r = SelectionRequest {
            current: Some(&cur),
            ..sr_req()
        };
        let sooner = ok("soon", vec![anchored(80.0, NOW + 6 * HOUR)]);
        assert_eq!(label_of(&select(&r, &[current.clone(), sooner])), "soon");
        // Equal reset with lower utilization would sort first, but it is not
        // strictly sooner → current kept.
        let equal = ok("eq", vec![anchored(1.0, NOW + 10 * HOUR)]);
        let sel = select(&r, &[equal.clone(), current.clone()]);
        assert_eq!(label_of(&sel), "cur");
        assert_eq!(ranks(&sel), vec![("eq".to_string(), 2)]);
        // Later reset in tier 1 → current kept.
        let later = ok("late", vec![anchored(0.0, NOW + 12 * HOUR)]);
        assert_eq!(label_of(&select(&r, &[later, current])), "cur");
    }

    #[test]
    fn sticky_never_keeps_ineligible_current_and_only_applies_to_soonest_reset() {
        let cur = cred("cur");
        let other = ok("o", vec![anchored(50.0, NOW + 5 * DAY)]);
        let r = SelectionRequest {
            current: Some(&cur),
            ..sr_req()
        };
        // Exhausted current → switch.
        let exhausted = ok("cur", vec![anchored(100.0, NOW + DAY)]);
        assert_eq!(label_of(&select(&r, &[exhausted, other.clone()])), "o");
        // Cooling-down current → switch.
        let mut cooling = ok("cur", vec![anchored(0.0, NOW + DAY)]);
        cooling.cooldown_until_ms = Some(NOW + HOUR);
        assert_eq!(label_of(&select(&r, &[cooling, other.clone()])), "o");
        // Stale current → switch.
        let mut stale = ok("cur", vec![anchored(0.0, NOW + DAY)]);
        stale.observed_at_ms = Some(NOW - 2 * HOUR);
        assert_eq!(label_of(&select(&r, &[stale, other.clone()])), "o");
        // Excluded current → switch (exclusion wins over stickiness).
        let excl = vec![cur.clone()];
        let r_excl = SelectionRequest {
            exclude: &excl,
            ..r.clone()
        };
        let healthy = ok("cur", vec![anchored(0.0, NOW + DAY)]);
        assert_eq!(
            label_of(&select(&r_excl, &[healthy.clone(), other.clone()])),
            "o"
        );
        // Current not among candidates at all → normal ranking, no panic.
        assert_eq!(label_of(&select(&r, std::slice::from_ref(&other))), "o");
        // Stickiness never applies to the other strategies, even if asked.
        let busy_current = ok("cur", vec![anchored(90.0, NOW + 5 * DAY)]);
        let r_lu = SelectionRequest {
            strategy: Strategy::LowestUtilization,
            sticky: true,
            current: Some(&cur),
            ..req()
        };
        assert_eq!(
            label_of(&select(&r_lu, &[busy_current.clone(), other.clone()])),
            "o"
        );
        let pref = vec!["o".to_string()];
        let r_po = SelectionRequest {
            strategy: Strategy::PreferenceOrder,
            sticky: true,
            current: Some(&cur),
            preference: &pref,
            ..req()
        };
        assert_eq!(label_of(&select(&r_po, &[busy_current, other])), "o");
    }

    #[test]
    fn failover_under_soonest_reset_never_repicks_sticky_failed_seat() {
        let cur = cred("a");
        // `a` still claims headroom and would be kept by stickiness.
        let a = ok("a", vec![anchored(0.0, NOW + 2 * DAY)]);
        let b = ok("b", vec![anchored(50.0, NOW + 5 * DAY)]);
        let r = SelectionRequest {
            current: Some(&cur),
            ..sr_req()
        };
        assert_eq!(label_of(&select(&r, &[a.clone(), b.clone()])), "a");
        let ev = FailureEvidence {
            kind: FailureKind::QuotaExhaustedPreOutput,
            output_started: false,
            tool_activity: false,
            failovers_so_far: 0,
        };
        match failover(&r, &cur, &ev, &[a.clone(), b]) {
            FailoverDecision::Failover { credential } => {
                assert_eq!(credential.storage_key(), "openai-codex@b")
            }
            other => panic!("unexpected {other:?}"),
        }
        assert!(matches!(
            failover(&r, &cur, &ev, &[a]),
            FailoverDecision::NoFailover { .. }
        ));
    }

    #[test]
    fn explicit_account_under_soonest_reset_never_falls_back() {
        let a = ok("a", vec![anchored(100.0, NOW + HOUR)]);
        let b = ok("b", vec![anchored(0.0, NOW + 6 * HOUR)]);
        let cur = cred("b");
        // Explicit exhausted seat: fail, even though `b` is urgent and pinned.
        let r = SelectionRequest {
            explicit_account: Some("a"),
            current: Some(&cur),
            ..sr_req()
        };
        match select(&r, &[a.clone(), b.clone()]) {
            Selection::NoCapacity { rejections, .. } => {
                assert_eq!(rejections.len(), 1);
                assert_eq!(rejections[0].credential.storage_key(), "openai-codex@a");
            }
            other => panic!("unexpected {other:?}"),
        }
        // Explicit healthy seat: other seats are never even evaluated.
        let r = SelectionRequest {
            explicit_account: Some("b"),
            ..sr_req()
        };
        match select(&r, &[a, b]) {
            Selection::Selected {
                credential,
                rejections,
                tier,
                ..
            } => {
                assert_eq!(credential.storage_key(), "openai-codex@b");
                assert!(rejections.is_empty());
                assert_eq!(tier, 1);
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    /// All permutations of `items` (Heap's algorithm), for order-independence checks.
    fn permutations<T: Clone>(items: &[T]) -> Vec<Vec<T>> {
        fn go<T: Clone>(k: usize, a: &mut Vec<T>, out: &mut Vec<Vec<T>>) {
            if k <= 1 {
                out.push(a.clone());
                return;
            }
            go(k - 1, a, out);
            for i in 0..k - 1 {
                if k.is_multiple_of(2) {
                    a.swap(i, k - 1);
                } else {
                    a.swap(0, k - 1);
                }
                go(k - 1, a, out);
            }
        }
        let mut a = items.to_vec();
        let mut out = Vec::new();
        go(a.len(), &mut a, &mut out);
        out
    }

    #[test]
    fn soonest_reset_is_deterministic_under_candidate_shuffle() {
        let cur = cred("t3b");
        let seats = vec![
            ok("t1", vec![anchored(70.0, NOW + 3 * HOUR)]),
            ok("t2", vec![unanchored()]),
            ok("t3a", vec![anchored(5.0, NOW + 2 * DAY)]),
            ok("t3b", vec![anchored(40.0, NOW + 4 * DAY)]),
            ok("x", vec![anchored(100.0, NOW + DAY)]),
        ];
        let r = SelectionRequest {
            current: Some(&cur),
            ..sr_req()
        };
        let perms = permutations(&seats);
        assert_eq!(perms.len(), 120);
        let baseline = select(&r, &seats);
        assert_eq!(label_of(&baseline), "t1");
        let normalize = |sel: &Selection| {
            let Selection::Selected {
                credential,
                tier,
                budget_reset_ms,
                utilization,
                rejections,
            } = sel
            else {
                panic!("expected selection");
            };
            let mut rej: Vec<(String, RejectReason)> = rejections
                .iter()
                .map(|r| (r.credential.storage_key(), r.reason.clone()))
                .collect();
            rej.sort_by(|a, b| a.0.cmp(&b.0));
            (
                credential.storage_key(),
                *tier,
                *budget_reset_ms,
                *utilization,
                rej,
            )
        };
        let expected = normalize(&baseline);
        assert_eq!(
            ranks(&baseline),
            vec![
                ("t2".to_string(), 2),
                ("t3a".to_string(), 3),
                ("t3b".to_string(), 4)
            ]
        );
        for p in perms {
            assert_eq!(normalize(&select(&r, &p)), expected);
        }
    }

    #[test]
    fn outranked_ranks_are_two_to_n_in_ranking_order() {
        let seats = [
            ok("c", vec![anchored(0.0, NOW + 4 * DAY)]),
            ok("a", vec![anchored(0.0, NOW + 2 * DAY)]),
            ok("d", vec![anchored(0.0, NOW + 5 * DAY)]),
            ok("b", vec![anchored(0.0, NOW + 3 * DAY)]),
        ];
        let sel = select(&sr_req(), &seats);
        assert_eq!(label_of(&sel), "a");
        assert_eq!(
            ranks(&sel),
            vec![
                ("b".to_string(), 2),
                ("c".to_string(), 3),
                ("d".to_string(), 4)
            ]
        );
        // Ranks are produced under the existing strategies too.
        let lu = [
            ok("hi", vec![anchored(80.0, NOW + DAY)]),
            ok("lo", vec![anchored(10.0, NOW + DAY)]),
            ok("mid", vec![anchored(50.0, NOW + DAY)]),
        ];
        let sel = select(&req(), &lu);
        assert_eq!(label_of(&sel), "lo");
        assert_eq!(
            ranks(&sel),
            vec![("mid".to_string(), 2), ("hi".to_string(), 3)]
        );
        assert_eq!(
            RejectReason::Outranked { rank: 3 }.to_string(),
            "eligible; outranked (rank 3)"
        );
    }

    #[test]
    fn soonest_reset_serde_is_backward_compatible() {
        assert_eq!(
            serde_json::to_string(&Strategy::SoonestReset).unwrap(),
            "\"soonest_reset\""
        );
        assert_eq!(
            serde_json::from_str::<Strategy>("\"soonest_reset\"").unwrap(),
            Strategy::SoonestReset
        );
        let a = ok("a", vec![anchored(10.0, NOW + 2 * HOUR)]);
        let b = ok("b", vec![anchored(10.0, NOW + 3 * HOUR)]);
        let sel = select(&sr_req(), &[a, b]);
        let json = serde_json::to_string(&sel).unwrap();
        assert!(json.contains("\"tier\":1"));
        assert!(json.contains("\"budget_reset_ms\""));
        assert!(json.contains("\"rank\":2"));
        assert_eq!(serde_json::from_str::<Selection>(&json).unwrap(), sel);
        // Records written before tiers/ranks existed still decode.
        let old = r#"{"outcome":"selected","credential":"openai-codex@a","utilization":10.0,"rejections":[{"credential":"openai-codex@b","reason":{"reason":"outranked"}}]}"#;
        match serde_json::from_str::<Selection>(old).unwrap() {
            Selection::Selected {
                tier,
                budget_reset_ms,
                rejections,
                ..
            } => {
                assert_eq!(tier, 0);
                assert_eq!(budget_reset_ms, None);
                assert_eq!(rejections[0].reason, RejectReason::Outranked { rank: 0 });
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    // ── Typed selection failures ─────────────────────────────────────────

    fn failed(label: &str, failure: ObservationFailure) -> AccountCapacity {
        AccountCapacity::failed(cred(label), failure)
    }

    fn failure_of(candidates: &[AccountCapacity]) -> SelectionFailure {
        match select(&req(), candidates) {
            Selection::NoCapacity { rejections, .. } => {
                SelectionFailure::from_rejections(&rejections, NOW)
            }
            other => panic!("expected no capacity, got {other:?}"),
        }
    }

    #[test]
    fn observation_failure_maps_to_a_never_capacity_observation() {
        use AccountFailureKind as K;
        for (kind, obs) in [
            (K::UsageRateLimited, QuotaObservation::Unknown),
            (K::RefreshTransient, QuotaObservation::Unknown),
            (K::UsageUnauthorized, QuotaObservation::AuthError),
            (K::RefreshRejected, QuotaObservation::AuthError),
            (K::CredentialMissing, QuotaObservation::AuthError),
            (K::UsageMalformed, QuotaObservation::Malformed),
            (K::Unsupported, QuotaObservation::Unsupported),
            (K::RefreshActionRequired, QuotaObservation::Unknown),
        ] {
            assert_eq!(ObservationFailure::new(kind).observation(), obs, "{kind}");
        }
        let f = ObservationFailure::new(K::UsageRateLimited)
            .with_status(429)
            .with_retry_after(Some(120));
        assert_eq!(
            f.to_string(),
            "usage_rate_limited, HTTP 429, retry after 120s"
        );
        assert_eq!(
            serde_json::to_value(&f).unwrap(),
            serde_json::json!({"kind": "usage_rate_limited", "http_status": 429, "retry_after_s": 120})
        );
        // Records without a cause (older writers) still decode.
        let old: Rejection = serde_json::from_str(
            r#"{"credential":"openai-codex@a","reason":{"reason":"unknown"}}"#,
        )
        .unwrap();
        assert_eq!(old.cause, None);
        assert_eq!(old.describe(), "quota unknown");
    }

    #[test]
    fn rejection_keeps_the_observation_cause_beside_a_cooldown() {
        use AccountFailureKind as K;
        let limited = ObservationFailure::new(K::UsageRateLimited).with_status(429);
        let mut cooling = failed("b", limited.clone());
        cooling.cooldown_until_ms = Some(NOW + HOUR);
        match select(&req(), &[failed("a", limited.clone()), cooling]) {
            Selection::NoCapacity { rejections, .. } => {
                assert_eq!(rejections[0].reason, RejectReason::Unknown);
                assert_eq!(rejections[0].cause.as_ref(), Some(&limited));
                assert_eq!(
                    rejections[0].describe(),
                    "quota unknown (usage_rate_limited, HTTP 429)"
                );
                // The verdict stays the policy's (eligibility unchanged),
                // but the read's failure is kept beside it (r2 blocker 1).
                assert!(matches!(
                    rejections[1].reason,
                    RejectReason::CoolingDown { .. }
                ));
                assert_eq!(rejections[1].cause.as_ref(), Some(&limited));
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    /// r2 blocker 1: a cooling account's failure keeps the observation kind
    /// (login advice depends on it) with the cooldown beside it, and still
    /// counts as limited for the top-level kind.
    #[test]
    fn a_cooling_accounts_failure_keeps_its_read_kind_and_counts_as_limited() {
        use AccountFailureKind as K;
        use SelectionFailureKind as S;
        let mut refused = failed(
            "a",
            ObservationFailure::new(K::UsageUnauthorized).with_status(401),
        );
        refused.cooldown_until_ms = Some(NOW + 2 * HOUR);
        let mut throttled = failed(
            "b",
            ObservationFailure::new(K::UsageRateLimited)
                .with_status(429)
                .with_retry_after(Some(90)),
        );
        throttled.cooldown_until_ms = Some(NOW + HOUR);
        let mut plain = ok("c", vec![win("primary", 5 * HOUR, 10.0, NOW + DAY)]);
        plain.cooldown_until_ms = Some(NOW + 3 * HOUR);

        let f = failure_of(&[refused, throttled, plain]);
        assert_eq!(f.kind, S::AllCoolingDown, "{f:?}");
        let a = &f.accounts[0];
        assert_eq!(
            (a.kind, a.http_status, a.cooling_down, a.until_ms),
            (K::UsageUnauthorized, Some(401), true, Some(NOW + 2 * HOUR))
        );
        let b = &f.accounts[1];
        assert_eq!(
            (b.kind, b.http_status, b.retry_after_s, b.cooling_down),
            (K::UsageRateLimited, Some(429), Some(90), true)
        );
        let c = &f.accounts[2];
        assert_eq!((c.kind, c.cooling_down), (K::CoolingDown, true));
        assert_eq!(f.login_labels(), vec!["a"]);
        assert_eq!(f.earliest_reset_ms, Some(NOW + HOUR));
        assert_eq!(
            f.accounts_field(),
            "a:usage_unauthorized:401:cooling,b:usage_rate_limited:429:cooling,c:cooling_down"
        );
        // Serialized with the flag; an account that is not cooling omits it.
        let v = serde_json::to_value(&f).unwrap();
        assert_eq!(v["accounts"][0]["cooling_down"], true);
        let g = failure_of(&[failed("d", ObservationFailure::new(K::UsageTimeout))]);
        assert!(serde_json::to_value(&g).unwrap()["accounts"][0]
            .get("cooling_down")
            .is_none());
    }

    /// r3, the B1 headline rule: the headline is what the user can act on
    /// now, classified over the accounts that aren't cooling down; a
    /// cooling account's read failure is shown per account (kind, status,
    /// Retry-After, the cooling flag and `:cooling` in the WARN field).
    /// A: every account cools, one also had a usage 429 → all_cooling_down.
    /// B: a cooling 429 plus a live refused login → credential_rejected.
    #[test]
    fn the_headline_skips_a_cooling_accounts_read_failure_which_stays_per_account() {
        use AccountFailureKind as K;
        use SelectionFailureKind as S;
        let throttled = || {
            let mut c = failed(
                "claude5",
                ObservationFailure::new(K::UsageRateLimited)
                    .with_status(429)
                    .with_retry_after(Some(90)),
            );
            c.cooldown_until_ms = Some(NOW + HOUR);
            c
        };
        let c5_kept = |f: &SelectionFailure| {
            let c5 = &f.accounts[0];
            assert_eq!(
                (
                    c5.account.as_str(),
                    c5.kind,
                    c5.http_status,
                    c5.retry_after_s,
                    c5.cooling_down,
                    c5.until_ms
                ),
                (
                    "claude5",
                    K::UsageRateLimited,
                    Some(429),
                    Some(90),
                    true,
                    Some(NOW + HOUR)
                ),
                "{f:?}"
            );
        };

        let mut plain = ok("claude6", vec![win("primary", 5 * HOUR, 10.0, NOW + DAY)]);
        plain.cooldown_until_ms = Some(NOW + 2 * HOUR);
        let a = failure_of(&[throttled(), plain]);
        assert_eq!(a.kind, S::AllCoolingDown, "{a:?}");
        c5_kept(&a);
        assert_eq!(
            a.accounts_field(),
            "claude5:usage_rate_limited:429:cooling,claude6:cooling_down"
        );
        assert_eq!(a.earliest_reset_ms, Some(NOW + HOUR));
        assert!(a.login_labels().is_empty(), "{a:?}");

        let refused = failed(
            "claude2",
            ObservationFailure::new(K::UsageUnauthorized).with_status(401),
        );
        let b = failure_of(&[throttled(), refused]);
        assert_eq!(b.kind, S::CredentialRejected, "{b:?}");
        c5_kept(&b);
        assert_eq!(
            b.accounts_field(),
            "claude5:usage_rate_limited:429:cooling,claude2:usage_unauthorized:401"
        );
        assert_eq!(b.earliest_reset_ms, Some(NOW + HOUR));
        assert_eq!(b.login_labels(), vec!["claude2"]);
    }

    /// r2 item 7: an account is usable again only when every exhausted
    /// window has reset and its cooldown has ended, so its `until` is the
    /// latest of those; the earliest reset is the minimum over accounts.
    #[test]
    fn an_accounts_until_is_its_latest_exhausted_reset_and_cooldown() {
        // (a) The second exhausted window resets later than the first.
        let later = ok(
            "a",
            vec![
                win("five_hour", 5 * HOUR, 100.0, NOW + HOUR),
                win("seven_day", 7 * DAY, 100.0, NOW + 3 * DAY),
            ],
        );
        // (b) The second exhausted window resets earlier than the first.
        let earlier = ok(
            "b",
            vec![
                win("seven_day", 7 * DAY, 100.0, NOW + 2 * DAY),
                win("five_hour", 5 * HOUR, 100.0, NOW + 2 * HOUR),
            ],
        );
        // Cooling beyond its only exhausted window's reset.
        let mut cooled = ok("c", vec![win("five_hour", 5 * HOUR, 100.0, NOW + HOUR)]);
        cooled.cooldown_until_ms = Some(NOW + 4 * HOUR);
        // An exhausted window without a reset makes the account's time unknown.
        let mut unknown = ok("d", vec![win("seven_day", 7 * DAY, 100.0, NOW + DAY)]);
        if let QuotaObservation::Ok { windows, .. } = &mut unknown.observation {
            windows.push(WindowLimit {
                resets_at_ms: None,
                ..win("five_hour", 5 * HOUR, 100.0, 0)
            });
        }

        let until = |f: &SelectionFailure, label: &str| {
            f.accounts
                .iter()
                .find(|a| a.account == label)
                .unwrap()
                .until_ms
        };
        let f = failure_of(&[later.clone(), earlier.clone(), cooled.clone(), unknown]);
        assert_eq!(until(&f, "a"), Some(NOW + 3 * DAY));
        assert_eq!(until(&f, "b"), Some(NOW + 2 * DAY));
        assert_eq!(until(&f, "c"), Some(NOW + 4 * HOUR));
        assert_eq!(until(&f, "d"), None);
        assert_eq!(f.earliest_reset_ms, Some(NOW + 4 * HOUR));
        assert_eq!(
            failure_of(&[later, earlier]).earliest_reset_ms,
            Some(NOW + 2 * DAY)
        );
        // Eligibility is unchanged: the first exhausted window still names
        // the verdict.
        match select(&req(), &[cooled]) {
            Selection::NoCapacity { rejections, .. } => {
                assert!(matches!(
                    rejections[0].reason,
                    RejectReason::CoolingDown { .. }
                ));
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    /// "Send again after" names a time some account is usable: a cooling
    /// account that also needs a login (or an action) is not usable when
    /// its cooldown ends, so it never sets the earliest reset; it still
    /// shows its own time.
    #[test]
    fn the_earliest_reset_skips_accounts_that_need_a_login_or_an_action() {
        use AccountFailureKind as K;
        let mut refused = failed(
            "a",
            ObservationFailure::new(K::UsageUnauthorized).with_status(401),
        );
        refused.cooldown_until_ms = Some(NOW + HOUR);
        let mut broken = failed("b", ObservationFailure::new(K::CredentialStore));
        broken.cooldown_until_ms = Some(NOW + 2 * HOUR);
        let mut plain = ok("c", vec![win("primary", 5 * HOUR, 10.0, NOW + DAY)]);
        plain.cooldown_until_ms = Some(NOW + 3 * HOUR);

        let f = failure_of(&[refused.clone(), broken.clone(), plain]);
        assert_eq!(f.kind, SelectionFailureKind::AllCoolingDown, "{f:?}");
        assert_eq!(f.earliest_reset_ms, Some(NOW + 3 * HOUR));
        assert_eq!(f.accounts[0].until_ms, Some(NOW + HOUR));
        assert_eq!(f.accounts[1].until_ms, Some(NOW + 2 * HOUR));
        assert_eq!(failure_of(&[refused, broken]).earliest_reset_ms, None);
    }

    /// r2 blocker 2: a refresh that needs action outside synaps and an
    /// unreadable store are their own kind, never `quota_unknown`.
    #[test]
    fn action_required_and_store_failures_get_their_own_kind() {
        use AccountFailureKind as K;
        use SelectionFailureKind as S;
        let action = ObservationFailure::new(K::RefreshActionRequired);
        let store = ObservationFailure::new(K::CredentialStore);
        let refused = ObservationFailure::new(K::UsageUnauthorized).with_status(401);
        let mut cooling = ok("c", vec![win("primary", 5 * HOUR, 10.0, NOW + DAY)]);
        cooling.cooldown_until_ms = Some(NOW + HOUR);

        for f in [
            failure_of(&[failed("a", action.clone())]),
            failure_of(&[failed("a", store.clone())]),
            failure_of(&[
                failed("a", action.clone()),
                failed("b", store.clone()),
                cooling.clone(),
            ]),
            failure_of(&[failed("a", action.clone()), failed("b", refused.clone())]),
        ] {
            assert_eq!(f.kind, S::ActionRequired, "{f:?}");
        }
        assert!(K::RefreshActionRequired.needs_action());
        assert!(K::CredentialStore.needs_action());
        assert!(
            !K::RefreshActionRequired.needs_login() && !K::RefreshActionRequired.is_transient()
        );
        let f = failure_of(&[failed("a", action.clone()), failed("b", store.clone())]);
        assert_eq!(f.action_labels(), vec!["a", "b"]);
        assert!(f.login_labels().is_empty());
        // A transient read elsewhere still means "capacity unproven".
        let f = failure_of(&[
            failed("a", action),
            failed("b", ObservationFailure::new(K::UsageTimeout)),
        ]);
        assert_eq!(f.kind, S::UsageReadFailed);
        assert_eq!(f.action_labels(), vec!["a"]);
        assert_eq!(S::ActionRequired.as_str(), "action_required");
        assert_eq!(S::CredentialStore.as_str(), "credential_store");
    }

    #[test]
    fn selection_failure_kind_priority_and_login_labels() {
        use AccountFailureKind as K;
        use SelectionFailureKind as S;
        let transient = ObservationFailure::new(K::UsageUpstream).with_status(503);
        let rejected = ObservationFailure::new(K::RefreshRejected);
        let exhausted = ok("x", vec![win("primary", 5 * HOUR, 100.0, NOW + 2 * HOUR)]);
        let mut cooling = ok("c", vec![win("primary", 5 * HOUR, 10.0, NOW + DAY)]);
        cooling.cooldown_until_ms = Some(NOW + HOUR);

        assert_eq!(failure_of(&[]).kind, S::NoCredentials);

        // Transient beats a rejected login: capacity unproven, not absent.
        let f = failure_of(&[
            failed("a", rejected.clone()),
            failed("b", transient.clone()),
        ]);
        assert_eq!(f.kind, S::UsageReadFailed);
        assert_eq!(f.login_labels(), vec!["a"]);
        assert_eq!(
            f.accounts_field(),
            "a:refresh_rejected,b:usage_upstream:503"
        );

        // Every account not cooling down needs a login.
        let f = failure_of(&[failed("a", rejected.clone()), cooling.clone()]);
        assert_eq!(f.kind, S::CredentialRejected);
        assert_eq!(f.login_labels(), vec!["a"]);
        assert_eq!(f.earliest_reset_ms, Some(NOW + HOUR));

        // Every account limited; the earliest reset over cooldowns and
        // exhausted windows.
        let f = failure_of(&[exhausted.clone(), cooling.clone()]);
        assert_eq!(f.kind, S::AllCoolingDown);
        assert_eq!(f.accounts_field(), "x:exhausted,c:cooling_down");
        assert_eq!(f.earliest_reset_ms, Some(NOW + HOUR));
        assert!(f.login_labels().is_empty());

        // A login problem among accounts that proved nothing is not
        // "every account needs a login".
        let no_evidence = ok("n", vec![]);
        let f = failure_of(&[failed("a", rejected), no_evidence]);
        assert_eq!(f.kind, S::QuotaUnknown);
        assert_eq!(f.login_labels(), vec!["a"]);

        // Refresh lock contention and local refresh failures are transient.
        for kind in [
            K::RefreshLockBusy,
            K::RefreshOther,
            K::UsageTimeout,
            K::UsageTransport,
        ] {
            let f = failure_of(&[failed("a", ObservationFailure::new(kind))]);
            assert_eq!(f.kind, S::UsageReadFailed, "{kind}");
        }
        // Not transient and not a login problem: their own kind (r2
        // blocker 2), never quota_unknown.
        for kind in [K::RefreshActionRequired, K::CredentialStore] {
            let f = failure_of(&[failed("a", ObservationFailure::new(kind))]);
            assert_eq!(f.kind, S::ActionRequired, "{kind}");
            assert!(f.login_labels().is_empty(), "{kind}");
        }
        let f = failure_of(&[failed("a", ObservationFailure::new(K::UsageMalformed))]);
        assert_eq!(f.kind, S::QuotaUnknown);
        assert!(f.login_labels().is_empty());
        // A past reset is never reported.
        let stale_exhausted = ok("y", vec![win("primary", 5 * HOUR, 100.0, NOW - 1)]);
        assert_eq!(failure_of(&[stale_exhausted]).earliest_reset_ms, None);
    }
    /// A duplicate-seat slot is excluded before its cooldown is checked, so
    /// it must not count as a live account: one exhausted seat plus its
    /// excluded duplicate is `all_cooling_down` with the seat's reset, not
    /// `quota_unknown` ("send again to retry").
    #[test]
    fn an_excluded_duplicate_seat_does_not_pick_the_headline() {
        use AccountFailureKind as K;
        let reset = NOW + 2 * HOUR;
        let spent = ok("claude1", vec![win("primary", 5 * HOUR, 100.0, reset)]);
        let dup = ok("claude1-dup", vec![win("primary", 5 * HOUR, 100.0, reset)]);
        let exclude = [cred("claude1-dup")];
        let request = SelectionRequest {
            exclude: &exclude,
            ..req()
        };
        let f = match select(&request, &[spent, dup]) {
            Selection::NoCapacity { rejections, .. } => {
                SelectionFailure::from_rejections(&rejections, NOW)
            }
            other => panic!("expected no capacity, got {other:?}"),
        };
        assert_eq!(f.kind, SelectionFailureKind::AllCoolingDown, "{f:?}");
        assert_eq!(f.earliest_reset_ms, Some(reset));
        assert_eq!(f.accounts[1].kind, K::Excluded);

        // Same with a cooling seat and a transient read failure on the dup.
        let mut cooling = ok("a", vec![win("primary", 5 * HOUR, 10.0, NOW + DAY)]);
        cooling.cooldown_until_ms = Some(NOW + HOUR);
        let dup = failed("b", ObservationFailure::new(K::UsageRateLimited));
        let exclude = [cred("b")];
        let request = SelectionRequest {
            exclude: &exclude,
            ..req()
        };
        let f = match select(&request, &[cooling, dup]) {
            Selection::NoCapacity { rejections, .. } => {
                SelectionFailure::from_rejections(&rejections, NOW)
            }
            other => panic!("expected no capacity, got {other:?}"),
        };
        assert_eq!(f.kind, SelectionFailureKind::AllCoolingDown, "{f:?}");
        assert_eq!(f.earliest_reset_ms, Some(NOW + HOUR));

        // Every account excluded and none limited: nothing proves a limit
        // or a login problem, so the headline stays `quota_unknown`.
        let only = ok("x", vec![win("primary", 5 * HOUR, 10.0, NOW + DAY)]);
        let exclude = [cred("x")];
        let request = SelectionRequest {
            exclude: &exclude,
            ..req()
        };
        let f = match select(&request, &[only]) {
            Selection::NoCapacity { rejections, .. } => {
                SelectionFailure::from_rejections(&rejections, NOW)
            }
            other => panic!("expected no capacity, got {other:?}"),
        };
        assert_eq!(f.kind, SelectionFailureKind::QuotaUnknown, "{f:?}");
    }
}