omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
//! Stage routing for `omni-dev ai jev route` (#1779, #1820).
//!
//! Asks Jev, in one `system_one` call per issue, which model class should do
//! each stage of the work — **design**, **implement** and **review** — and
//! derives the issue's overall class as the higher of design and implement.
//! The three questions are asked once per requested [`Ladder`] (one per AI
//! provider), keyed `<provider>.stage_<stage>`, all in that same single call.
//!
//! Everything here consumes only the provider-neutral [`IssueDoc`], so a
//! GitLab fetcher slots in without touching it. The question wording, the
//! `anthropic` tier descriptions and the input format are the ones validated
//! against `jev-1.13.0` in #1779; see `docs/jev.md` for the evidence and its
//! limits.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use anyhow::{bail, Context, Result};
use clap::ValueEnum;
use serde::{Deserialize, Serialize};
use tracing::warn;

use crate::jev::citations::{find_citation_mentions, Citation};
use crate::jev::client::JevClient;
use crate::jev::error::is_auth_failure;
use crate::jev::input::truncate_middle;
use crate::jev::markdown_code::mask_code;
use crate::jev::protocol::{Answer, Question, SystemOneRequest, Usage};
use crate::provider::{IssueDoc, ItemRef, ItemState};

pub use crate::jev::input::TRUNCATION_MARKER;

pub mod effort;

/// The three stage questions, each missing its per-tier criteria.
const STAGE_QUESTIONS_YAML: &str = include_str!("../templates/jev-route-questions.yaml");

/// The design-stage option meaning "no design work remains". Reserved: no
/// tier may use this name.
pub const NO_DESIGN: &str = "none";

/// An AI provider with an embedded model ladder (#1820).
///
/// Each variant's ladder lives in `src/templates/jev-route-tiers-<name>.yaml`,
/// least capable first, named by the abbreviated model name so the consumer
/// gets a model to hand the work to rather than a rung to translate. Only
/// `anthropic`'s text was validated against Jev (#1779); the other ladders
/// reuse its descriptions rung for rung, differing only in the tier names
/// Jev sees as criterion keys. `anthropic` has two rungs (#1903 dropped
/// `fable` as redundant with `opus`); `openai`/`gemini` still have three.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Provider {
    /// `sonnet` / `opus`.
    #[value(name = "anthropic")]
    Anthropic,
    /// `terra` / `sol` / `astra` (gpt-5.6-terra / gpt-5.6-sol / gpt-6-astra).
    #[value(name = "openai")]
    OpenAi,
    /// `flash` / `pro` / `deep-think` (gemini-3-flash-preview /
    /// gemini-3.1-pro-preview / Gemini 3 Deep Think).
    #[value(name = "gemini")]
    Gemini,
}

impl Provider {
    /// Every provider, in the order the docs list them.
    pub const ALL: [Self; 3] = [Self::Anthropic, Self::OpenAi, Self::Gemini];

    /// The provider's name: its clap value, its output key and its question
    /// key prefix.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Anthropic => "anthropic",
            Self::OpenAi => "openai",
            Self::Gemini => "gemini",
        }
    }

    /// The provider's embedded ladder file.
    const fn tiers_yaml(self) -> &'static str {
        match self {
            Self::Anthropic => include_str!("../templates/jev-route-tiers-anthropic.yaml"),
            Self::OpenAi => include_str!("../templates/jev-route-tiers-openai.yaml"),
            Self::Gemini => include_str!("../templates/jev-route-tiers-gemini.yaml"),
        }
    }

    /// The provider's embedded ladder, parsed and validated.
    pub fn tiers(self) -> Result<Tiers> {
        Tiers::parse(self.tiers_yaml())
            .with_context(|| format!("Invalid embedded tiers for provider {}", self.name()))
    }
}

/// Default confidence below which a stage is reported as a close call. A
/// working heuristic from the #1779 backlog run, not a validated threshold.
pub const DEFAULT_CLOSE_CALL: f64 = 0.3;

/// Default top-two probability margin below which a model-class stage is a
/// close call. A configurable working heuristic, not a calibrated threshold.
pub const DEFAULT_CLOSE_CALL_MARGIN: f64 = 0.2;

/// Default cap, in characters, on the issue text sent to Jev. Jev's input
/// limit is undocumented; the longest input tested was about 48k characters.
pub const DEFAULT_MAX_INPUT_CHARS: usize = 60_000;

/// Fewest tiers a tiers file may define — routing between one class is not
/// a judgment.
const MIN_TIERS: usize = 2;

/// The open citations found in each routed issue's own text (#1812).
///
/// Keyed by the citing issue's `(project, number)`. Built by the CLI's
/// blocking `gh` fetch (`fetch_docs`) — [`run_route`] only reads it, so it
/// stays free of GitHub-specific I/O.
pub type OpenDependencies = BTreeMap<(String, u64), Vec<Citation>>;

/// Citations whose individual GitHub lookup did not resolve.
///
/// Keyed by the citing issue's `(project, number)`, like
/// [`OpenDependencies`]. These are retained in route output so a typo or
/// stale reference is visible rather than being mistaken for no citation.
pub type ReferenceFetchFailures = BTreeMap<(String, u64), Vec<ReferenceFetchFailure>>;

/// A citation GitHub could not fetch while preparing a route.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ReferenceFetchFailure {
    /// The citation exactly as written in the issue text.
    #[serde(rename = "ref")]
    pub item_ref: String,
    /// Why the reference could not be fetched.
    pub error: String,
}

/// One stage of the work on an issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Stage {
    /// Choosing the approach, settling open questions, writing a plan.
    Design,
    /// Writing the code, tests and docs.
    Implement,
    /// Reviewing the finished change before merge.
    Review,
}

impl Stage {
    /// Every stage, in the order they happen.
    const ALL: [Self; 3] = [Self::Design, Self::Implement, Self::Review];

    /// The key of this stage's question in the embedded questions file.
    const fn template_key(self) -> &'static str {
        match self {
            Self::Design => "stage_design",
            Self::Implement => "stage_implement",
            Self::Review => "stage_review",
        }
    }

    /// The key of this stage's question for `provider` in the Jev request
    /// and response, e.g. `anthropic.stage_design`.
    fn question_key(self, provider: &str) -> String {
        format!("{provider}.{}", self.template_key())
    }
}

/// One model class a stage can be routed to.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Tier {
    /// The option name Jev picks, e.g. `sonnet`.
    pub name: String,
    /// What this class is reliable at, shown to Jev as the option's criterion.
    pub description: String,
    /// Concrete downstream models and their effort capabilities; absent for legacy ladders.
    pub models: Option<Vec<effort::Model>>,
}

/// The on-disk shape of a tiers file.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TiersFile {
    tiers: Vec<Tier>,
}

/// An ordered list of [`Tier`]s, from least to most capable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tiers(Vec<Tier>);

impl Tiers {
    /// Parses and validates a tiers file: at least two tiers, non-empty
    /// unique names and descriptions, and no tier named [`NO_DESIGN`].
    pub fn parse(yaml: &str) -> Result<Self> {
        let file: TiersFile = serde_yaml::from_str(yaml).context("Failed to parse tiers file")?;
        if file.tiers.len() < MIN_TIERS {
            bail!(
                "a tiers file needs at least {MIN_TIERS} tiers, got {}",
                file.tiers.len()
            );
        }
        let mut seen = BTreeSet::new();
        for tier in &file.tiers {
            if tier.name.trim().is_empty() || tier.description.trim().is_empty() {
                bail!("every tier needs a non-empty name and description");
            }
            if tier.name == NO_DESIGN {
                bail!("the tier name {NO_DESIGN:?} is reserved for \"no design work remains\"");
            }
            if !seen.insert(tier.name.as_str()) {
                bail!("tier {:?} is defined more than once", tier.name);
            }
        }
        let mut model_rungs = BTreeMap::new();
        for tier in &file.tiers {
            if let Some(models) = &tier.models {
                effort::validate(models).with_context(|| format!("rung {:?}", tier.name))?;
                for model in models {
                    for &stage in &model.stages {
                        if let Some(previous) = model_rungs.insert((&model.name, stage), &tier.name)
                        {
                            bail!(
                                "model {:?} is bound to both rungs {previous:?} and {:?} for {stage:?}",
                                model.name,
                                tier.name
                            );
                        }
                    }
                }
            }
        }
        Ok(Self(file.tiers))
    }

    /// Loads a custom tiers file.
    pub fn load_file(path: &Path) -> Result<Self> {
        let yaml = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read tiers file {}", path.display()))?;
        Self::parse(&yaml).with_context(|| format!("Invalid tiers file {}", path.display()))
    }

    /// The tiers, least capable first.
    #[must_use]
    pub fn as_slice(&self) -> &[Tier] {
        &self.0
    }

    /// The rank of `choice` on the scale `none` (0) < first tier (1) < … —
    /// `None` if `choice` is neither [`NO_DESIGN`] nor a tier.
    fn rank(&self, choice: &str) -> Option<usize> {
        if choice == NO_DESIGN {
            return Some(0);
        }
        self.0.iter().position(|t| t.name == choice).map(|i| i + 1)
    }
}

/// One model ladder (#1820, #1826).
///
/// The name its answers are reported under and the tiers Jev chooses
/// between. A ladder is either a built-in provider's embedded ladder or a
/// custom one registered under its own name via `--ladder-definition`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ladder {
    /// The ladder's name: the output key and the question-key prefix.
    pub name: String,
    /// The tiers, least capable first.
    pub tiers: Tiers,
}

impl Ladder {
    /// A built-in provider's embedded ladder, named after the provider.
    pub fn builtin(provider: Provider) -> Result<Self> {
        Ok(Self {
            name: provider.name().to_string(),
            tiers: provider.tiers()?,
        })
    }

    /// A custom ladder registered under `name` (#1826).
    #[must_use]
    pub fn named(name: String, tiers: Tiers) -> Self {
        Self { name, tiers }
    }
}

/// Builds class and per-model effort questions for every ladder.
///
/// Class questions use the embedded wording with one criterion per tier,
/// keyed `<provider>.stage_<stage>`. All questions share one request. The
/// route command uses a class-only subset unless effort advice is requested.
pub fn build_route_questions(ladders: &[Ladder]) -> Result<BTreeMap<String, Question>> {
    build_route_questions_for_mode(ladders, true)
}

/// [`build_route_questions`] with effort advice chosen explicitly: `route`
/// calls this with `--effort-advice`, so `false` is its default request.
///
/// Public so an evaluation harness builds the same request `route` sends.
pub fn build_route_questions_for_mode(
    ladders: &[Ladder],
    effort_advice: bool,
) -> Result<BTreeMap<String, Question>> {
    let templates: BTreeMap<String, Question> = serde_yaml::from_str(STAGE_QUESTIONS_YAML)
        .context("Failed to parse the embedded stage questions")?;
    for stage in Stage::ALL {
        if !templates.contains_key(stage.template_key()) {
            bail!(
                "the embedded stage questions have no {:?}",
                // omni-dev: coverage ignore-line reason="defensive: the embedded questions YAML always has all three stage keys, pinned by stage_questions_are_the_tested_wording"
                stage.template_key()
            );
        }
    }
    let mut questions = BTreeMap::from([("open_questions".to_string(), open_questions_question())]);
    for ladder in ladders {
        for (key, template) in &templates {
            let mut question = template.clone();
            let Question::Choice { criteria, .. } = &mut question else {
                // omni-dev: coverage ignore-line reason="defensive: every embedded stage question is a choice question, pinned by stage_questions_are_the_tested_wording"
                bail!("embedded stage question {key:?} is not a choice question");
            };
            for tier in ladder.tiers.as_slice() {
                if criteria
                    .insert(tier.name.clone(), tier.description.clone())
                    .is_some()
                {
                    // omni-dev: coverage ignore-line reason="defensive: no embedded or custom tier is ever named `none`, the one fixed criterion (stage_design's no-design-work option)"
                    bail!(
                        "tier {:?} of ladder {:?} collides with a fixed option of {key:?}",
                        tier.name,
                        ladder.name
                    );
                }
            }
            question
                .validate()
                .with_context(|| format!("stage question {key:?} for {:?}", ladder.name))?;
            questions.insert(format!("{}.{key}", ladder.name), question);
        }
    }
    if effort_advice {
        for ladder in ladders {
            effort::add_questions(ladder, &mut questions);
        }
    }
    Ok(questions)
}

/// Builds the text Jev judges for one issue: its title, body and human
/// comments. Returns the text and whether it was truncated.
///
/// Text over `max_chars` keeps its first and last halves with a
/// [`TRUNCATION_MARKER`] between them, rather than losing its end: the end
/// holds the latest comments, and a decision comment there is what moves the
/// design stage most (#1779). No validated input reached the cap, so this
/// policy itself is untested against Jev.
///
/// The layout is the input format validated in #1779 (condition C1), not the
/// slightly different format the issue body first proposed. The one
/// difference from the evaluation script is that bot comments are dropped
/// upstream, as the issue asks; the script kept them. Referenced issues and
/// pull requests are deliberately **not** included: they cost about twice the
/// tokens and inflate small issues.
#[must_use]
pub fn build_route_state(doc: &IssueDoc, max_chars: usize) -> (String, bool) {
    build_route_state_with_drafts(doc, max_chars, &[])
}

/// The text `route` scans for `depends_on` citations (#2003): exactly
/// [`build_route_state`]'s text with the code in the title, body and each
/// comment masked by [`mask_code`].
///
/// Each part is masked on its own, so an unclosed fence or a stray backtick
/// in one comment cannot pair with markup in another and hide the citations
/// between them. Masking replaces characters one for one, so the truncation
/// lands in the same place and the scan sees the same text Jev does, minus
/// its code. Not sent to Jev.
#[must_use]
pub fn build_route_citation_text(doc: &IssueDoc, max_chars: usize) -> String {
    build_route_citation_text_with_drafts(doc, max_chars, &[])
}

/// Builds routing input with local drafts appended after fetched comments.
#[must_use]
pub fn build_route_state_with_drafts(
    doc: &IssueDoc,
    max_chars: usize,
    drafts: &[String],
) -> (String, bool) {
    assemble_route_state(doc, max_chars, drafts, str::to_string)
}

/// Builds the same retained input with code masked separately in each draft.
#[must_use]
pub fn build_route_citation_text_with_drafts(
    doc: &IssueDoc,
    max_chars: usize,
    drafts: &[String],
) -> String {
    assemble_route_state(doc, max_chars, drafts, mask_code).0
}

/// Lays out [`build_route_state`]'s text, passing the title, body and each
/// comment body through `prose` first.
fn assemble_route_state(
    doc: &IssueDoc,
    max_chars: usize,
    drafts: &[String],
    prose: impl Fn(&str) -> String,
) -> (String, bool) {
    let mut text = format!(
        "# #{} {}\n\n{}\n",
        doc.number,
        prose(&doc.title),
        prose(doc.body.trim())
    );
    if !doc.comments.is_empty() || !drafts.is_empty() {
        text.push_str("\n\n---\n\n## Comments on this issue\n");
        for comment in &doc.comments {
            text.push_str(&format!(
                "\n\n**Comment by {}:**\n\n{}\n",
                comment.author,
                prose(comment.body.trim())
            ));
        }
    }
    for draft in drafts {
        text.push_str(&format!(
            "\n\n**Comment by draft:**\n\n{}\n",
            prose(draft.trim())
        ));
    }
    truncate_middle(&text, max_chars)
}

/// Jev's answer for one stage.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct StageAnswer {
    /// The chosen tier, or [`NO_DESIGN`] for the design stage.
    pub choice: String,
    /// Jev's confidence in `choice`.
    pub confidence: f64,
    /// The probability of every option offered.
    pub probabilities: BTreeMap<String, f64>,
    /// Effort advice for every rung and its concrete models, independent of the selected rung.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub effort_by_model: BTreeMap<String, Vec<effort::ModelEffort>>,
}

/// The answers for all three stages of one issue.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct StageAnswers {
    /// Who should do the remaining design work, if any.
    pub design: StageAnswer,
    /// Who should write the code, tests and docs.
    pub implement: StageAnswer,
    /// Who should review the finished change.
    pub review: StageAnswer,
}

impl StageAnswers {
    fn get(&self, stage: Stage) -> &StageAnswer {
        match stage {
            Stage::Design => &self.design,
            Stage::Implement => &self.implement,
            Stage::Review => &self.review,
        }
    }
}

/// One open issue/PR a routed issue's text cites, and whether resolving it
/// would plausibly reduce the remaining work (#1812).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DependencyEntry {
    /// The citation exactly as written, e.g. `"#1129"` or `"PR #1629"` — not
    /// a reconstructed `owner/repo#N`, since the raw text already carries
    /// whatever form the issue used.
    #[serde(rename = "ref")]
    pub item_ref: String,
    /// Resolved GitHub URL for terminal links; not part of the data format.
    #[serde(skip)]
    pub url: Option<String>,
    /// Always [`ItemState::Open`]: a closed citation is settled and is not
    /// reported here.
    pub state: ItemState,
    /// The citing text's explicit relation to this open reference. An
    /// unspecified relation does not imply that the citation is irrelevant.
    pub relation: CitationRelation,
    /// The probability, per stage, that resolving this citation would leave
    /// less of that stage's work remaining than the text implies. Only
    /// `"design"` is populated. An implementation-worded twin scored within
    /// 0.05 of it on every one of 15 cited issues, so it is not asked
    /// separately (see #1812 and the #1871 round-4 evaluation).
    pub could_be_cheaper: BTreeMap<String, f64>,
}

/// What the issue's own wording establishes about an open citation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CitationRelation {
    /// The cited work is explicitly named as a prerequisite.
    Blocker,
    /// The citation is explicitly named as a parent or tracking issue.
    Tracker,
    /// The text has no unambiguous relation phrase.
    Unspecified,
}

/// The routing result for one issue.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct IssueRoute {
    /// Local draft source paths, as supplied to the CLI, for preview provenance.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub draft_comments: Vec<std::path::PathBuf>,
    /// The issue, as `owner/repo#N`.
    #[serde(rename = "ref")]
    pub item_ref: String,
    /// The issue's web URL.
    pub url: String,
    /// The issue title.
    pub title: String,
    /// The issue's own open/closed state on GitHub — distinct from
    /// `depends_on`'s `state`, which is always [`ItemState::Open`] and
    /// describes a *citation*, not this issue.
    pub state: ItemState,
    /// The routing, or why this issue could not be routed.
    #[serde(flatten)]
    pub outcome: RouteOutcome,
    /// Whether the issue text was cut at the input cap.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub truncated: bool,
}

/// The stage whose choice supplied an issue's class (#2051).
///
/// Review never supplies it, and neither does design `none`, so there are
/// only two sources.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ClassSource {
    /// Design chose a strictly higher tier than implement.
    Design,
    /// Implement chose the class; design chose the same tier or a lower one.
    Implement,
}

impl ClassSource {
    /// The stage name as shown in text output, e.g. `design`.
    const fn label(self) -> &'static str {
        match self {
            Self::Design => "design",
            Self::Implement => "implementation",
        }
    }
}

/// One provider's routing of an issue (#1820).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ProviderRoute {
    /// Jev's answer per stage.
    pub stages: StageAnswers,
    /// The issue's class: the higher of the design and implement choices.
    pub class: String,
    /// Which stage supplied `class`. A tie goes to `implement`, so `design`
    /// means design alone raised the class above what implementation chose.
    pub class_from: ClassSource,
    /// Stages below the confidence threshold or top-two model-class probability margin.
    pub close_calls: Vec<Stage>,
}

/// The kind of unresolved questions in an issue, independent of routing tiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenQuestionKind {
    /// The text settles the approach and questions.
    None,
    /// Reading existing code can settle the questions.
    Factual,
    /// Choosing between alternatives requires judgment.
    Design,
    /// Both factual and design questions remain.
    Both,
}

impl OpenQuestionKind {
    fn label(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Factual => "factual",
            Self::Design => "design",
            Self::Both => "both",
        }
    }

    fn parse(label: &str) -> Result<Self> {
        match label {
            "none" => Ok(Self::None),
            "factual" => Ok(Self::Factual),
            "design" => Ok(Self::Design),
            "both" => Ok(Self::Both),
            _ => bail!("open_questions label {label:?} was not offered"),
        }
    }
}

/// Jev's independent assessment of the issue's remaining questions.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct OpenQuestions {
    /// Which kind of questions remains.
    pub choice: OpenQuestionKind,
    /// Jev's confidence in the chosen kind.
    pub confidence: f64,
    /// Probability of each offered label.
    pub probabilities: BTreeMap<String, f64>,
}

fn open_questions_question() -> Question {
    Question::Choice {
        instructions: "What kind of questions is still open in the issue after considering all \
                comments? Unknown existing-code facts and genuine design tradeoffs are different \
                kinds. A suggested fix direction does not settle unverified factual premises, \
                such as whether a reusable helper already exists. A code-informed decision with \
                a concrete plan does settle them: carrying out its prescribed caller audits, \
                code edits, tests, or verification is execution work, not an open question. \
                Routine coding choices do not count as design tradeoffs. Judge the remaining \
                uncertainty, not the amount of work."
            .to_string(),
        criteria: BTreeMap::from([
            (
                "none".to_string(),
                "The latest text establishes the relevant existing-code facts and prescribes the \
                approach. Executing its specified plan, including audits and verification, does \
                not itself create open questions."
                    .to_string(),
            ),
            (
                "factual".to_string(),
                "Only existing-code facts remain unsettled: whether a reusable helper exists, \
                what it does, or which existing sites need changes. A suggested fix with \
                uncertain reuse or scope is factual even if its intended behavior is clear; \
                inspecting code can settle it without a discretionary design tradeoff."
                    .to_string(),
            ),
            (
                "design".to_string(),
                "Only genuine choices between competing approaches remain, requiring judgment \
                about behavior, architecture, or tradeoffs even after existing-code facts are \
                known. Routine choices while implementing a prescribed fix do not qualify."
                    .to_string(),
            ),
            (
                "both".to_string(),
                "Both unresolved existing-code premises and genuine choices between competing \
                designs remain. Code reading alone cannot settle the design tradeoffs."
                    .to_string(),
            ),
        ]),
    }
}

fn open_questions_answer(answers: &BTreeMap<String, Answer>) -> Result<OpenQuestions> {
    let Some(Answer::Choice {
        choice,
        confidence,
        probabilities,
    }) = answers.get("open_questions")
    else {
        bail!("no choice answer for open_questions");
    };
    let choice = OpenQuestionKind::parse(choice)?;
    for label in probabilities.keys() {
        OpenQuestionKind::parse(label)?;
    }
    Ok(OpenQuestions {
        choice,
        confidence: *confidence,
        probabilities: probabilities.clone(),
    })
}

/// What routing one issue produced.
///
/// Serialised untagged and flattened into [`IssueRoute`], so a routed issue
/// carries `providers`/`depends_on` and a failed one carries `error` and any
/// citation fetch failures.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(untagged)]
pub enum RouteOutcome {
    /// Jev answered every stage for every ladder.
    Routed {
        /// Independent issue-level question kind; never changes the class.
        /// Absent when Jev returned no usable answer to this experimental
        /// question: it is advisory, so that never fails the routing.
        #[serde(skip_serializing_if = "Option::is_none")]
        open_questions: Option<OpenQuestions>,
        /// Each requested ladder's routing, keyed by provider name.
        providers: BTreeMap<String, ProviderRoute>,
        /// Open issues/PRs this issue's text cites (#1812). About the issue,
        /// not a provider, so it sits beside `providers` rather than inside.
        depends_on: Vec<DependencyEntry>,
        /// Citations that could not be fetched. They are not dependencies
        /// because their state is unknown, but remain visible to the user.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        reference_fetch_failures: Vec<ReferenceFetchFailure>,
    },
    /// The Jev call for this issue failed, or its answer was unusable. The
    /// other issues are still routed, so a long run keeps what it paid for.
    Failed {
        /// The error chain, on one line.
        error: String,
        /// Citations that could not be fetched before the Jev call failed.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        reference_fetch_failures: Vec<ReferenceFetchFailure>,
    },
}

impl IssueRoute {
    /// Whether this issue failed to route.
    #[must_use]
    pub fn failed(&self) -> bool {
        matches!(self.outcome, RouteOutcome::Failed { .. })
    }
}

/// The routing result for every issue.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RouteReport {
    /// The Jev model that answered (comma-separated in the unlikely case the
    /// alias moved mid-run).
    pub model: String,
    /// One entry per routed issue, in the order requested.
    pub issues: Vec<IssueRoute>,
    /// Closed issues dropped from the batch by
    /// [`RouteOptions::ignore_closed`], in the order requested (#2000).
    /// Omitted when empty, so a run that skipped nothing serialises as before.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ignored_closed: Vec<IgnoredIssue>,
    /// Token usage summed over every Jev call.
    pub usage: Usage,
}

/// A closed issue [`RouteOptions::ignore_closed`] dropped from the batch
/// without routing it (#2000).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IgnoredIssue {
    /// The issue, as `owner/repo#N`.
    #[serde(rename = "ref")]
    pub item_ref: String,
    /// The issue's web URL.
    pub url: String,
    /// The issue title.
    pub title: String,
}

/// Knobs for [`run_route`].
#[derive(Debug, Clone)]
pub struct RouteOptions {
    /// Local comments appended after fetched comments, in supplied order.
    pub draft_comments: Vec<String>,
    /// The Jev model to request.
    pub model: String,
    /// Confidence below which a stage is a close call.
    pub close_call: f64,
    /// Top-two model-class probability margin below which a stage is a close call.
    /// Zero disables margin flagging; effort advice uses only `close_call`.
    pub close_call_margin: f64,
    /// Ask for per-model effort advice as well as class routing.
    pub effort_advice: bool,
    /// Cap, in characters, on each issue's text.
    pub max_input_chars: usize,
    /// Route closed issues instead of refusing them.
    pub allow_closed: bool,
    /// Drop closed issues from the batch instead of refusing them, listing
    /// them under [`RouteReport::ignored_closed`] (#2000). Mutually
    /// exclusive with [`RouteOptions::allow_closed`].
    pub ignore_closed: bool,
}

/// Routes every issue in `docs`, one Jev call each, in order.
///
/// Every ladder in `ladders` is routed in that same call: Jev takes a map of
/// questions over one state, so the three stage questions are keyed per
/// provider and share the issue text (#1820). One independent `open_questions`
/// choice is shared across all providers. It never changes class derivation, and
/// an unusable answer to it is dropped with a warning rather than failing the issue.
///
/// Refuses closed issues unless [`RouteOptions::allow_closed`]: their comments
/// often describe how the work was actually done, which leaks the answer.
/// With [`RouteOptions::ignore_closed`] they are instead dropped before any
/// request is sent and listed under [`RouteReport::ignored_closed`]; a batch
/// with no open issue left is still an error.
///
/// `dependencies` is each issue's open citations (#1812), keyed by `(project,
/// number)` — pre-resolved by the caller's `gh` fetch, since this function
/// only ever talks to Jev. An issue with no entry (or an empty one) gets an
/// empty `depends_on` and no extra questions.
///
/// A failure on one issue is recorded on that issue as
/// [`RouteOutcome::Failed`] and the run continues, so a transient error late
/// in a long `--all-open` run does not discard the answers already paid for.
/// The exception is an authentication failure (HTTP 401/403), which would
/// fail every remaining issue the same way and so ends the run.
pub async fn run_route(
    jev: &JevClient,
    docs: &[IssueDoc],
    ladders: &[Ladder],
    opts: &RouteOptions,
    dependencies: &OpenDependencies,
) -> Result<RouteReport> {
    run_route_with_reference_fetch_failures(
        jev,
        docs,
        ladders,
        opts,
        dependencies,
        &ReferenceFetchFailures::new(),
    )
    .await
}

/// Like [`run_route`], while retaining per-citation fetch failures in the
/// report. The CLI supplies this data after its blocking GitHub fetch.
pub async fn run_route_with_reference_fetch_failures(
    jev: &JevClient,
    docs: &[IssueDoc],
    ladders: &[Ladder],
    opts: &RouteOptions,
    dependencies: &OpenDependencies,
    reference_fetch_failures: &ReferenceFetchFailures,
) -> Result<RouteReport> {
    if !opts.draft_comments.is_empty() && docs.len() != 1 {
        bail!("draft comments apply to exactly one issue; cannot preview a batch");
    }
    let (docs, ignored_closed) = drop_closed(docs, opts)?;
    validate_options(&docs, ladders, opts)?;
    let questions = build_route_questions_for_mode(ladders, opts.effort_advice)?;
    // A custom ladder can hold any number of tiers, so check its questions
    // against the caps of the model that will be asked, naming the question.
    for (key, question) in &questions {
        question
            .validate_for_model(&opts.model)
            .with_context(|| format!("route question {key:?}"))?;
    }

    let mut models = BTreeSet::new();
    let mut usage = Usage::default();
    let mut issues = Vec::with_capacity(docs.len());
    for doc in docs {
        let item_ref = item_ref(doc);
        let (state, truncated) =
            build_route_state_with_drafts(doc, opts.max_input_chars, &opts.draft_comments);
        if truncated {
            warn!(
                "Issue {item_ref} is longer than {} characters; its input was truncated",
                opts.max_input_chars
            );
        }
        let citations = dependencies
            .get(&(doc.project.clone(), doc.number))
            .map_or(&[][..], Vec::as_slice);
        let relations = citation_relations(&state, doc);
        let citation_failures = reference_fetch_failures
            .get(&(doc.project.clone(), doc.number))
            .cloned()
            .unwrap_or_default();
        let mut request_questions = questions.clone();
        for (i, citation) in citations.iter().enumerate() {
            request_questions.insert(
                could_be_cheaper_key(i),
                could_be_cheaper_question(&citation.raw),
            );
        }
        let request = SystemOneRequest {
            state: serde_json::Value::String(state),
            model: opts.model.clone(),
            questions: request_questions,
        };
        let outcome = match jev.system_one(&request).await {
            Err(err) if is_auth_failure(&err) => {
                return Err(err).with_context(|| format!("Failed to route issue {item_ref}"));
            }
            Err(err) => failed(
                &item_ref,
                &err.context("Jev request failed"),
                &citation_failures,
            ),
            Ok(response) => {
                models.insert(response.model);
                usage.input_tokens += response.usage.input_tokens;
                usage.output_tokens += response.usage.output_tokens;
                match provider_routes(
                    &response.answers,
                    ladders,
                    opts.close_call,
                    opts.close_call_margin,
                    opts.effort_advice,
                ) {
                    Ok(providers) => RouteOutcome::Routed {
                        // Experimental and advisory (held-out agreement is no better
                        // than always answering `factual`): losing it must not discard
                        // the validated stage answers Jev gave in the same response.
                        open_questions: open_questions_answer(&response.answers)
                            .map_err(|err| {
                                warn!(
                                    "Ignoring open_questions for {item_ref}: {err:#}; \
                                     routing is unaffected"
                                );
                            })
                            .ok(),
                        providers,
                        depends_on: dependency_entries(
                            &item_ref,
                            citations,
                            &relations,
                            &response.answers,
                        ),
                        reference_fetch_failures: citation_failures.clone(),
                    },
                    Err(err) => failed(
                        &item_ref,
                        &err.context("Unexpected Jev answer"),
                        &citation_failures,
                    ),
                }
            }
        };
        issues.push(IssueRoute {
            draft_comments: vec![],
            item_ref,
            url: doc.url.clone(),
            title: doc.title.clone(),
            state: doc.state,
            outcome,
            truncated,
        });
    }

    Ok(RouteReport {
        model: models.into_iter().collect::<Vec<_>>().join(", "),
        issues,
        ignored_closed,
        usage,
    })
}

/// Whether `--ignore-closed` drops `doc` from the batch. Shared with the
/// CLI, which skips resolving the citations of exactly these issues.
#[must_use]
pub fn is_ignored_closed(doc: &IssueDoc, ignore_closed: bool) -> bool {
    ignore_closed && doc.state == ItemState::Closed
}

/// `doc`'s `owner/repo#N` reference.
fn item_ref(doc: &IssueDoc) -> String {
    format!("{}#{}", doc.project, doc.number)
}

/// Splits off the closed issues [`RouteOptions::ignore_closed`] skips,
/// returning the issues still to route. Without the flag every issue is kept,
/// so [`validate_options`] can refuse the closed ones. Refuses the flag
/// alongside [`RouteOptions::allow_closed`] first, so that conflict is
/// reported whatever the batch holds, then a batch the flag would leave empty, naming what it skipped, rather than letting it
/// surface as the less helpful "no issues to route".
fn drop_closed<'a>(
    docs: &'a [IssueDoc],
    opts: &RouteOptions,
) -> Result<(Vec<&'a IssueDoc>, Vec<IgnoredIssue>)> {
    if opts.allow_closed && opts.ignore_closed {
        bail!("--allow-closed and --ignore-closed cannot be used together");
    }
    let (open, closed): (Vec<&IssueDoc>, Vec<&IssueDoc>) = docs
        .iter()
        .partition(|d| !is_ignored_closed(d, opts.ignore_closed));
    if open.is_empty() && !closed.is_empty() {
        bail!(
            "every requested issue is closed ({}) and --ignore-closed skipped them; nothing to \
             route",
            closed
                .iter()
                .map(|d| item_ref(d))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
    let ignored = closed
        .into_iter()
        .map(|d| IgnoredIssue {
            item_ref: item_ref(d),
            url: d.url.clone(),
            title: d.title.clone(),
        })
        .collect();
    Ok((open, ignored))
}

/// Records `err` as `item_ref`'s outcome, warning so a long run shows it as
/// it happens.
fn failed(
    item_ref: &str,
    err: &anyhow::Error,
    reference_fetch_failures: &[ReferenceFetchFailure],
) -> RouteOutcome {
    let error = format!("{err:#}");
    warn!("Could not route issue {item_ref}: {error}");
    RouteOutcome::Failed {
        error,
        reference_fetch_failures: reference_fetch_failures.to_vec(),
    }
}

/// Rejects an empty run, an empty or repeated ladder list, out-of-range
/// knobs, and (by default) closed issues, before any paid request is sent.
fn validate_options(docs: &[&IssueDoc], ladders: &[Ladder], opts: &RouteOptions) -> Result<()> {
    if docs.is_empty() {
        bail!("no issues to route");
    }
    if ladders.is_empty() {
        bail!("no ladders to route against");
    }
    let mut seen = BTreeSet::new();
    for ladder in ladders {
        if !seen.insert(ladder.name.as_str()) {
            bail!("ladder {:?} is listed more than once", ladder.name);
        }
    }
    if !(0.0..=1.0).contains(&opts.close_call) {
        bail!(
            "the close-call threshold must be between 0 and 1, got {}",
            opts.close_call
        );
    }
    if !(0.0..=1.0).contains(&opts.close_call_margin) {
        bail!(
            "the close-call margin must be between 0 and 1, got {}",
            opts.close_call_margin
        );
    }
    if opts.max_input_chars == 0 {
        bail!("the input cap must be at least 1 character");
    }
    if !opts.allow_closed {
        let closed: Vec<String> = docs
            .iter()
            .filter(|d| d.state == ItemState::Closed)
            .map(|d| item_ref(d))
            .collect();
        if !closed.is_empty() {
            bail!(
                "refusing to route closed issues ({}): their comments often describe how the \
                 work was done, which leaks the answer. Pass --ignore-closed to skip them, or \
                 --allow-closed to route them anyway",
                closed.join(", ")
            );
        }
    }
    Ok(())
}

/// Reads every ladder's routing out of one response. Any ladder whose
/// answers are missing or malformed fails the whole issue, as a single
/// ladder's did before #1820.
fn provider_routes(
    answers: &BTreeMap<String, Answer>,
    ladders: &[Ladder],
    close_call: f64,
    close_call_margin: f64,
    effort_advice: bool,
) -> Result<BTreeMap<String, ProviderRoute>> {
    ladders
        .iter()
        .map(|ladder| {
            let mut stages = stage_answers(answers, ladder)?;
            if effort_advice {
                for (stage, answer) in [
                    (Stage::Design, &mut stages.design),
                    (Stage::Implement, &mut stages.implement),
                    (Stage::Review, &mut stages.review),
                ] {
                    answer.effort_by_model =
                        effort::decode(ladder, stage, answer, answers, close_call)?;
                }
            }
            let (class, class_from) = issue_class(&stages, &ladder.tiers);
            let route = ProviderRoute {
                class,
                class_from,
                close_calls: close_calls(&stages, &ladder.tiers, close_call, close_call_margin),
                stages,
            };
            Ok((ladder.name.clone(), route))
        })
        .collect()
}

/// Reads one ladder's three stage answers out of a response, checking each
/// is a `choice` naming an option that was offered.
fn stage_answers(answers: &BTreeMap<String, Answer>, ladder: &Ladder) -> Result<StageAnswers> {
    let tiers = &ladder.tiers;
    let read = |stage: Stage| -> Result<StageAnswer> {
        let key = stage.question_key(&ladder.name);
        let Some(Answer::Choice {
            choice,
            confidence,
            probabilities,
        }) = answers.get(&key)
        else {
            bail!("no choice answer for {key:?}");
        };
        let offered = match tiers.rank(choice) {
            Some(0) => stage == Stage::Design,
            Some(_) => true,
            None => false,
        };
        if !offered {
            bail!("{key:?} chose {choice:?}, which was not offered");
        }
        Ok(StageAnswer {
            choice: choice.clone(),
            confidence: *confidence,
            probabilities: probabilities.clone(),
            effort_by_model: BTreeMap::new(),
        })
    };
    Ok(StageAnswers {
        design: read(Stage::Design)?,
        implement: read(Stage::Implement)?,
        review: read(Stage::Review)?,
    })
}

/// The higher of the design and implement choices, and the stage that
/// supplied it. Implement is always a tier, so the result is always a tier,
/// never [`NO_DESIGN`].
///
/// Tie rule (#2051): when both stages choose the same tier, implement
/// supplies it. Design is credited only when it strictly outranks implement,
/// which is the case worth reporting — design alone raised the class.
fn issue_class(stages: &StageAnswers, tiers: &Tiers) -> (String, ClassSource) {
    let rank = |a: &StageAnswer| tiers.rank(&a.choice).unwrap_or_default();
    if rank(&stages.design) > rank(&stages.implement) {
        (stages.design.choice.clone(), ClassSource::Design)
    } else {
        (stages.implement.choice.clone(), ClassSource::Implement)
    }
}

/// The top-two usable probabilities among options offered to this stage.
/// Partial maps are usable with two entries; no normalization or imputation.
fn top_two_margin(answer: &StageAnswer, stage: Stage, tiers: &Tiers) -> Option<f64> {
    let mut usable: Vec<_> = answer
        .probabilities
        .iter()
        .filter(|(name, probability)| {
            probability.is_finite()
                && (0.0..=1.0).contains(*probability)
                && match tiers.rank(name) {
                    Some(0) => stage == Stage::Design,
                    Some(_) => true,
                    None => false,
                }
        })
        .collect();
    usable.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0)));
    let [first, second, ..] = usable.as_slice() else {
        return None;
    };
    Some(first.1 - second.1)
}

/// Flag confidence or top-two margin below its threshold, in stage order.
/// Strict comparisons let a zero margin threshold recover confidence-only behavior.
fn close_calls(stages: &StageAnswers, tiers: &Tiers, threshold: f64, margin: f64) -> Vec<Stage> {
    Stage::ALL
        .into_iter()
        .filter(|&stage| {
            let answer = stages.get(stage);
            answer.confidence < threshold
                || top_two_margin(answer, stage, tiers).is_some_and(|gap| gap < margin)
        })
        .collect()
}

/// The request key for the `i`th open citation's `could_be_cheaper` question.
///
/// Public so an evaluation harness builds the same request `route` sends
/// rather than a copy that can drift.
pub fn could_be_cheaper_key(i: usize) -> String {
    format!("could_be_cheaper_{i}")
}

/// Builds the `could_be_cheaper` question for one open citation (#1812).
///
/// Asked for the design stage only — the exact wording validated live against
/// `jev-1.13.0`, 2026-09-20; see docs/jev.md for the evidence. An
/// implementation-worded twin duplicated its score (r = 0.99 over 15 pairs, #1871)
/// and is not asked. Do not reword without re-validating (pinned by
/// `could_be_cheaper_question_is_the_tested_wording`).
pub fn could_be_cheaper_question(citation: &str) -> Question {
    Question::Noul {
        instructions: format!(
            "This issue cites {citation}, which is still open. If {citation} is resolved, how \
             likely is it that LESS design work would remain for THIS issue than the current \
             text implies — as opposed to this issue's own remaining work being unaffected, \
             because it is already scoped separately, is a parallel/sibling effort, or \
             {citation} is otherwise not a precondition for finishing this issue's own \
             remaining work?"
        ),
        criteria: None,
    }
}

/// Labels only an explicit relation in the citing sentence. Every mention is
/// considered, so a later "blocked on #N" is not lost behind an earlier bare
/// "#N". Conflicting claims and quoted examples remain unspecified.
fn citation_relations(state: &str, doc: &IssueDoc) -> BTreeMap<(String, u64), CitationRelation> {
    let judged = ItemRef {
        provider: doc.provider,
        project: doc.project.clone(),
        kind: doc.kind,
        number: doc.number,
    };
    let mut evidence: BTreeMap<(String, u64), (bool, bool, bool)> = BTreeMap::new();
    for mention in find_citation_mentions(state, &doc.project, &judged) {
        let key = (
            mention.citation.item_ref.project,
            mention.citation.item_ref.number,
        );
        let entry = evidence.entry(key).or_default();
        match relation_at(state, &mention.range) {
            MentionRelation::Blocker => entry.0 = true,
            MentionRelation::Tracker => entry.1 = true,
            MentionRelation::Negated => entry.2 = true,
            MentionRelation::None => {}
        }
    }
    evidence
        .into_iter()
        .map(|(key, (blocker, tracker, negated))| {
            let relation = match (blocker, tracker, negated) {
                (true, false, false) => CitationRelation::Blocker,
                (false, true, false) => CitationRelation::Tracker,
                _ => CitationRelation::Unspecified,
            };
            (key, relation)
        })
        .collect()
}

enum MentionRelation {
    Blocker,
    Tracker,
    Negated,
    None,
}

fn relation_at(state: &str, range: &std::ops::Range<usize>) -> MentionRelation {
    if !state[..range.start]
        .matches("```")
        .count()
        .is_multiple_of(2)
    {
        return MentionRelation::None;
    }
    let before = &state[..range.start];
    let boundary = before.rfind(['.', '!', '?', '\n']).map_or(0, |i| i + 1);
    let sentence = &state[boundary..];
    if sentence.trim_start().starts_with('>') {
        return MentionRelation::None;
    }
    let prefix = &state[boundary..range.start];
    if !prefix.matches('`').count().is_multiple_of(2)
        || !prefix.matches('"').count().is_multiple_of(2)
    {
        return MentionRelation::None;
    }
    let nearby: String = prefix
        .chars()
        .rev()
        .take(160)
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    let nearby = nearby.to_ascii_lowercase();
    let after = &state[range.end..];
    let end = after.find(['.', '!', '?', '\n']).unwrap_or(after.len());
    let following = after[..end].trim_start().to_ascii_lowercase();
    if nearby.contains("such as")
        || nearby.contains("for example")
        || nearby.contains("worked example")
        || nearby.contains("e.g.")
    {
        return MentionRelation::None;
    }
    if nearby.contains("not blocked on")
        || nearby.contains("no longer blocked on")
        || nearby.contains("isn't blocked on")
        || nearby.contains("not dependent on")
        || nearby.contains("unblocked")
        || nearby.contains("not a tracker")
        || nearby.contains("not split out of")
        || following.starts_with("does not block")
        || following.starts_with("no longer blocks")
    {
        return MentionRelation::Negated;
    }
    if following.starts_with("blocks ")
        || following.starts_with("is required for ")
        || following.starts_with("must land before ")
    {
        return MentionRelation::Blocker;
    }
    if nearby.contains("blocked on")
        || nearby.contains("depends on")
        || nearby.contains("requires")
        || nearby.contains("prerequisite")
    {
        return MentionRelation::Blocker;
    }
    if nearby.contains("split out of")
        || nearby.contains("split from")
        || nearby.contains("parent tracker")
        || nearby.contains("tracker checkbox")
    {
        return MentionRelation::Tracker;
    }
    MentionRelation::None
}

/// Builds `depends_on` from `citations` and the Jev response that answered
/// one `could_be_cheaper` question per citation.
///
/// A missing or malformed answer leaves the citation visible with an empty
/// score map. It is logged but does not fail the stage routing.
fn dependency_entries(
    item_ref: &str,
    citations: &[Citation],
    relations: &BTreeMap<(String, u64), CitationRelation>,
    answers: &BTreeMap<String, Answer>,
) -> Vec<DependencyEntry> {
    citations
        .iter()
        .enumerate()
        .map(|(i, citation)| {
            let could_be_cheaper =
                if let Some(Answer::Noul { noul }) = answers.get(&could_be_cheaper_key(i)) {
                    BTreeMap::from([("design".to_string(), *noul)])
                } else {
                    warn!(
                        "Issue {item_ref}: no could_be_cheaper answer for citation {:?}",
                        citation.raw
                    );
                    BTreeMap::new()
                };
            DependencyEntry {
                item_ref: citation.raw.clone(),
                url: citation.url.clone(),
                state: ItemState::Open,
                relation: relations
                    .get(&(citation.item_ref.project.clone(), citation.item_ref.number))
                    .copied()
                    .unwrap_or(CitationRelation::Unspecified),
                could_be_cheaper,
            }
        })
        .collect()
}

/// Renders `report` as one block per issue, blank-line separated, in request
/// order, followed by a trailing model/usage line (#1824).
///
/// Plain text, deliberately with no markdown: it's read directly in a
/// terminal, which doesn't render `**bold**`/`*italic*` markers, so they'd
/// just be clutter. Each issue is a header line (`ref — title`, with a
/// trailing ` (closed)` when the issue itself is closed — relevant here since
/// `--allow-closed` routes them) followed by one indented line per fact — one
/// per provider's routing, then `depends_on` — rather than one run-on
/// sentence, which reads poorly once more than one provider is involved.
/// Closed issues `--ignore-closed` skipped get one `ignored closed:` line
/// before the `model`/`usage` footer.
///
/// `max_input_chars` is threaded in explicitly rather than read off
/// `RouteReport` (which doesn't carry it) so a truncated issue's block can
/// name the actual configured cap. This is still a pure, side-effect-free
/// function of its arguments, unit-tested directly with fixture reports.
///
/// The wording is **not** a stable contract: it may change without notice.
/// Scripts should use `json` or `yaml` instead.
#[must_use]
pub fn render_route_text(report: &RouteReport, max_input_chars: usize) -> String {
    render_route_text_styled(report, max_input_chars, &[], TerminalStyle::default())
}

/// Terminal features selected by the CLI. Passing them explicitly keeps the
/// renderer deterministic and lets callers retain plain output for pipes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TerminalStyle {
    /// Emit SGR colour sequences.
    pub color: bool,
    /// Emit OSC 8 links around issue references.
    pub hyperlinks: bool,
}

impl TerminalStyle {
    /// Disables escape sequences for redirected output and dumb terminals.
    #[must_use]
    pub fn new(tty: bool, term: &str, no_color: bool, supports_links: bool) -> Self {
        let usable = tty && !term.is_empty() && term != "dumb";
        Self {
            color: usable && !no_color,
            hyperlinks: usable && supports_links,
        }
    }
}

/// Renders the human report with terminal presentation when supported.
#[must_use]
pub fn render_route_text_styled(
    report: &RouteReport,
    max_input_chars: usize,
    ladders: &[Ladder],
    style: TerminalStyle,
) -> String {
    let mut blocks: Vec<String> = report
        .issues
        .iter()
        .map(|issue| render_issue_block(issue, max_input_chars, ladders, style))
        .collect();
    if !report.ignored_closed.is_empty() {
        let refs: Vec<String> = report
            .ignored_closed
            .iter()
            .map(|issue| hyperlink(&issue.item_ref, Some(&issue.url), style))
            .collect();
        blocks.push(format!("ignored closed: {}", refs.join(", ")));
    }
    blocks.push(format!(
        "model: {}, usage: {} input tokens, {} output tokens",
        report.model, report.usage.input_tokens, report.usage.output_tokens
    ));
    let mut text = blocks.join("\n\n");
    text.push('\n');
    text
}

/// Renders one issue's block: a header line, one indented line per provider's
/// routing (or its error), one `cites` line per open citation, and a
/// truncation note.
fn render_issue_block(
    issue: &IssueRoute,
    max_input_chars: usize,
    ladders: &[Ladder],
    style: TerminalStyle,
) -> String {
    let item_ref = hyperlink(&issue.item_ref, Some(&issue.url), style);
    let item_ref = if issue.failed() {
        item_ref
    } else {
        colorize(&item_ref, Complexity::Low, style)
    };
    let header = if issue.state == ItemState::Closed {
        format!("{item_ref} — {} (closed)", issue.title)
    } else {
        format!("{item_ref} — {}", issue.title)
    };
    let mut lines = vec![header];
    if !issue.draft_comments.is_empty() {
        lines.push(format!(
            "  draft comments (preview): {:?}",
            issue.draft_comments
        ));
    }
    match &issue.outcome {
        RouteOutcome::Routed {
            providers,
            depends_on,
            reference_fetch_failures,
            open_questions,
        } => {
            if let Some(open_questions) = open_questions {
                lines.push(format!(
                    "  open_questions: {} ({:.2})",
                    open_questions.choice.label(),
                    open_questions.confidence
                ));
            }
            for (provider, route) in providers {
                let ladder = ladders.iter().find(|ladder| ladder.name == *provider);
                lines.extend(render_provider_line(
                    provider,
                    route,
                    providers.len(),
                    ladder,
                    style,
                ));
            }
            lines.extend(render_depends_on_lines(depends_on, style));
            lines.extend(render_reference_fetch_failure_lines(
                reference_fetch_failures,
            ));
        }
        RouteOutcome::Failed {
            error,
            reference_fetch_failures,
        } => {
            lines.push(format!(
                "  {}",
                colorize(&format!("failed: {error}"), Complexity::High, style)
            ));
            lines.extend(render_reference_fetch_failure_lines(
                reference_fetch_failures,
            ));
        }
    }
    if issue.truncated {
        lines.push(format!(
            "  input truncated at {} characters",
            with_thousands(max_input_chars)
        ));
    }
    lines.join("\n")
}

/// Whether any of `route`'s three stage answers names a multi-model tier (a
/// comma-joined tier name from a custom ladder, #1826). The compact
/// single-line layout repeats a chosen tier name up to four times, which
/// becomes unreadable once that name is ~100 characters of comma-joined
/// model ids — so this is the trigger for the one-line-per-stage layout
/// (#1847). Checking the three stage choices is sufficient: `route.class` is
/// always one of `design`/`implement`'s choice (see `issue_class`), so it
/// can never be multi-model without one of those already being caught.
fn route_has_multi_model_tier(route: &ProviderRoute) -> bool {
    [
        &route.stages.design,
        &route.stages.implement,
        &route.stages.review,
    ]
    .into_iter()
    .any(|answer| answer.choice.contains(','))
}

/// Renders one provider's routing as one or more indented lines: the compact
/// single line (unchanged since #1824) when every chosen tier is
/// single-model, or one line per fact when a multi-model tier name would
/// otherwise repeat illegibly on one line (#1847).
fn render_provider_line(
    provider: &str,
    route: &ProviderRoute,
    provider_count: usize,
    ladder: Option<&Ladder>,
    style: TerminalStyle,
) -> Vec<String> {
    let mut lines = if route_has_multi_model_tier(route) {
        render_provider_block(provider, route, provider_count, ladder, style)
    } else {
        vec![render_provider_line_compact(
            provider,
            route,
            provider_count,
            ladder,
            style,
        )]
    };
    lines.extend(effort::render(&route.stages, ladder));
    lines
}

/// Renders one provider's routing as an indented line, e.g. `  opus (from
/// design) — design needs opus (0.52), ...` or, with more than one provider
/// requested, `  anthropic: opus (from design) — design needs opus (0.52),
/// ...`.
fn render_provider_line_compact(
    provider: &str,
    route: &ProviderRoute,
    provider_count: usize,
    ladder: Option<&Ladder>,
    style: TerminalStyle,
) -> String {
    let class = format!(
        "{} (from {})",
        color_choice(&route.class, ladder, style),
        route.class_from.label()
    );
    let lead = if provider_count > 1 {
        format!("{provider}: {class}")
    } else {
        class
    };
    let clauses: Vec<String> = Stage::ALL
        .into_iter()
        .map(|stage| render_stage_clause(stage, &route.stages, &route.close_calls, ladder, style))
        .collect();
    format!("  {lead} — {}", clauses.join(", "))
}

/// Renders one stage's clause, e.g. `design needs opus (0.52)` or `review
/// sonnet (0.41, close call)`.
fn render_stage_clause(
    stage: Stage,
    stages: &StageAnswers,
    close_calls: &[Stage],
    ladder: Option<&Ladder>,
    style: TerminalStyle,
) -> String {
    let answer = stages.get(stage);
    let choice = color_choice(&answer.choice, ladder, style);
    let label = match stage {
        Stage::Design if answer.choice == NO_DESIGN => format!(
            "design needs {}",
            colorize("no further work", Complexity::Low, style)
        ),
        Stage::Design => format!("design needs {choice}"),
        Stage::Implement => format!("implementation {choice}"),
        Stage::Review => format!("review {choice}"),
    };
    format!(
        "{label} ({})",
        render_stage_confidence(answer, close_calls.contains(&stage))
    )
}

/// Adds the highest-probability alternative to a close call in either text
/// layout. Ties pick the alphabetically first option for stable output.
fn render_stage_confidence(answer: &StageAnswer, close_call: bool) -> String {
    let mut detail = format!("{:.2}", answer.confidence);
    if close_call {
        detail.push_str(", close call");
        if let Some((name, probability)) = answer
            .probabilities
            .iter()
            .filter(|(name, probability)| name.as_str() != answer.choice && probability.is_finite())
            .max_by(|a, b| a.1.total_cmp(b.1).then_with(|| b.0.cmp(a.0)))
        {
            detail.push_str(&format!(" — {name} {probability:.2}"));
        }
    }
    detail
}

/// Renders one provider's routing as one line per fact: `class:` once, then
/// `design:` / `implementation:` / `review:` — the one-line-per-stage layout
/// used when a chosen tier name is multi-model (#1847). With more than one
/// provider requested, the provider name heads the block instead of
/// prefixing every line, and the fact lines nest one indent level deeper.
fn render_provider_block(
    provider: &str,
    route: &ProviderRoute,
    provider_count: usize,
    ladder: Option<&Ladder>,
    style: TerminalStyle,
) -> Vec<String> {
    let mut lines = Vec::with_capacity(5);
    let indent = if provider_count > 1 {
        lines.push(format!("  {provider}:"));
        "    "
    } else {
        "  "
    };
    lines.push(format!(
        "{indent}class: {} (from {})",
        color_choice(&route.class, ladder, style),
        route.class_from.label()
    ));
    for stage in Stage::ALL {
        lines.push(format!(
            "{indent}{}",
            render_stage_line(stage, &route.stages, &route.close_calls, ladder, style)
        ));
    }
    lines
}

/// Renders one stage's fact line for [`render_provider_block`], e.g.
/// `design: needs no further work (0.94)` or `review: opus (0.41, close
/// call)` — parallel to [`render_stage_clause`] but with the stage name as a
/// `label:` prefix rather than folded into a clause.
fn render_stage_line(
    stage: Stage,
    stages: &StageAnswers,
    close_calls: &[Stage],
    ladder: Option<&Ladder>,
    style: TerminalStyle,
) -> String {
    let answer = stages.get(stage);
    let choice = color_choice(&answer.choice, ladder, style);
    let (label, content) = match stage {
        Stage::Design if answer.choice == NO_DESIGN => (
            "design",
            format!(
                "needs {}",
                colorize("no further work", Complexity::Low, style)
            ),
        ),
        Stage::Design => ("design", format!("needs {choice}")),
        Stage::Implement => ("implementation", choice),
        Stage::Review => ("review", choice),
    };
    format!(
        "{label}: {content} ({})",
        render_stage_confidence(answer, close_calls.contains(&stage))
    )
}

/// Renders one `  cites` line per open citation in `depends_on`, in citation
/// order. Empty when there are no open citations.
fn render_depends_on_lines(depends_on: &[DependencyEntry], style: TerminalStyle) -> Vec<String> {
    depends_on
        .iter()
        .map(|dep| {
            let item_ref = hyperlink(&dep.item_ref, dep.url.as_deref(), style);
            let relation = match dep.relation {
                CitationRelation::Blocker => "blocker",
                CitationRelation::Tracker => "tracker",
                CitationRelation::Unspecified => "relation unspecified",
            };
            match dep.could_be_cheaper.get("design") {
                Some(prob) => format!(
                    "  cites open {item_ref} ({relation}), which could leave less design work if resolved ({prob:.2})"
                ),
                None => format!("  cites open {item_ref} ({relation})"),
            }
        })
        .collect()
}

/// Renders per-citation GitHub misses separately from open dependencies.
fn render_reference_fetch_failure_lines(failures: &[ReferenceFetchFailure]) -> Vec<String> {
    failures
        .iter()
        .map(|failure| {
            format!(
                "  reference fetch failed: {} ({})",
                failure.item_ref, failure.error
            )
        })
        .collect()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Complexity {
    Low,
    Medium,
    High,
}

/// Tier order, rather than provider-specific names, determines complexity.
fn choice_complexity(choice: &str, ladder: &Ladder) -> Option<Complexity> {
    if choice == NO_DESIGN {
        return Some(Complexity::Low);
    }
    let tiers = ladder.tiers.as_slice();
    let index = tiers.iter().position(|tier| tier.name == choice)?;
    Some(if index == 0 {
        Complexity::Low
    } else if index == tiers.len() - 1 {
        Complexity::High
    } else {
        Complexity::Medium
    })
}

fn color_choice(choice: &str, ladder: Option<&Ladder>, style: TerminalStyle) -> String {
    ladder
        .and_then(|ladder| choice_complexity(choice, ladder))
        .map_or_else(
            || choice.to_string(),
            |level| colorize(choice, level, style),
        )
}

fn colorize(text: &str, level: Complexity, style: TerminalStyle) -> String {
    if !style.color {
        return text.to_string();
    }
    let code = match level {
        Complexity::Low => 32,
        Complexity::Medium => 33,
        Complexity::High => 31,
    };
    format!("\x1b[{code}m{text}\x1b[0m")
}

/// Link only the visible reference, and only to a GitHub issue/PR URL. OSC 8
/// URLs must not contain characters that could terminate the control sequence.
fn hyperlink(text: &str, url: Option<&str>, style: TerminalStyle) -> String {
    let Some(url) = url.filter(|url| style.hyperlinks && valid_github_item_url(url)) else {
        return text.to_string();
    };
    format!("\x1b]8;;{url}\x1b\\{text}\x1b]8;;\x1b\\")
}

fn valid_github_item_url(raw: &str) -> bool {
    if raw.chars().any(char::is_control) {
        return false;
    }
    let Ok(url) = url::Url::parse(raw) else {
        return false;
    };
    if url.scheme() != "https" || url.host_str() != Some("github.com") {
        return false;
    }
    let Some(segments) = url.path_segments() else {
        return false; // omni-dev: coverage ignore-line reason="unreachable: https is a special scheme per the WHATWG URL spec, so a URL that already passed the scheme check above can never be cannot-be-a-base and path_segments() is always Some"
    };
    let parts: Vec<_> = segments.collect();
    parts.len() == 4
        && !parts[0].is_empty()
        && !parts[1].is_empty()
        && matches!(parts[2], "issues" | "pull")
        && parts[3].parse::<u64>().is_ok()
}

/// Groups `n`'s digits by thousands, e.g. `60_000` -> `"60,000"`.
fn with_thousands(n: usize) -> String {
    let digits = n.to_string();
    let mut grouped = String::with_capacity(digits.len() + digits.len() / 3);
    for (i, ch) in digits.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            grouped.push(',');
        }
        grouped.push(ch);
    }
    grouped.chars().rev().collect()
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::provider::{Comment, GitProvider, ItemKind, ItemRef};

    fn doc(number: u64, state: ItemState) -> IssueDoc {
        IssueDoc {
            provider: GitProvider::GitHub,
            project: "rust-works/omni-dev".to_string(),
            number,
            kind: ItemKind::Issue,
            title: "Route issues".to_string(),
            state,
            body: "  The body.\n".to_string(),
            comments: vec![],
            closed_by: vec![],
            url: format!("https://github.com/rust-works/omni-dev/issues/{number}"),
        }
    }

    fn opts() -> RouteOptions {
        RouteOptions {
            draft_comments: vec![],
            model: "jev-latest".to_string(),
            close_call: DEFAULT_CLOSE_CALL,
            close_call_margin: DEFAULT_CLOSE_CALL_MARGIN,
            effort_advice: false,
            max_input_chars: DEFAULT_MAX_INPUT_CHARS,
            allow_closed: false,
            ignore_closed: false,
        }
    }

    fn default_tiers() -> Tiers {
        Provider::Anthropic.tiers().unwrap()
    }

    // Existing class-only fixtures exercise backward compatibility; effort tests use real built-ins.
    fn class_only(provider: Provider) -> Result<Ladder> {
        let mut ladder = Ladder::builtin(provider)?;
        for tier in &mut ladder.tiers.0 {
            tier.models = None;
        }
        Ok(ladder)
    }

    fn anthropic() -> Vec<Ladder> {
        vec![class_only(Provider::Anthropic).unwrap()]
    }

    fn tier_names(tiers: &Tiers) -> Vec<&str> {
        tiers.as_slice().iter().map(|t| t.name.as_str()).collect()
    }

    // ── Tiers and providers ──────────────────────────────────────────

    /// #1903 dropped `fable` as redundant with `opus`; the ladder is now two
    /// rungs.
    #[test]
    fn anthropic_tiers_are_sonnet_opus_in_order() {
        let tiers = default_tiers();
        assert_eq!(tier_names(&tiers), ["sonnet", "opus"]);
        assert_eq!(
            tiers.as_slice()[0].models.as_ref().unwrap()[0].name,
            "claude-sonnet-5-5"
        );
        assert_eq!(
            tiers.as_slice()[1].models.as_ref().unwrap()[0].name,
            "claude-opus-5-5"
        );
    }

    #[test]
    fn anthropic_tier_descriptions_are_the_reevaluated_text() {
        let tiers = default_tiers();
        let sonnet = &tiers.as_slice()[0];
        let opus = &tiers.as_slice()[1];
        assert_eq!(
            sonnet.description,
            "Reliable at implementing and reviewing well-scoped work across several files, \
             including debugging and non-obvious interactions when the approach is clear. May \
             need help with complex, open-ended design requiring sustained judgement."
        );
        assert_eq!(
            opus.description,
            "Reliable at complex, open-ended design and research: weighing architectures and \
             unfamiliar approaches, anticipating failure modes, and making security-critical \
             judgements. Carries subtle multi-file implementation and review through with \
             sustained judgement."
        );
    }

    #[test]
    fn provider_names_are_the_documented_abbreviations() {
        assert_eq!(
            tier_names(&Provider::OpenAi.tiers().unwrap()),
            ["terra", "sol", "astra"]
        );
        assert_eq!(
            tier_names(&Provider::Gemini.tiers().unwrap()),
            ["flash", "pro", "deep-think"]
        );
        assert_eq!(
            Provider::ALL.map(Provider::name),
            ["anthropic", "openai", "gemini"]
        );
        for provider in Provider::ALL {
            assert_eq!(
                provider.to_possible_value().unwrap().get_name(),
                provider.name()
            );
        }
    }

    /// Only the anthropic text was validated (#1779), and rewording shifts
    /// answers, so the other ladders copy it rung for rung where they
    /// overlap. A ladder that diverges must do so deliberately, by editing
    /// this test too.
    ///
    /// #1903 dropped `anthropic`'s third rung (`fable`) as redundant with
    /// its second (`opus`), on evidence specific to those two Claude
    /// families; `openai`/`gemini` keep three rungs each, since no
    /// equivalent case has been made for `astra`/`deep-think` shrinking
    /// their own top rungs. Their third rung's description therefore still
    /// reuses the retired `fable` text verbatim, pinned here as a literal
    /// since it is no longer present in `anthropic`'s own (now two-rung)
    /// tiers.
    #[test]
    fn openai_and_gemini_ladders_reuse_the_anthropic_descriptions_rung_for_rung() {
        let anthropic = default_tiers();
        const RETIRED_ANTHROPIC_THIRD_RUNG: &str =
            "Strongest at open-ended design and research: choosing between architectures, \
             working in unfamiliar territory with no precedent in the codebase, anticipating \
             failure modes, and security-critical judgement.";
        for provider in [Provider::OpenAi, Provider::Gemini] {
            let tiers = provider.tiers().unwrap();
            assert_eq!(tiers.as_slice().len(), 3);
            for (rung, reference) in tiers.as_slice().iter().zip(anthropic.as_slice()) {
                assert_eq!(
                    rung.description,
                    reference.description,
                    "{}: {} differs from {}",
                    // omni-dev: coverage ignore-line reason="assert_eq!'s message args are only evaluated on failure, and this test always passes"
                    provider.name(),
                    rung.name,
                    reference.name
                );
            }
            assert_eq!(
                tiers.as_slice()[2].description,
                RETIRED_ANTHROPIC_THIRD_RUNG,
                "{}: {} no longer matches the retired anthropic fable rung",
                provider.name(), // omni-dev: coverage ignore-line reason="assert_eq!'s message args are only evaluated on failure, and this test always passes"
                tiers.as_slice()[2].name // omni-dev: coverage ignore-line reason="assert_eq!'s message args are only evaluated on failure, and this test always passes"
            );
        }
    }

    #[test]
    fn ladders_are_named_by_provider_or_a_custom_name() {
        let ladder = class_only(Provider::Gemini).unwrap();
        assert_eq!(ladder.name, "gemini");
        let custom = Ladder::named("mine".to_string(), default_tiers());
        assert_eq!(custom.name, "mine");
        assert_eq!(custom.tiers, default_tiers());
    }

    #[test]
    fn tiers_need_at_least_two() {
        let err = Tiers::parse("tiers:\n  - {name: a, description: A}\n").unwrap_err();
        assert!(err.to_string().contains("at least 2 tiers"), "{err}");
    }

    #[test]
    fn tiers_reject_the_reserved_none() {
        let err = Tiers::parse(
            "tiers:\n  - {name: a, description: A}\n  - {name: none, description: B}\n",
        )
        .unwrap_err();
        assert!(err.to_string().contains("reserved"), "{err}");
    }

    #[test]
    fn tiers_reject_duplicate_names() {
        let err =
            Tiers::parse("tiers:\n  - {name: a, description: A}\n  - {name: a, description: B}\n")
                .unwrap_err();
        assert!(err.to_string().contains("more than once"), "{err}");
    }

    #[test]
    fn tiers_reject_empty_descriptions() {
        let err =
            Tiers::parse("tiers:\n  - {name: a, description: A}\n  - {name: b, description: ''}\n")
                .unwrap_err();
        assert!(err.to_string().contains("non-empty"), "{err}");
    }

    #[test]
    fn tiers_reject_unknown_fields() {
        let err = Tiers::parse(
            "tiers:\n  - {name: a, description: A, rank: 1}\n  - {name: b, description: B}\n",
        )
        .unwrap_err();
        assert!(format!("{err:#}").contains("unknown field"), "{err:#}");
    }

    #[test]
    fn tiers_load_reads_a_custom_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("tiers.yaml");
        std::fs::write(
            &path,
            "tiers:\n  - {name: small, description: S}\n  - {name: big, description: B}\n",
        )
        .unwrap();
        let tiers = Tiers::load_file(&path).unwrap();
        assert_eq!(tiers.as_slice()[1].name, "big");
    }

    #[test]
    fn tiers_load_names_a_missing_file() {
        let err = Tiers::load_file(Path::new("/no/such/tiers.yaml")).unwrap_err();
        assert!(err.to_string().contains("Failed to read tiers file"));
    }

    // ── questions ────────────────────────────────────────────────────

    const BAR: &str = " Choose the least capable class likely to complete this stage correctly \
                       with no rework, about 9 times in 10. Judge the work that remains given \
                       the text, not the size of the text.";

    fn instructions(questions: &BTreeMap<String, Question>, key: &str) -> String {
        let Question::Choice { instructions, .. } = &questions[key] else {
            panic!("{key} is not a choice");
        };
        instructions.clone()
    }

    fn options(questions: &BTreeMap<String, Question>, key: &str) -> Vec<String> {
        let Question::Choice { criteria, .. } = &questions[key] else {
            panic!("{key} is not a choice");
        };
        criteria.keys().cloned().collect()
    }

    /// Pins the #1779 stage instructions and the #1885 re-evaluated criteria.
    /// Changing either shifts answers and requires a deliberate evaluation.
    #[test]
    fn stage_questions_are_the_tested_wording() {
        let questions = build_route_questions(&anthropic()).unwrap();
        let tiers = default_tiers();
        for stage in ["stage_design", "stage_implement", "stage_review"] {
            let Question::Choice { criteria, .. } = &questions[&format!("anthropic.{stage}")]
            else {
                panic!("{stage} is not a choice");
            };
            for tier in tiers.as_slice() {
                assert_eq!(
                    criteria[&tier.name], tier.description,
                    "{stage}: {}",
                    tier.name
                );
            }
        }
        assert_eq!(
            instructions(&questions, "anthropic.stage_design"),
            format!(
                "Which class should do the design work that remains before implementation can \
                 start: choosing the approach, settling open questions, and writing a plan?{BAR}"
            )
        );
        assert_eq!(
            instructions(&questions, "anthropic.stage_implement"),
            format!(
                "Assume any remaining design work has been completed well. Which class should \
                 write the code, tests and docs?{BAR}"
            )
        );
        assert_eq!(
            instructions(&questions, "anthropic.stage_review"),
            format!(
                "Which class should review the finished change before merge, so that mistakes \
                 the automated tests would miss are caught?{BAR}"
            )
        );
    }

    #[test]
    fn only_the_design_stage_offers_none() {
        let questions = build_route_questions(&anthropic()).unwrap();
        assert_eq!(
            options(&questions, "anthropic.stage_design"),
            ["none", "opus", "sonnet"]
        );
        assert_eq!(
            options(&questions, "anthropic.stage_implement"),
            ["opus", "sonnet"]
        );
        assert_eq!(
            options(&questions, "anthropic.stage_review"),
            ["opus", "sonnet"]
        );
        let Question::Choice { criteria, .. } = &questions["anthropic.stage_design"] else {
            panic!();
        };
        assert_eq!(
            criteria[NO_DESIGN],
            "No design work remains: the text already settles the approach and the open \
             questions."
        );
    }

    /// Several ladders share one request: the same wording under each
    /// provider's prefix, with that provider's tiers as the options.
    #[test]
    fn questions_are_keyed_per_provider_in_one_map() {
        let ladders = [
            class_only(Provider::Anthropic).unwrap(),
            class_only(Provider::OpenAi).unwrap(),
        ];
        let questions = build_route_questions(&ladders).unwrap();
        let keys: Vec<&String> = questions.keys().collect();
        assert_eq!(
            keys,
            [
                "anthropic.stage_design",
                "anthropic.stage_implement",
                "anthropic.stage_review",
                "open_questions",
                "openai.stage_design",
                "openai.stage_implement",
                "openai.stage_review",
            ]
        );
        assert_eq!(
            options(&questions, "openai.stage_design"),
            ["astra", "none", "sol", "terra"]
        );
        assert_eq!(
            instructions(&questions, "openai.stage_review"),
            instructions(&questions, "anthropic.stage_review")
        );
    }

    #[test]
    fn a_named_ladder_is_keyed_by_its_own_name() {
        let ladders = [Ladder::named(
            "mine".to_string(),
            Tiers::parse("tiers:\n  - {name: a, description: A}\n  - {name: b, description: B}\n")
                .unwrap(),
        )];
        let questions = build_route_questions(&ladders).unwrap();
        assert_eq!(options(&questions, "mine.stage_implement"), ["a", "b"]);
    }

    // ── build_route_state ────────────────────────────────────────────

    #[test]
    fn route_state_without_comments_is_title_and_trimmed_body() {
        let (state, truncated) = build_route_state(&doc(7, ItemState::Open), 1000);
        assert_eq!(state, "# #7 Route issues\n\nThe body.\n");
        assert!(!truncated);
    }

    #[test]
    fn route_state_lists_comments_in_order_in_the_tested_format() {
        let mut d = doc(7, ItemState::Open);
        d.comments = vec![
            Comment {
                author: "alice".to_string(),
                body: "first\n".to_string(),
                id: None,
            },
            Comment {
                author: "bob".to_string(),
                body: "second".to_string(),
                id: None,
            },
        ];
        let (state, _) = build_route_state(&d, 1000);
        assert_eq!(
            state,
            "# #7 Route issues\n\nThe body.\n\n\n---\n\n## Comments on this issue\n\
             \n\n**Comment by alice:**\n\nfirst\n\
             \n\n**Comment by bob:**\n\nsecond\n"
        );
    }

    #[test]
    fn route_state_truncates_the_middle_on_a_char_boundary() {
        let mut d = doc(7, ItemState::Open);
        d.body = "é".repeat(100);
        let (full, _) = build_route_state(&d, usize::MAX);
        let (state, truncated) = build_route_state(&d, 20);
        assert!(truncated);
        let (head, tail) = state
            .split_once(&format!("\n\n{TRUNCATION_MARKER}\n\n"))
            .unwrap();
        assert_eq!(head.chars().count(), 10);
        assert_eq!(tail.chars().count(), 10);
        assert!(full.starts_with(head));
        assert!(full.ends_with(tail));
    }

    fn comment(author: &str, body: &str) -> Comment {
        Comment {
            author: author.to_string(),
            body: body.to_string(),
            id: None,
        }
    }

    /// #2003: the citation text is the state with its code masked, character
    /// for character, so the cut lands in the same place.
    #[test]
    fn citation_text_is_the_state_with_code_masked() {
        let mut d = doc(7, ItemState::Open);
        d.title = "Fix `o/r#1`".to_string();
        d.body = "See #5.\n\n```\nerror: o/r#2\n```".to_string();
        d.comments = vec![comment("alice", "inline `o/r#3` and #6")];
        let (state, _) = build_route_state(&d, 1000);
        let text = build_route_citation_text(&d, 1000);
        assert_eq!(text.chars().count(), state.chars().count());
        assert!(text.contains("See #5."), "{text}");
        assert!(text.contains("and #6"), "{text}");
        assert!(text.contains("**Comment by alice:**"), "{text}");
        for masked in ["o/r#1", "o/r#2", "o/r#3"] {
            assert!(!text.contains(masked), "{masked} survived in {text}");
        }
    }

    #[test]
    fn citation_text_is_truncated_where_the_state_is() {
        let mut d = doc(7, ItemState::Open);
        d.body = format!("start #1 {} `o/r#9` end #2", "x".repeat(500));
        let (state, truncated) = build_route_state(&d, 100);
        let text = build_route_citation_text(&d, 100);
        assert!(truncated);
        assert_eq!(text.chars().count(), state.chars().count());
        assert!(text.contains(TRUNCATION_MARKER), "{text}");
    }

    /// #2003: markup is masked per part, so an unclosed fence in one comment
    /// neither hides the citations after it nor turns a later quoted example
    /// into a citation.
    #[test]
    fn citation_text_masks_each_comment_on_its_own() {
        let mut d = doc(7, ItemState::Open);
        d.comments = vec![
            comment("alice", "```\nstray fence, never closed\nreal #11"),
            comment("bob", "real #12"),
            comment("carol", "```\nerror: o/r#9\n```"),
        ];
        let text = build_route_citation_text(&d, 10_000);
        assert!(text.contains("real #11"), "{text}");
        assert!(text.contains("real #12"), "{text}");
        assert!(!text.contains("o/r#9"), "{text}");
    }

    /// The latest comment is where a decision lands, so a cut must not lose it.
    #[test]
    fn route_state_truncation_keeps_the_latest_comment() {
        let mut d = doc(7, ItemState::Open);
        d.body = "x".repeat(10_000);
        d.comments = vec![Comment {
            author: "maintainer".to_string(),
            body: "**Decision**: settled.".to_string(),
            id: None,
        }];
        let (state, truncated) = build_route_state(&d, 1_000);
        assert!(truncated);
        assert!(state.starts_with("# #7 Route issues"));
        assert!(state.ends_with("**Decision**: settled.\n"), "{state}");
    }

    #[test]
    fn route_state_truncation_handles_a_one_char_cap() {
        let (state, truncated) = build_route_state(&doc(7, ItemState::Open), 1);
        assert!(truncated);
        assert_eq!(state, format!("\n\n{TRUNCATION_MARKER}\n\n\n"));
    }

    #[test]
    fn route_state_at_exactly_the_cap_is_not_truncated() {
        let d = doc(7, ItemState::Open);
        let (full, _) = build_route_state(&d, usize::MAX);
        let (state, truncated) = build_route_state(&d, full.chars().count());
        assert_eq!(state, full);
        assert!(!truncated);
    }

    #[test]
    fn drafts_follow_fetched_comments_and_default_input_is_identical() {
        let mut d = doc(7, ItemState::Open);
        for (author, body) in [("alice", "first"), ("bob", "second")] {
            d.comments.push(Comment {
                author: author.into(),
                body: body.into(),
                id: None,
            });
        }
        let drafts = ["  third\n\n  indented\n".into(), "fourth".into()];
        let (state, truncated) = build_route_state_with_drafts(&d, 1000, &drafts);
        assert!(!truncated);
        assert!(state.ends_with(
            "**Comment by draft:**\n\nthird\n\n  indented\n\n\n**Comment by draft:**\n\nfourth\n"
        ));
        assert!(state.find("first").unwrap() < state.find("second").unwrap());
        assert!(state.find("second").unwrap() < state.find("third").unwrap());
        assert_eq!(
            build_route_state_with_drafts(&d, 1000, &[]),
            build_route_state(&d, 1000)
        );
        assert_eq!(
            build_route_citation_text_with_drafts(&d, 1000, &[]),
            build_route_citation_text(&d, 1000)
        );
        d.comments.clear();
        let (state, _) = build_route_state_with_drafts(&d, 1000, &drafts);
        assert!(state.contains("## Comments on this issue"));
    }

    #[test]
    fn draft_truncation_and_code_masking_remain_aligned() {
        let d = doc(7, ItemState::Open);
        let drafts = [
            format!("`#99` {}\n```\n#88\n```", "é".repeat(200)),
            "See #2 at the tail".into(),
        ];
        let (full, _) = build_route_state_with_drafts(&d, usize::MAX, &drafts);
        let masked = build_route_citation_text_with_drafts(&d, usize::MAX, &drafts);
        assert_eq!(full.chars().count(), masked.chars().count());
        assert!(!masked.contains("#99"));
        assert!(!masked.contains("#88"));
        assert!(masked.contains("#2"));
        let (cut, truncated) = build_route_state_with_drafts(&d, 120, &drafts);
        let masked_cut = build_route_citation_text_with_drafts(&d, 120, &drafts);
        assert!(truncated);
        assert!(cut.ends_with("See #2 at the tail\n"));
        assert_eq!(cut.chars().count(), masked_cut.chars().count());
        let marker = crate::jev::input::TRUNCATION_MARKER;
        let before = cut.split_once(marker).unwrap().0.chars().count();
        let masked_before = masked_cut.split_once(marker).unwrap().0.chars().count();
        assert_eq!(before, masked_before);
        assert!(cut.find(marker).unwrap() < cut.find("See #2").unwrap());
        let isolated =
            build_route_citation_text_with_drafts(&d, 1000, &["`start".into(), "#2 end`".into()]);
        assert!(isolated.contains("#2"));
    }

    #[tokio::test]
    async fn drafts_reach_requests_and_batch_guard_precedes_closed_filtering() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(routed_json()))
            .expect(1)
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let mut options = opts();
        options.draft_comments = vec!["Blocked on #1129".into()];
        let dependencies = OpenDependencies::from([(
            ("rust-works/omni-dev".into(), 7),
            vec![citation("#1129", 1129)],
        )]);
        run_route(
            &client,
            &[doc(7, ItemState::Open)],
            &anthropic(),
            &options,
            &dependencies,
        )
        .await
        .unwrap();
        options.ignore_closed = true;
        let err = run_route(
            &client,
            &[doc(7, ItemState::Open), doc(8, ItemState::Closed)],
            &anthropic(),
            &options,
            &dependencies,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("exactly one issue"));
        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests.len(), 1);
        let body: serde_json::Value = requests[0].body_json().unwrap();
        assert!(body["state"]
            .as_str()
            .unwrap()
            .ends_with("**Comment by draft:**\n\nBlocked on #1129\n"));
        assert!(body["questions"].get("could_be_cheaper_0").is_some());
        let expected = build_route_questions_for_mode(&anthropic(), false).unwrap();
        for (key, question) in expected {
            assert_eq!(
                body["questions"][key],
                serde_json::to_value(question).unwrap()
            );
        }
    }

    #[test]
    fn preview_provenance_is_visible_in_all_formats_including_failures() {
        let mut issue = IssueRoute {
            draft_comments: vec!["triage draft.md".into(), "scope.md".into()],
            item_ref: "o/r#1".into(),
            url: "u".into(),
            title: "t".into(),
            state: ItemState::Open,
            truncated: false,
            outcome: RouteOutcome::Failed {
                error: "failure".into(),
                reference_fetch_failures: vec![],
            },
        };
        for outcome in [
            issue.outcome.clone(),
            RouteOutcome::Routed {
                open_questions: Some(test_open_questions()),
                providers: BTreeMap::new(),
                depends_on: vec![],
                reference_fetch_failures: vec![],
            },
        ] {
            issue.outcome = outcome;
            let json = serde_json::to_value(&issue).unwrap();
            assert_eq!(
                json["draft_comments"],
                serde_json::json!(["triage draft.md", "scope.md"])
            );
            let yaml: serde_yaml::Value =
                serde_yaml::from_str(&serde_yaml::to_string(&issue).unwrap()).unwrap();
            assert_eq!(yaml["draft_comments"][0].as_str(), Some("triage draft.md"));
            let text = render_issue_block(&issue, 1000, &[], TerminalStyle::default());
            assert!(text.contains("draft comments (preview): [\"triage draft.md\", \"scope.md\"]"));
        }
        issue.draft_comments.clear();
        assert!(serde_json::to_value(&issue)
            .unwrap()
            .get("draft_comments")
            .is_none());
        assert!(
            !render_issue_block(&issue, 1000, &[], TerminalStyle::default()).contains("preview")
        );
    }

    // ── class and close calls ────────────────────────────────────────

    fn answer(choice: &str, confidence: f64) -> StageAnswer {
        StageAnswer {
            effort_by_model: BTreeMap::new(),
            choice: choice.to_string(),
            confidence,
            probabilities: BTreeMap::new(),
        }
    }

    fn stages(design: &str, implement: &str, review: &str) -> StageAnswers {
        StageAnswers {
            design: answer(design, 0.9),
            implement: answer(implement, 0.9),
            review: answer(review, 0.9),
        }
    }

    #[test]
    fn close_call_shows_the_best_alternative_in_compact_text() {
        let mut stages = stages("sol", "terra", "sol");
        stages.design.confidence = 0.21;
        stages.design.probabilities = BTreeMap::from([
            ("none".to_string(), 0.44),
            ("sol".to_string(), 0.48),
            ("terra".to_string(), 0.08),
        ]);

        assert_eq!(
            render_stage_clause(
                Stage::Design,
                &stages,
                &[Stage::Design],
                None,
                TerminalStyle::default(),
            ),
            "design needs sol (0.21, close call — none 0.44)"
        );
        assert_eq!(
            render_stage_clause(Stage::Design, &stages, &[], None, TerminalStyle::default(),),
            "design needs sol (0.21)"
        );
    }

    #[test]
    fn close_call_uses_a_stable_tiebreaker_and_handles_missing_alternatives() {
        let mut answer = answer("sol", 0.21);
        answer.probabilities = BTreeMap::from([
            ("astra".to_string(), 0.4),
            ("sol".to_string(), 0.2),
            ("terra".to_string(), 0.4),
        ]);
        assert_eq!(
            render_stage_confidence(&answer, true),
            "0.21, close call — astra 0.40"
        );
        answer.probabilities.clear();
        assert_eq!(render_stage_confidence(&answer, true), "0.21, close call");
    }

    #[test]
    fn design_supplies_the_class_when_it_outranks_implement() {
        let tiers = default_tiers();
        assert_eq!(
            issue_class(&stages("opus", "sonnet", "sonnet"), &tiers),
            ("opus".to_string(), ClassSource::Design)
        );
    }

    #[test]
    fn implement_supplies_the_class_when_it_outranks_design() {
        let tiers = default_tiers();
        assert_eq!(
            issue_class(&stages("sonnet", "opus", "sonnet"), &tiers),
            ("opus".to_string(), ClassSource::Implement)
        );
    }

    /// The tie rule (#2051): equal choices credit implement, so `design`
    /// only ever means design alone raised the class.
    #[test]
    fn a_tie_goes_to_implement() {
        let tiers = default_tiers();
        for tier in ["sonnet", "opus"] {
            assert_eq!(
                issue_class(&stages(tier, tier, "sonnet"), &tiers),
                (tier.to_string(), ClassSource::Implement),
                "{tier}"
            );
        }
    }

    #[test]
    fn class_ignores_review_and_none() {
        let tiers = default_tiers();
        assert_eq!(
            issue_class(&stages("none", "sonnet", "opus"), &tiers),
            ("sonnet".to_string(), ClassSource::Implement)
        );
    }

    #[test]
    fn close_calls_are_below_the_threshold_in_stage_order() {
        let mut s = stages("opus", "sonnet", "opus");
        s.review.confidence = 0.1;
        s.design.confidence = 0.29;
        s.implement.confidence = 0.3;
        assert_eq!(
            close_calls(&s, &default_tiers(), 0.3, DEFAULT_CLOSE_CALL_MARGIN),
            [Stage::Design, Stage::Review]
        );
    }

    fn distribution(entries: &[(&str, f64)]) -> BTreeMap<String, f64> {
        entries
            .iter()
            .map(|(name, p)| ((*name).into(), *p))
            .collect()
    }

    #[test]
    fn close_call_flags_3017_split_and_preserves_class() {
        let mut s = stages("none", "sonnet", "opus");
        s.implement.confidence = 0.32;
        s.implement.probabilities = distribution(&[("sonnet", 0.55), ("opus", 0.45)]);
        assert_eq!(
            close_calls(&s, &default_tiers(), 0.3, 0.2),
            [Stage::Implement]
        );
        assert!(close_calls(&s, &default_tiers(), 0.3, 0.0).is_empty());
        assert_eq!(
            issue_class(&s, &default_tiers()),
            ("sonnet".into(), ClassSource::Implement)
        );
    }

    #[test]
    fn close_call_predicates_are_strict_independent_and_ordered() {
        let tiers = default_tiers();
        let mut s = stages("sonnet", "sonnet", "sonnet");
        for (confidence, gap, expected) in [
            (0.25, 0.25, false),  // Both exactly equal.
            (0.125, 0.5, true),   // Confidence only.
            (0.5, 0.125, true),   // Margin only.
            (0.125, 0.125, true), // Both.
            (0.5, 0.5, false),    // Neither.
        ] {
            s.design.confidence = confidence;
            s.design.probabilities = distribution(&[("sonnet", 0.5 + gap), ("opus", 0.5)]);
            assert_eq!(
                close_calls(&s, &tiers, 0.25, 0.25).contains(&Stage::Design),
                expected
            );
        }
        s.design.confidence = 0.1;
        s.design.probabilities = distribution(&[("sonnet", 0.5), ("opus", 0.5)]);
        s.implement.probabilities = s.design.probabilities.clone();
        s.review.probabilities = s.design.probabilities.clone();
        assert_eq!(close_calls(&s, &tiers, 0.3, 0.2), Stage::ALL);
        assert_eq!(close_calls(&s, &tiers, 0.3, 0.0), [Stage::Design]);
        s.design.confidence = 0.9;
        s.design.probabilities = distribution(&[("sonnet", 1.0), ("opus", 0.0)]);
        assert!(!close_calls(&s, &tiers, 0.3, 1.0).contains(&Stage::Design));
    }

    #[test]
    fn margin_uses_only_finite_offered_probabilities_without_imputation() {
        let tiers = default_tiers();
        let mut a = answer("sonnet", 0.9);
        assert_eq!(top_two_margin(&a, Stage::Design, &tiers), None);
        a.probabilities = distribution(&[("sonnet", 0.5)]);
        assert_eq!(top_two_margin(&a, Stage::Design, &tiers), None);
        for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.1, 1.1] {
            a.probabilities = distribution(&[("sonnet", 0.5), ("opus", invalid), ("unknown", 0.5)]);
            assert_eq!(top_two_margin(&a, Stage::Implement, &tiers), None);
        }
        a.probabilities = distribution(&[("none", 0.5), ("sonnet", 0.5), ("unknown", 0.5)]);
        assert_eq!(top_two_margin(&a, Stage::Design, &tiers), Some(0.0));
        for stage in [Stage::Implement, Stage::Review] {
            assert_eq!(top_two_margin(&a, stage, &tiers), None);
        }
        // Missing chosen probability and a partial, non-unit sum remain usable.
        a.probabilities = distribution(&[("none", 0.375), ("opus", 0.25)]);
        assert_eq!(top_two_margin(&a, Stage::Design, &tiers), Some(0.125));
        // The top two need not include the chosen option.
        let openai = Provider::OpenAi.tiers().unwrap();
        a.choice = "terra".into();
        a.probabilities = distribution(&[("terra", 0.0), ("sol", 0.5), ("astra", 0.5)]);
        assert_eq!(top_two_margin(&a, Stage::Implement, &openai), Some(0.0));
    }

    #[test]
    fn invalid_probabilities_retain_existing_confidence_behavior() {
        let mut s = stages("none", "sonnet", "opus");
        s.design.confidence = 0.1;
        s.design.probabilities = distribution(&[("sonnet", f64::NAN), ("opus", -1.0)]);
        s.implement.confidence = f64::NAN;
        s.review.confidence = f64::NEG_INFINITY;
        assert_eq!(
            close_calls(&s, &default_tiers(), 0.3, 0.2),
            [Stage::Design, Stage::Review]
        );
        s.implement.probabilities = distribution(&[("sonnet", 0.5), ("opus", 0.5)]);
        assert_eq!(close_calls(&s, &default_tiers(), 0.3, 0.2), Stage::ALL);
    }

    #[test]
    fn custom_and_multiple_ladders_share_flags_across_output_formats() {
        let ladders = [
            Ladder::named("custom".into(), Tiers::parse("tiers:\n  - name: small,alternative\n    description: Local work\n  - name: large\n    description: Complex work\n").unwrap()),
            class_only(Provider::Anthropic).unwrap(),
        ];
        let mut answers = BTreeMap::new();
        for ladder in &ladders {
            let first = &ladder.tiers.as_slice()[0].name;
            let second = &ladder.tiers.as_slice()[1].name;
            for stage in Stage::ALL {
                let (p1, p2) = if ladder.name == "custom" && stage == Stage::Implement {
                    (0.55, 0.45)
                } else {
                    (0.9, 0.1)
                };
                answers.insert(
                    stage.question_key(&ladder.name),
                    Answer::Choice {
                        choice: first.clone(),
                        confidence: 0.32,
                        probabilities: distribution(&[(first, p1), (second, p2)]),
                    },
                );
            }
        }
        let routes = provider_routes(&answers, &ladders, 0.3, 0.2, false).unwrap();
        assert!(routes["anthropic"].close_calls.is_empty());
        let route = &routes["custom"];
        assert_eq!(route.close_calls, [Stage::Implement]);
        let json = serde_json::to_value(route).unwrap();
        let yaml: serde_json::Value =
            serde_yaml::from_str(&serde_yaml::to_string(route).unwrap()).unwrap();
        assert_eq!(json, yaml);
        assert_eq!(json["close_calls"], serde_json::json!(["implement"]));
        for stage in Stage::ALL {
            let clause = render_stage_clause(
                stage,
                &route.stages,
                &route.close_calls,
                None,
                TerminalStyle::default(),
            );
            let line = render_stage_line(
                stage,
                &route.stages,
                &route.close_calls,
                Some(&ladders[0]),
                TerminalStyle::default(),
            );
            for text in [clause, line] {
                assert_eq!(
                    text.contains("close call"),
                    stage == Stage::Implement,
                    "{text}"
                );
                if stage == Stage::Implement {
                    assert!(text.contains("0.32, close call — large 0.45"), "{text}");
                }
            }
        }
        let confidence_only = provider_routes(&answers, &ladders, 0.3, 0.0, false).unwrap();
        assert!(confidence_only["custom"].close_calls.is_empty());
        assert_eq!(route.class, confidence_only["custom"].class);
        assert_eq!(route.class_from, confidence_only["custom"].class_from);
    }

    #[tokio::test]
    async fn run_route_applies_the_configured_margin_without_changing_requests() {
        let server = wiremock::MockServer::start().await;
        let mut implementation = choice_json("sonnet", 0.32);
        implementation["probabilities"] = serde_json::json!({"sonnet": 0.55, "opus": 0.45});
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/v1/systemone"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "model": "jev-1.13.0", "answers": {
                        "open_questions": choice_json("factual", 0.8),
                        "anthropic.stage_design": choice_json("none", 0.9),
                        "anthropic.stage_implement": implementation,
                        "anthropic.stage_review": choice_json("opus", 0.9)
                    }, "usage": {"input_tokens": 100, "output_tokens": 10}
                })),
            )
            .expect(2)
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        for margin in [0.0, DEFAULT_CLOSE_CALL_MARGIN] {
            let mut options = opts();
            options.close_call_margin = margin;
            let report = run_route(
                &client,
                &[doc(1, ItemState::Open)],
                &anthropic(),
                &options,
                &OpenDependencies::new(),
            )
            .await
            .unwrap();
            assert_eq!(
                provider(&report.issues[0].outcome, "anthropic")
                    .close_calls
                    .contains(&Stage::Implement),
                margin > 0.0
            );
        }
        let requests = server.received_requests().await.unwrap();
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[0].body, requests[1].body);
    }

    #[tokio::test]
    async fn invalid_margins_fail_before_a_jev_request() {
        let server = wiremock::MockServer::start().await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        for margin in [-0.1, 1.1, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let mut options = opts();
            options.close_call_margin = margin;
            let err = run_route(
                &client,
                &[doc(1, ItemState::Open)],
                &anthropic(),
                &options,
                &OpenDependencies::new(),
            )
            .await
            .unwrap_err();
            assert!(err.to_string().contains("close-call margin"), "{err}");
        }
        for margin in [0.0, 1.0] {
            let mut options = opts();
            options.close_call_margin = margin;
            validate_options(&[&doc(1, ItemState::Open)], &anthropic(), &options).unwrap();
        }
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[test]
    fn could_be_cheaper_key_is_stable_and_indexed() {
        assert_eq!(could_be_cheaper_key(0), "could_be_cheaper_0");
        assert_eq!(could_be_cheaper_key(1), "could_be_cheaper_1");
    }

    #[test]
    fn could_be_cheaper_question_is_the_tested_wording() {
        let Question::Noul {
            instructions,
            criteria,
        } = could_be_cheaper_question("#1129")
        else {
            panic!("expected a noul question");
        };
        assert_eq!(
            instructions,
            "This issue cites #1129, which is still open. If #1129 is resolved, how likely is \
             it that LESS design work would remain for THIS issue than the current text \
             implies — as opposed to this issue's own remaining work being unaffected, because \
             it is already scoped separately, is a parallel/sibling effort, or #1129 is \
             otherwise not a precondition for finishing this issue's own remaining work?"
        );
        assert!(criteria.is_none());
    }

    #[test]
    fn dependency_entries_reads_the_noul_answer_per_citation() {
        let citations = vec![
            Citation {
                item_ref: ItemRef {
                    provider: GitProvider::GitHub,
                    project: "rust-works/omni-dev".to_string(),
                    kind: ItemKind::Issue,
                    number: 1129,
                },
                raw: "#1129".to_string(),
                url: None,
            },
            Citation {
                item_ref: ItemRef {
                    provider: GitProvider::GitHub,
                    project: "rust-works/omni-dev".to_string(),
                    kind: ItemKind::Issue,
                    number: 1349,
                },
                raw: "#1349".to_string(),
                url: None,
            },
        ];
        let answers = BTreeMap::from([(
            "could_be_cheaper_0".to_string(),
            Answer::Noul { noul: 0.75 },
        )]);
        let deps = dependency_entries("o/r#1", &citations, &BTreeMap::new(), &answers);
        assert_eq!(deps.len(), 2, "{deps:?}");
        assert_eq!(deps[0].item_ref, "#1129");
        assert_eq!(deps[0].state, ItemState::Open);
        assert_eq!(deps[0].could_be_cheaper.get("design"), Some(&0.75));
        assert_eq!(deps[0].relation, CitationRelation::Unspecified);
        let json = serde_json::to_value(&deps[0]).unwrap();
        assert_eq!(json["relation"], "unspecified");
        assert_eq!(json["could_be_cheaper"]["design"], 0.75);
        assert_eq!(deps[1].item_ref, "#1349");
        assert!(deps[1].could_be_cheaper.is_empty());
        assert_eq!(
            serde_json::to_value(CitationRelation::Blocker).unwrap(),
            "blocker"
        );
        assert_eq!(
            serde_json::to_value(CitationRelation::Tracker).unwrap(),
            "tracker"
        );
    }

    fn relation_for(body: &str, target: u64) -> CitationRelation {
        let mut issue = doc(9999, ItemState::Open);
        issue.body = body.to_string();
        citation_relations(body, &issue)
            .get(&(issue.project, target))
            .copied()
            .unwrap_or(CitationRelation::Unspecified)
    }

    #[test]
    fn citation_relation_uses_later_explicit_mentions() {
        assert_eq!(
            relation_for(
                "See #1351 for background. Blocked on node identity in #1351.",
                1351
            ),
            CitationRelation::Blocker
        );
        assert_eq!(
            relation_for("See #1830. Split out of #1830.", 1830),
            CitationRelation::Tracker
        );
    }

    #[test]
    fn citation_relation_ignores_negation_quotes_and_conflicts() {
        for body in [
            "Not blocked on #123.",
            "For example, \"blocked on #123\" is a blocker claim.",
            "> Blocked on #123.",
            "```\nBlocked on #123\n```",
            "This is such as #123, a worked example.",
            "See #123 for context.",
            "Blocked on #123. Split out of #123.",
            "Blocked on #123. No longer blocked on #123.",
            "#123 blocks this issue. #123 no longer blocks it.",
        ] {
            assert_eq!(
                relation_for(body, 123),
                CitationRelation::Unspecified,
                "{body}"
            );
        }
    }

    #[test]
    fn citation_relation_real_issue_phrasing() {
        assert_eq!(
            relation_for(
                "Split out of #1830. Blocker #1831 closed as ADR-0083.",
                1830
            ),
            CitationRelation::Tracker
        );
        assert_eq!(
            relation_for("## Triage — blocked on #1129's classifier change.", 1129),
            CitationRelation::Blocker
        );
        assert_eq!(
            relation_for(
                "Blocked on real alias/node identity — the same work as #1351.",
                1351
            ),
            CitationRelation::Blocker
        );
        assert_eq!(
            relation_for("Absorbed by #1753; neither suggested option remains.", 1753),
            CitationRelation::Unspecified
        );
        assert_eq!(
            relation_for("#1831 blocks this issue until its ADR lands.", 1831),
            CitationRelation::Blocker
        );
        assert_eq!(
            relation_for("See #1831. It blocks this issue.", 1831),
            CitationRelation::Unspecified
        );
    }

    #[test]
    fn citation_relations_match_frozen_public_issues() {
        for (inputs, labels) in [
            (
                include_str!("../../docs/evaluations/jev-route-1871/inputs.json"),
                include_str!("../../docs/evaluations/jev-route-1871/labels.json"),
            ),
            (
                include_str!("../../docs/evaluations/jev-route-1871/holdout-inputs.json"),
                include_str!("../../docs/evaluations/jev-route-1871/holdout-labels.json"),
            ),
        ] {
            let cases: Vec<serde_json::Value> = serde_json::from_str(inputs).unwrap();
            let labels: serde_json::Value = serde_json::from_str(labels).unwrap();
            for case in cases {
                let id = case["id"].as_str().unwrap();
                let doc: IssueDoc = serde_json::from_value(case["doc"].clone()).unwrap();
                let (state, _) = build_route_state(&doc, DEFAULT_MAX_INPUT_CHARS);
                let relations = citation_relations(&state, &doc);
                // A case with no labelled relations contributes nothing.
                for (number, label) in labels[id]["relations"].as_object().into_iter().flatten() {
                    let actual = relations
                        .get(&(doc.project.clone(), number.parse().unwrap()))
                        .copied()
                        .unwrap_or(CitationRelation::Unspecified);
                    let want = [
                        ("blocker", CitationRelation::Blocker),
                        ("tracker", CitationRelation::Tracker),
                        ("unspecified", CitationRelation::Unspecified),
                    ]
                    .into_iter()
                    .find(|(name, _)| Some(*name) == label.as_str())
                    .expect("a known relation label")
                    .1;
                    assert_eq!(actual, want, "{id} -> #{number}");
                }
            }
        }
    }

    #[test]
    fn stage_answers_reject_none_outside_design() {
        let choice = |c: &str| Answer::Choice {
            choice: c.to_string(),
            confidence: 0.5,
            probabilities: BTreeMap::new(),
        };
        let answers = BTreeMap::from([
            ("anthropic.stage_design".to_string(), choice("none")),
            ("anthropic.stage_implement".to_string(), choice("none")),
            ("anthropic.stage_review".to_string(), choice("opus")),
        ]);
        let err = stage_answers(&answers, &anthropic()[0]).unwrap_err();
        assert!(err.to_string().contains("not offered"), "{err}");
    }

    #[test]
    fn stage_answers_require_a_choice_per_stage() {
        let answers = BTreeMap::from([(
            "anthropic.stage_design".to_string(),
            Answer::Noul { noul: 0.5 },
        )]);
        let err = stage_answers(&answers, &anthropic()[0]).unwrap_err();
        assert!(err.to_string().contains("no choice answer"), "{err}");
        assert!(err.to_string().contains("anthropic.stage_design"), "{err}");
    }

    /// A ladder's answers are read under its own prefix, so one provider's
    /// answers can never satisfy another's questions.
    #[test]
    fn stage_answers_are_read_under_the_ladders_prefix() {
        let choice = |c: &str| Answer::Choice {
            choice: c.to_string(),
            confidence: 0.5,
            probabilities: BTreeMap::new(),
        };
        let answers = BTreeMap::from([
            ("anthropic.stage_design".to_string(), choice("none")),
            ("anthropic.stage_implement".to_string(), choice("sonnet")),
            ("anthropic.stage_review".to_string(), choice("opus")),
        ]);
        let err = stage_answers(&answers, &class_only(Provider::OpenAi).unwrap()).unwrap_err();
        assert!(err.to_string().contains("openai.stage_design"), "{err}");
    }

    // ── validate_options ─────────────────────────────────────────────

    #[test]
    fn closed_issues_are_refused_by_default() {
        let err =
            validate_options(&[&doc(1, ItemState::Closed)], &anthropic(), &opts()).unwrap_err();
        assert!(err.to_string().contains("rust-works/omni-dev#1"), "{err}");
        assert!(err.to_string().contains("--allow-closed"), "{err}");
        assert!(err.to_string().contains("--ignore-closed"), "{err}");
    }

    /// Checked before the batch is split, so an all-closed batch still
    /// reports the conflict rather than "nothing to route".
    #[test]
    fn allow_closed_and_ignore_closed_are_mutually_exclusive() {
        let mut o = opts();
        o.allow_closed = true;
        o.ignore_closed = true;
        for state in [ItemState::Open, ItemState::Closed] {
            let err = drop_closed(&[doc(1, state)], &o).unwrap_err();
            assert!(err.to_string().contains("cannot be used together"), "{err}");
        }
    }

    // ── drop_closed (#2000) ─────────────────────────────────────────

    #[test]
    fn drop_closed_keeps_every_issue_without_the_flag() {
        let docs = [doc(1, ItemState::Open), doc(2, ItemState::Closed)];
        let (kept, ignored) = drop_closed(&docs, &opts()).unwrap();
        assert_eq!(kept.len(), 2);
        assert!(ignored.is_empty());
    }

    #[test]
    fn drop_closed_skips_closed_issues_in_request_order() {
        let mut o = opts();
        o.ignore_closed = true;
        let docs = [
            doc(3, ItemState::Closed),
            doc(1, ItemState::Open),
            doc(2, ItemState::Closed),
        ];
        let (kept, ignored) = drop_closed(&docs, &o).unwrap();
        assert_eq!(kept.iter().map(|d| d.number).collect::<Vec<_>>(), [1]);
        assert_eq!(
            ignored,
            [
                IgnoredIssue {
                    item_ref: "rust-works/omni-dev#3".to_string(),
                    url: "https://github.com/rust-works/omni-dev/issues/3".to_string(),
                    title: "Route issues".to_string(),
                },
                IgnoredIssue {
                    item_ref: "rust-works/omni-dev#2".to_string(),
                    url: "https://github.com/rust-works/omni-dev/issues/2".to_string(),
                    title: "Route issues".to_string(),
                },
            ]
        );
    }

    #[test]
    fn drop_closed_refuses_a_batch_with_no_open_issue_left() {
        let mut o = opts();
        o.ignore_closed = true;
        let docs = [doc(1, ItemState::Closed), doc(2, ItemState::Closed)];
        let err = drop_closed(&docs, &o).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("rust-works/omni-dev#1, rust-works/omni-dev#2"),
            "{msg}"
        );
        assert!(msg.contains("nothing to route"), "{msg}");
    }

    /// An empty batch passes through, keeping `validate_options`' generic
    /// "no issues to route" error.
    #[test]
    fn drop_closed_passes_an_empty_batch_through() {
        let mut o = opts();
        o.ignore_closed = true;
        let (kept, ignored) = drop_closed(&[], &o).unwrap();
        assert!(kept.is_empty());
        assert!(ignored.is_empty());
    }

    #[test]
    fn closed_issues_are_allowed_on_request() {
        let mut o = opts();
        o.allow_closed = true;
        validate_options(&[&doc(1, ItemState::Closed)], &anthropic(), &o).unwrap();
    }

    #[test]
    fn empty_runs_and_bad_knobs_are_rejected() {
        assert!(validate_options(&[], &anthropic(), &opts()).is_err());
        let mut o = opts();
        o.close_call = 1.5;
        assert!(validate_options(&[&doc(1, ItemState::Open)], &anthropic(), &o).is_err());
        let mut o = opts();
        o.max_input_chars = 0;
        assert!(validate_options(&[&doc(1, ItemState::Open)], &anthropic(), &o).is_err());
    }

    #[test]
    fn empty_and_duplicate_providers_are_rejected() {
        let err = validate_options(&[&doc(1, ItemState::Open)], &[], &opts()).unwrap_err();
        assert!(err.to_string().contains("no ladders"), "{err}");
        let twice = [
            class_only(Provider::Gemini).unwrap(),
            class_only(Provider::Gemini).unwrap(),
        ];
        let err = validate_options(&[&doc(1, ItemState::Open)], &twice, &opts()).unwrap_err();
        assert!(
            err.to_string()
                .contains("\"gemini\" is listed more than once"),
            "{err}"
        );
    }

    // ── run_route (wiremock) ─────────────────────────────────────────

    #[test]
    fn open_questions_uses_the_evaluated_wording() {
        let evaluated: serde_json::Value = serde_json::from_str(include_str!(
            "../../docs/evaluations/jev-route-2053/candidate-v3.json"
        ))
        .unwrap();
        assert_eq!(
            serde_json::to_value(open_questions_question()).unwrap(),
            evaluated
        );
    }

    #[test]
    fn open_questions_is_once_per_issue_in_both_modes() {
        let ladders = [
            Ladder::builtin(Provider::Anthropic).unwrap(),
            Ladder::builtin(Provider::OpenAi).unwrap(),
        ];
        for effort in [false, true] {
            let questions = build_route_questions_for_mode(&ladders, effort).unwrap();
            assert_eq!(
                options(&questions, "open_questions"),
                ["both", "design", "factual", "none"]
            );
            assert_eq!(
                questions
                    .keys()
                    .filter(|key| key.contains("open_questions"))
                    .count(),
                1
            );
            assert_eq!(questions["open_questions"], open_questions_question());
        }
    }

    #[test]
    fn open_questions_parses_all_kinds_without_changing_class() {
        let ladder = class_only(Provider::Anthropic).unwrap();
        for (label, kind) in [
            ("none", OpenQuestionKind::None),
            ("factual", OpenQuestionKind::Factual),
            ("design", OpenQuestionKind::Design),
            ("both", OpenQuestionKind::Both),
        ] {
            let choice = |label: &str| Answer::Choice {
                choice: label.into(),
                confidence: 0.8,
                probabilities: BTreeMap::from([(label.into(), 0.8)]),
            };
            let answers = BTreeMap::from([
                ("open_questions".into(), choice(label)),
                ("anthropic.stage_design".into(), choice("none")),
                ("anthropic.stage_implement".into(), choice("sonnet")),
                ("anthropic.stage_review".into(), choice("opus")),
            ]);
            let answer = open_questions_answer(&answers).unwrap();
            assert_eq!(answer.choice, kind);
            let routes =
                provider_routes(&answers, std::slice::from_ref(&ladder), 0.3, 0.2, false).unwrap();
            assert_eq!(routes["anthropic"].class, "sonnet");
            assert_eq!(routes["anthropic"].class_from, ClassSource::Implement);
            let issue = IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".into(),
                url: String::new(),
                title: "Example".into(),
                state: ItemState::Open,
                truncated: false,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(answer),
                    providers: routes,
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
            };
            let json = serde_json::to_value(&issue).unwrap();
            assert_eq!(json["open_questions"]["choice"], label);
            assert_eq!(json["open_questions"]["confidence"], 0.8);
            assert_eq!(json["open_questions"]["probabilities"][label], 0.8);
            let yaml: serde_yaml::Value =
                serde_yaml::from_str(&serde_yaml::to_string(&issue).unwrap()).unwrap();
            assert_eq!(yaml["open_questions"]["choice"].as_str(), Some(label));
            assert!(
                render_issue_block(&issue, 1000, &[], TerminalStyle::default())
                    .contains(&format!("  open_questions: {label} (0.80)"))
            );
        }
    }

    #[test]
    fn open_questions_rejects_absent_wrong_type_and_unknown_labels() {
        assert!(open_questions_answer(&BTreeMap::new())
            .unwrap_err()
            .to_string()
            .contains("no choice answer for open_questions"));
        for answer in [
            Answer::Noul { noul: 0.8 },
            Answer::Choice {
                choice: "unknown".into(),
                confidence: 0.8,
                probabilities: BTreeMap::new(),
            },
            Answer::Choice {
                choice: "none".into(),
                confidence: 0.8,
                probabilities: BTreeMap::from([("unknown".into(), 0.2)]),
            },
        ] {
            assert!(
                open_questions_answer(&BTreeMap::from([("open_questions".into(), answer)]))
                    .unwrap_err()
                    .to_string()
                    .contains("open_questions")
            );
        }
    }

    #[tokio::test]
    async fn unusable_open_questions_never_fail_routing() {
        let server = wiremock::MockServer::start().await;
        for number in [7, 8, 9] {
            let mut answers = serde_json::json!({
                "anthropic.stage_design": choice_json("none", 0.9),
                "anthropic.stage_implement": choice_json("sonnet", 0.9),
                "anthropic.stage_review": choice_json("opus", 0.9),
            });
            match number {
                // 7 omits the answer; 9 returns a label that was never offered.
                8 => answers["open_questions"] = choice_json("both", 0.7),
                9 => answers["open_questions"] = choice_json("maybe", 0.7),
                _ => {}
            }
            wiremock::Mock::given(wiremock::matchers::body_partial_json(serde_json::json!({"state": format!("# #{number} Route issues\n\nThe body.\n")})))
                .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"model": "jev-test", "answers": answers, "usage": {"input_tokens": 10, "output_tokens": 5}})))
                .expect(1).mount(&server).await;
        }
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let report = run_route(
            &client,
            &[
                doc(7, ItemState::Open),
                doc(8, ItemState::Open),
                doc(9, ItemState::Open),
            ],
            &anthropic(),
            &opts(),
            &OpenDependencies::new(),
        )
        .await
        .unwrap();
        assert!(report.issues.iter().all(|issue| !issue.failed()));
        assert_eq!(report.usage.input_tokens, 30);
        let json = serde_json::to_value(&report).unwrap();
        for index in [0, 2] {
            let issue = &json["issues"][index];
            assert!(issue.get("open_questions").is_none(), "{issue}");
            assert_eq!(issue["providers"]["anthropic"]["class"], "sonnet");
            assert!(issue.get("error").is_none(), "{issue}");
            let text =
                render_issue_block(&report.issues[index], 1000, &[], TerminalStyle::default());
            assert!(!text.contains("open_questions"), "{text}");
        }
        assert_eq!(json["issues"][1]["open_questions"]["choice"], "both");
        assert_eq!(
            json["issues"][1]["providers"]["anthropic"]["class"],
            "sonnet"
        );
    }

    fn test_open_questions() -> OpenQuestions {
        OpenQuestions {
            choice: OpenQuestionKind::Factual,
            confidence: 0.8,
            probabilities: BTreeMap::from([("factual".into(), 0.8)]),
        }
    }

    fn choice_json(choice: &str, confidence: f64) -> serde_json::Value {
        serde_json::json!({
            "type": "choice", "choice": choice, "confidence": confidence,
            "probabilities": {choice: confidence}
        })
    }

    fn provider<'a>(outcome: &'a RouteOutcome, name: &str) -> &'a ProviderRoute {
        let RouteOutcome::Routed { providers, .. } = outcome else {
            // omni-dev: coverage ignore-line reason="guards this test helper against misuse; every call site below passes an already-routed outcome"
            panic!("expected a routed issue: {outcome:?}");
        };
        &providers[name]
    }

    #[tokio::test]
    async fn run_route_asks_stages_and_open_questions_per_issue_and_sums_usage() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/v1/systemone"))
            .and(wiremock::matchers::body_partial_json(serde_json::json!({
                "model": "jev-latest",
                "state": "# #7 Route issues\n\nThe body.\n",
            })))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "model": "jev-1.13.0",
                    "answers": {
                        "open_questions": choice_json("factual", 0.8),
                        "anthropic.stage_design": choice_json("opus", 0.52),
                        "anthropic.stage_implement": choice_json("sonnet", 0.83),
                        "anthropic.stage_review": choice_json("opus", 0.21),
                    },
                    "usage": {"input_tokens": 100, "output_tokens": 10}
                })),
            )
            .expect(2)
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();

        let report = run_route(
            &client,
            &[doc(7, ItemState::Open), doc(7, ItemState::Open)],
            &anthropic(),
            &opts(),
            &OpenDependencies::new(),
        )
        .await
        .unwrap();

        assert_eq!(report.model, "jev-1.13.0");
        assert_eq!(report.usage.input_tokens, 200);
        assert_eq!(report.usage.output_tokens, 20);
        let issue = &report.issues[0];
        assert_eq!(issue.item_ref, "rust-works/omni-dev#7");
        let route = provider(&issue.outcome, "anthropic");
        assert_eq!(route.class, "opus");
        assert_eq!(route.class_from, ClassSource::Design);
        assert_eq!(route.close_calls, [Stage::Review]);
        assert!(!issue.truncated);

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests[0].body_json().unwrap();
        let keys: Vec<&String> = body["questions"].as_object().unwrap().keys().collect();
        assert_eq!(
            keys,
            [
                "anthropic.stage_design",
                "anthropic.stage_implement",
                "anthropic.stage_review",
                "open_questions",
            ]
        );
    }

    /// `--ignore-closed` sends one request per *open* issue, lists the closed
    /// ones under `ignored_closed`, and a closed-only batch sends nothing
    /// (#2000).
    #[tokio::test]
    async fn run_route_ignore_closed_routes_only_open_issues() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "model": "jev-1.13.0",
                    "answers": {
                        "open_questions": choice_json("factual", 0.8),
                        "anthropic.stage_design": choice_json("opus", 0.52),
                        "anthropic.stage_implement": choice_json("sonnet", 0.83),
                        "anthropic.stage_review": choice_json("opus", 0.61),
                    },
                    "usage": {"input_tokens": 100, "output_tokens": 10}
                })),
            )
            .expect(2)
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let mut o = opts();
        o.ignore_closed = true;

        let report = run_route(
            &client,
            &[
                doc(7, ItemState::Open),
                doc(8, ItemState::Closed),
                doc(9, ItemState::Open),
            ],
            &anthropic(),
            &o,
            &OpenDependencies::new(),
        )
        .await
        .unwrap();

        let refs: Vec<&str> = report.issues.iter().map(|i| i.item_ref.as_str()).collect();
        assert_eq!(refs, ["rust-works/omni-dev#7", "rust-works/omni-dev#9"]);
        let json = serde_json::to_value(&report).unwrap();
        assert_eq!(
            json["ignored_closed"],
            serde_json::json!([{
                "ref": "rust-works/omni-dev#8",
                "url": "https://github.com/rust-works/omni-dev/issues/8",
                "title": "Route issues",
            }])
        );

        let err = run_route(
            &client,
            &[doc(8, ItemState::Closed)],
            &anthropic(),
            &o,
            &OpenDependencies::new(),
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("nothing to route"), "{err}");
    }

    /// A report that skipped nothing serialises without `ignored_closed`, so
    /// existing consumers see the same shape as before #2000.
    #[test]
    fn route_report_omits_an_empty_ignored_closed() {
        let report = RouteReport {
            model: "m".to_string(),
            issues: vec![],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let json = serde_json::to_value(&report).unwrap();
        assert!(json.get("ignored_closed").is_none(), "{json}");
    }

    /// Two ladders ride one request and come back as two independent
    /// routings; `depends_on` stays issue-level, asked once.
    #[tokio::test]
    async fn run_route_routes_every_provider_in_one_call() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "model": "jev-1.13.0",
                    "answers": {
                        "open_questions": choice_json("factual", 0.8),
                        "anthropic.stage_design": choice_json("opus", 0.52),
                        "anthropic.stage_implement": choice_json("sonnet", 0.83),
                        "anthropic.stage_review": choice_json("opus", 0.9),
                        "openai.stage_design": choice_json("none", 0.9),
                        "openai.stage_implement": choice_json("sol", 0.2),
                        "openai.stage_review": choice_json("astra", 0.9),
                        "could_be_cheaper_0": {"type": "noul", "noul": 0.4},
                    },
                    "usage": {"input_tokens": 10, "output_tokens": 1}
                })),
            )
            .expect(1)
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let ladders = [
            class_only(Provider::Anthropic).unwrap(),
            class_only(Provider::OpenAi).unwrap(),
        ];
        let dependencies = OpenDependencies::from([(
            ("rust-works/omni-dev".to_string(), 7),
            vec![citation("#1129", 1129)],
        )]);
        let reference_fetch_failures = ReferenceFetchFailures::from([(
            ("rust-works/omni-dev".to_string(), 7),
            vec![ReferenceFetchFailure {
                item_ref: "#404".to_string(),
                error: "not found".to_string(),
            }],
        )]);

        let report = run_route_with_reference_fetch_failures(
            &client,
            &[doc(7, ItemState::Open)],
            &ladders,
            &opts(),
            &dependencies,
            &reference_fetch_failures,
        )
        .await
        .unwrap();

        let outcome = &report.issues[0].outcome;
        let RouteOutcome::Routed {
            providers,
            depends_on,
            reference_fetch_failures,
            ..
        } = outcome
        else {
            // omni-dev: coverage ignore-line reason="guards this test's assumption; the mocked response above always answers with a routed outcome"
            panic!("expected a routed issue: {outcome:?}");
        };
        assert_eq!(
            providers.keys().collect::<Vec<_>>(),
            ["anthropic", "openai"]
        );
        assert_eq!(provider(outcome, "anthropic").class, "opus");
        assert_eq!(
            provider(outcome, "anthropic").class_from,
            ClassSource::Design
        );
        assert!(provider(outcome, "anthropic").close_calls.is_empty());
        assert_eq!(provider(outcome, "openai").class, "sol");
        assert_eq!(
            provider(outcome, "openai").class_from,
            ClassSource::Implement
        );
        assert_eq!(provider(outcome, "openai").close_calls, [Stage::Implement]);
        assert_eq!(depends_on.len(), 1);
        assert_eq!(reference_fetch_failures[0].item_ref, "#404");

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests[0].body_json().unwrap();
        let keys: Vec<&String> = body["questions"].as_object().unwrap().keys().collect();
        assert_eq!(
            keys,
            [
                "anthropic.stage_design",
                "anthropic.stage_implement",
                "anthropic.stage_review",
                "could_be_cheaper_0",
                "open_questions",
                "openai.stage_design",
                "openai.stage_implement",
                "openai.stage_review",
            ]
        );
    }

    /// A ladder whose answers are missing fails the issue, so a partly
    /// routed issue is never reported as routed.
    #[tokio::test]
    async fn run_route_fails_the_issue_when_one_provider_is_unanswered() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(routed_json()))
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let ladders = [
            class_only(Provider::Anthropic).unwrap(),
            class_only(Provider::Gemini).unwrap(),
        ];
        let report = run_route(
            &client,
            &[doc(7, ItemState::Open)],
            &ladders,
            &opts(),
            &OpenDependencies::new(),
        )
        .await
        .unwrap();
        let RouteOutcome::Failed { error, .. } = &report.issues[0].outcome else {
            // omni-dev: coverage ignore-line reason="guards this test's assumption; the mocked response above always leaves gemini's answers missing"
            panic!("expected a failed issue: {:?}", report.issues[0]);
        };
        assert!(error.contains("gemini.stage_design"), "{error}");
    }

    fn routed_json() -> serde_json::Value {
        serde_json::json!({
            "model": "jev-1.13.0",
            "answers": {
                        "open_questions": choice_json("factual", 0.8),
                "anthropic.stage_design": choice_json("none", 0.9),
                "anthropic.stage_implement": choice_json("sonnet", 0.9),
                "anthropic.stage_review": choice_json("opus", 0.9),
            },
            "usage": {"input_tokens": 5, "output_tokens": 1}
        })
    }

    /// A failure on one issue is recorded on it; the others are still routed.
    #[tokio::test]
    async fn run_route_keeps_going_past_a_failed_issue() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::body_partial_json(
                serde_json::json!({"state": "# #1 Route issues\n\nThe body.\n"}),
            ))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(routed_json()))
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let reference_fetch_failures = ReferenceFetchFailures::from([(
            ("rust-works/omni-dev".to_string(), 1),
            vec![ReferenceFetchFailure {
                item_ref: "#404".to_string(),
                error: "not found".to_string(),
            }],
        )]);
        let report = run_route_with_reference_fetch_failures(
            &client,
            &[doc(1, ItemState::Open), doc(2, ItemState::Open)],
            &anthropic(),
            &opts(),
            &OpenDependencies::new(),
            &reference_fetch_failures,
        )
        .await
        .unwrap();

        assert!(report.issues[0].failed());
        let RouteOutcome::Failed {
            error,
            reference_fetch_failures,
        } = &report.issues[0].outcome
        else {
            panic!();
        };
        assert!(error.contains("500"), "{error}");
        assert_eq!(reference_fetch_failures[0].item_ref, "#404");
        let json = serde_json::to_value(&report).unwrap();
        assert_eq!(
            json["issues"][0]["reference_fetch_failures"][0]["ref"],
            "#404"
        );
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains("  reference fetch failed: #404 (not found)"),
            "{text}"
        );
        assert!(!report.issues[1].failed());
        assert_eq!(report.usage.input_tokens, 5);
    }

    #[tokio::test]
    async fn run_route_stops_on_an_auth_failure() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(401).set_body_string("bad key"))
            .expect(1)
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let err = run_route(
            &client,
            &[doc(3, ItemState::Open), doc(4, ItemState::Open)],
            &anthropic(),
            &opts(),
            &OpenDependencies::new(),
        )
        .await
        .unwrap_err();
        assert!(format!("{err:#}").contains("Failed to route issue rust-works/omni-dev#3"));
    }

    #[tokio::test]
    async fn run_route_rejects_a_ladder_over_the_choice_cap_before_any_request() {
        let yaml: String = std::iter::once("tiers:\n".to_string())
            .chain((0..256).map(|i| format!("  - {{name: t{i}, description: d{i}}}\n")))
            .collect();
        let ladder = Ladder::named("big".to_string(), Tiers::parse(&yaml).unwrap());
        let client = JevClient::new("http://127.0.0.1:1", "key").unwrap();
        let err = run_route(
            &client,
            &[doc(3, ItemState::Open)],
            &[ladder],
            &opts(),
            &OpenDependencies::new(),
        )
        .await
        .unwrap_err();
        let chain = format!("{err:#}");
        assert!(chain.contains("route question \"big.stage_"), "{chain}");
        assert!(
            chain.contains("at most 255 options on jev-latest"),
            "{chain}"
        );
    }

    #[tokio::test]
    async fn run_route_names_the_issue_on_an_unexpected_answer() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "model": "jev-1.13.0",
                    "answers": {
                        "open_questions": choice_json("factual", 0.8),
                        "anthropic.stage_design": choice_json("haiku", 0.9),
                        "anthropic.stage_implement": choice_json("sonnet", 0.9),
                        "anthropic.stage_review": choice_json("opus", 0.9),
                    },
                })),
            )
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let report = run_route(
            &client,
            &[doc(9, ItemState::Open)],
            &anthropic(),
            &opts(),
            &OpenDependencies::new(),
        )
        .await
        .unwrap();
        let RouteOutcome::Failed { error, .. } = &report.issues[0].outcome else {
            panic!("expected a failed issue");
        };
        assert!(error.contains("Unexpected Jev answer"), "{error}");
        assert!(error.contains("not offered"), "{error}");
    }

    fn citation(raw: &str, number: u64) -> Citation {
        Citation {
            item_ref: ItemRef {
                provider: GitProvider::GitHub,
                project: "rust-works/omni-dev".to_string(),
                kind: ItemKind::Issue,
                number,
            },
            raw: raw.to_string(),
            url: None,
        }
    }

    #[tokio::test]
    async fn run_route_asks_could_be_cheaper_for_each_open_citation() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "model": "jev-1.13.0",
                    "answers": {
                        "open_questions": choice_json("factual", 0.8),
                        "anthropic.stage_design": choice_json("opus", 0.2),
                        "anthropic.stage_implement": choice_json("sonnet", 0.61),
                        "anthropic.stage_review": choice_json("opus", 0.9),
                        "could_be_cheaper_0": {"type": "noul", "noul": 0.75},
                    },
                    "usage": {"input_tokens": 10, "output_tokens": 1}
                })),
            )
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let dependencies = OpenDependencies::from([(
            ("rust-works/omni-dev".to_string(), 7),
            vec![citation("#1129", 1129)],
        )]);

        let report = run_route(
            &client,
            &[doc(7, ItemState::Open)],
            &anthropic(),
            &opts(),
            &dependencies,
        )
        .await
        .unwrap();

        let RouteOutcome::Routed { depends_on, .. } = &report.issues[0].outcome else {
            panic!("expected a routed issue: {:?}", report.issues[0]);
        };
        assert_eq!(depends_on.len(), 1);
        assert_eq!(depends_on[0].item_ref, "#1129");
        assert_eq!(depends_on[0].state, ItemState::Open);
        assert_eq!(depends_on[0].could_be_cheaper.get("design"), Some(&0.75));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests[0].body_json().unwrap();
        let keys: Vec<&String> = body["questions"].as_object().unwrap().keys().collect();
        assert_eq!(
            keys,
            [
                "anthropic.stage_design",
                "anthropic.stage_implement",
                "anthropic.stage_review",
                "could_be_cheaper_0",
                "open_questions",
            ]
        );
    }

    #[tokio::test]
    async fn run_route_keeps_a_dependency_with_no_could_be_cheaper_answer() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(routed_json()))
            .mount(&server)
            .await;
        let client = JevClient::new(&server.uri(), "key").unwrap();
        let dependencies = OpenDependencies::from([(
            ("rust-works/omni-dev".to_string(), 7),
            vec![citation("#1129", 1129)],
        )]);

        let report = run_route(
            &client,
            &[doc(7, ItemState::Open)],
            &anthropic(),
            &opts(),
            &dependencies,
        )
        .await
        .unwrap();

        // routed_json() has no could_be_cheaper_0 answer; the issue still
        // routes and the citation remains visible without a score.
        let RouteOutcome::Routed { depends_on, .. } = &report.issues[0].outcome else {
            panic!("expected a routed issue: {:?}", report.issues[0]);
        };
        assert_eq!(depends_on.len(), 1, "{depends_on:?}");
        assert_eq!(depends_on[0].item_ref, "#1129");
        assert!(depends_on[0].could_be_cheaper.is_empty());
    }

    #[test]
    fn report_serialises_ref_and_omits_false_truncated() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: stages("none", "sonnet", "opus"),
                            class: "sonnet".to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let value = serde_json::to_value(&report).unwrap();
        assert_eq!(value["issues"][0]["ref"], "o/r#1");
        assert!(value["issues"][0].get("truncated").is_none());
        let anthropic = &value["issues"][0]["providers"]["anthropic"];
        assert_eq!(anthropic["stages"]["design"]["choice"], "none");
        assert_eq!(anthropic["class"], "sonnet");
        assert_eq!(anthropic["close_calls"], serde_json::json!([]));
        assert!(value["issues"][0].get("stages").is_none());
        assert!(value["issues"][0].get("class").is_none());
        assert_eq!(value["issues"][0]["depends_on"], serde_json::json!([]));
        assert!(value["issues"][0].get("reference_fetch_failures").is_none());
        assert!(value["issues"][0].get("error").is_none());
    }

    #[test]
    fn a_failed_issue_serialises_only_its_error() {
        let route = IssueRoute {
            draft_comments: vec![],
            item_ref: "o/r#1".to_string(),
            url: "u".to_string(),
            title: "t".to_string(),
            state: ItemState::Open,
            outcome: RouteOutcome::Failed {
                error: "HTTP 529".to_string(),
                reference_fetch_failures: vec![],
            },
            truncated: false,
        };
        let value = serde_json::to_value(&route).unwrap();
        assert_eq!(value["error"], "HTTP 529");
        assert!(value.get("providers").is_none());
        assert!(value.get("depends_on").is_none());
    }

    // ── render_route_text (#1824) ──────────────────────────────────────

    #[test]
    fn render_route_text_matches_the_worked_example() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "rust-works/omni-dev#1641".to_string(),
                url: "u".to_string(),
                title: "Some issue title".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: StageAnswers {
                                design: answer("opus", 0.52),
                                implement: answer("sonnet", 0.83),
                                review: answer("opus", 0.41),
                            },
                            class: "opus".to_string(),
                            class_from: ClassSource::Design,
                            close_calls: vec![Stage::Review],
                        },
                    )]),
                    depends_on: vec![DependencyEntry {
                        item_ref: "#1129".to_string(),
                        url: None,
                        state: ItemState::Open,
                        relation: CitationRelation::Unspecified,
                        could_be_cheaper: BTreeMap::from([("design".to_string(), 0.75)]),
                    }],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage {
                input_tokens: 1432,
                output_tokens: 61,
            },
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert_eq!(
            text,
            "rust-works/omni-dev#1641 — Some issue title\n\
             \x20\x20open_questions: factual (0.80)\n\
             \x20\x20opus (from design) — design needs opus (0.52), implementation sonnet (0.83), review \
             opus (0.41, close call)\n\
             \x20\x20cites open #1129 (relation unspecified), which could leave less design work if resolved (0.75)\n\n\
             model: jev-1.13.0, usage: 1432 input tokens, 61 output tokens\n"
        );
    }

    #[test]
    fn render_route_text_puts_each_open_citation_on_its_own_line() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "rust-works/omni-dev#1845".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: stages("none", "sonnet", "sonnet"),
                            class: "sonnet".to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![
                        DependencyEntry {
                            item_ref: "#1830".to_string(),
                            url: None,
                            state: ItemState::Open,
                            relation: CitationRelation::Unspecified,
                            could_be_cheaper: BTreeMap::from([("design".to_string(), 0.46)]),
                        },
                        DependencyEntry {
                            item_ref: "#1831".to_string(),
                            url: None,
                            state: ItemState::Open,
                            relation: CitationRelation::Unspecified,
                            could_be_cheaper: BTreeMap::new(),
                        },
                    ],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains(
                "  cites open #1830 (relation unspecified), which could leave less design work if resolved (0.46)\n  \
                 cites open #1831 (relation unspecified)\n"
            ),
            "{text}"
        );
        assert!(!text.contains("; "), "{text}");
    }

    #[test]
    fn render_depends_on_lines_labels_each_citation_relation() {
        let entry = |item_ref: &str, relation| DependencyEntry {
            item_ref: item_ref.to_string(),
            url: None,
            state: ItemState::Open,
            relation,
            could_be_cheaper: BTreeMap::new(),
        };
        let lines = render_depends_on_lines(
            &[
                entry("#1", CitationRelation::Blocker),
                entry("#2", CitationRelation::Tracker),
                entry("#3", CitationRelation::Unspecified),
            ],
            TerminalStyle::default(),
        );
        assert_eq!(
            lines,
            [
                "  cites open #1 (blocker)",
                "  cites open #2 (tracker)",
                "  cites open #3 (relation unspecified)",
            ]
        );
    }

    #[test]
    fn render_route_text_names_each_provider_when_there_are_several() {
        let route = |class: &str| ProviderRoute {
            stages: stages("none", "sonnet", "sonnet"),
            class: class.to_string(),
            class_from: ClassSource::Implement,
            close_calls: vec![],
        };
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([
                        ("anthropic".to_string(), route("sonnet")),
                        ("openai".to_string(), route("terra")),
                    ]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains("  anthropic: sonnet (from implementation) —"),
            "{text}"
        );
        assert!(
            text.contains("  openai: terra (from implementation) —"),
            "{text}"
        );
    }

    #[test]
    fn render_route_text_reports_a_failed_issue() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Failed {
                    error: "HTTP 529".to_string(),
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(text.contains("o/r#1 — t\n  failed: HTTP 529"), "{text}");
    }

    #[test]
    fn render_route_text_marks_a_closed_issue_in_the_header() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Closed,
                outcome: RouteOutcome::Failed {
                    error: "HTTP 529".to_string(),
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(text.starts_with("o/r#1 — t (closed)\n"), "{text}");
        assert!(!text.contains("ignored closed"), "{text}");
    }

    #[test]
    fn render_route_text_lists_ignored_closed_issues_before_the_footer() {
        let ignored = |n: u64| IgnoredIssue {
            item_ref: format!("o/r#{n}"),
            url: format!("https://github.com/o/r/issues/{n}"),
            title: "t".to_string(),
        };
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![],
            ignored_closed: vec![ignored(2), ignored(3)],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains("ignored closed: o/r#2, o/r#3\n\nmodel: jev-1.13.0"),
            "{text}"
        );
        let styled = render_route_text_styled(
            &report,
            DEFAULT_MAX_INPUT_CHARS,
            &[],
            TerminalStyle {
                color: false,
                hyperlinks: true,
            },
        );
        assert!(
            styled.contains("https://github.com/o/r/issues/2"),
            "{styled}"
        );
    }

    #[test]
    fn render_route_text_omits_the_depends_on_sentence_when_empty() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: stages("none", "sonnet", "sonnet"),
                            class: "sonnet".to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(!text.contains("cites"), "{text}");
    }

    /// A dependency with no `could_be_cheaper` probability for `design`
    /// (defensive: [`run_route`] always sets one for every entry it puts in
    /// `depends_on`) still renders, just without the parenthetical.
    #[test]
    fn render_route_text_cites_a_dependency_with_no_could_be_cheaper_probability() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: stages("none", "sonnet", "sonnet"),
                            class: "sonnet".to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![DependencyEntry {
                        item_ref: "#1129".to_string(),
                        url: None,
                        state: ItemState::Open,
                        relation: CitationRelation::Unspecified,
                        could_be_cheaper: BTreeMap::new(),
                    }],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(text.contains("cites open #1129"), "{text}");
        assert!(!text.contains("could leave less design work"), "{text}");
    }

    #[test]
    fn render_route_text_notes_a_truncated_issue_and_omits_the_note_otherwise() {
        let issue = |truncated: bool| IssueRoute {
            draft_comments: vec![],
            item_ref: "o/r#1".to_string(),
            url: "u".to_string(),
            title: "t".to_string(),
            state: ItemState::Open,
            outcome: RouteOutcome::Routed {
                open_questions: Some(test_open_questions()),
                providers: BTreeMap::from([(
                    "anthropic".to_string(),
                    ProviderRoute {
                        stages: stages("none", "sonnet", "sonnet"),
                        class: "sonnet".to_string(),
                        class_from: ClassSource::Implement,
                        close_calls: vec![],
                    },
                )]),
                depends_on: vec![],
                reference_fetch_failures: vec![],
            },
            truncated,
        };
        let report = |truncated| RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![issue(truncated)],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let truncated_text = render_route_text(&report(true), 60_000);
        assert!(
            truncated_text.contains("  input truncated at 60,000 characters"),
            "{truncated_text}"
        );
        let kept_text = render_route_text(&report(false), 60_000);
        assert!(!kept_text.contains("truncated"), "{kept_text}");
    }

    #[test]
    fn render_route_text_notes_no_further_design_work() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: stages("none", "sonnet", "sonnet"),
                            class: "sonnet".to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(text.contains("design needs no further work"), "{text}");
    }

    /// Pins the layout switch from #1847: a comma-joined (multi-model) tier
    /// name switches the block to one line per fact instead of repeating the
    /// name up to four times on one line.
    #[test]
    fn render_route_text_switches_to_one_line_per_stage_for_multi_model_tiers() {
        let multi = "global.anthropic.claude-sonnet-4-6,global.anthropic.claude-sonnet-5";
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "rust-works/omni-dev#1832".to_string(),
                url: "u".to_string(),
                title: "feat(drive): banded ranges for drive sheets (#1830)".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: StageAnswers {
                                design: answer(NO_DESIGN, 0.94),
                                implement: answer(multi, 0.94),
                                review: answer(multi, 0.70),
                            },
                            class: multi.to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![DependencyEntry {
                        item_ref: "#1830".to_string(),
                        url: None,
                        state: ItemState::Open,
                        relation: CitationRelation::Unspecified,
                        could_be_cheaper: BTreeMap::from([("design".to_string(), 0.48)]),
                    }],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert_eq!(
            text,
            format!(
                "rust-works/omni-dev#1832 — feat(drive): banded ranges for drive sheets (#1830)\n\
                 \x20\x20open_questions: factual (0.80)\n\
                 \x20\x20class: {multi} (from implementation)\n\
                 \x20\x20design: needs no further work (0.94)\n\
                 \x20\x20implementation: {multi} (0.94)\n\
                 \x20\x20review: {multi} (0.70)\n\
                 \x20\x20cites open #1830 (relation unspecified), which could leave less design work if resolved (0.48)\n\n\
                 model: jev-1.13.0, usage: 0 input tokens, 0 output tokens\n"
            )
        );
    }

    /// A comma-free (single-model) choice keeps today's exact compact
    /// layout — no output churn for existing built-in-ladder users.
    #[test]
    fn render_route_text_keeps_the_compact_line_for_single_word_tiers() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: stages("opus", "sonnet", "opus"),
                            class: "opus".to_string(),
                            class_from: ClassSource::Design,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains(
                "  opus (from design) — design needs opus (0.90), implementation sonnet (0.90), \
                 review opus (0.90)"
            ),
            "{text}"
        );
        assert!(!text.contains("class:"), "{text}");
    }

    /// With more than one ladder requested, a multi-model ladder's block is
    /// headed by its provider name rather than prefixing every line.
    #[test]
    fn render_route_text_headers_the_block_by_provider_when_multi_model_and_multiple_ladders() {
        let route = |class: &str| ProviderRoute {
            stages: StageAnswers {
                design: answer(NO_DESIGN, 0.9),
                implement: answer(class, 0.9),
                review: answer(class, 0.9),
            },
            class: class.to_string(),
            class_from: ClassSource::Implement,
            close_calls: vec![],
        };
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([
                        ("anthropic".to_string(), route("a,b")),
                        ("openai".to_string(), route("c,d")),
                    ]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains("  anthropic:\n    class: a,b (from implementation)\n"),
            "{text}"
        );
        assert!(text.contains("    implementation: a,b (0.90)"), "{text}");
        assert!(
            text.contains("  openai:\n    class: c,d (from implementation)\n"),
            "{text}"
        );
        assert!(text.contains("    implementation: c,d (0.90)"), "{text}");
    }

    /// The multi-line layout is decided per ladder, not for the whole issue:
    /// one provider with a multi-model choice does not force another
    /// provider's single-model choice into the block layout too.
    #[test]
    fn render_route_text_multi_model_layout_is_decided_per_ladder() {
        let multi_route = ProviderRoute {
            stages: StageAnswers {
                design: answer(NO_DESIGN, 0.9),
                implement: answer("a,b", 0.9),
                review: answer("a,b", 0.9),
            },
            class: "a,b".to_string(),
            class_from: ClassSource::Implement,
            close_calls: vec![],
        };
        let compact_route = ProviderRoute {
            stages: stages("none", "terra", "terra"),
            class: "terra".to_string(),
            class_from: ClassSource::Implement,
            close_calls: vec![],
        };
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([
                        ("anthropic".to_string(), multi_route),
                        ("openai".to_string(), compact_route),
                    ]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains("  anthropic:\n    class: a,b (from implementation)\n"),
            "{text}"
        );
        assert!(
            text.contains("  openai: terra (from implementation) — design needs no further work"),
            "{text}"
        );
    }

    /// The close-call marker stays per stage in the multi-line layout too.
    #[test]
    fn render_route_text_notes_a_close_call_in_the_multi_line_layout() {
        let mut review = answer("a,b", 0.41);
        review.probabilities =
            BTreeMap::from([("a,b".to_string(), 0.56), ("c,d".to_string(), 0.44)]);
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: StageAnswers {
                                design: answer(NO_DESIGN, 0.9),
                                implement: answer("a,b", 0.94),
                                review,
                            },
                            class: "a,b".to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![Stage::Review],
                        },
                    )]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains("review: a,b (0.41, close call — c,d 0.44)"),
            "{text}"
        );
    }

    #[test]
    fn render_route_text_separates_multiple_issues_with_a_blank_line_in_request_order() {
        let issue = |item_ref: &str| IssueRoute {
            draft_comments: vec![],
            item_ref: item_ref.to_string(),
            url: "u".to_string(),
            title: "t".to_string(),
            state: ItemState::Open,
            outcome: RouteOutcome::Failed {
                error: "e".to_string(),
                reference_fetch_failures: vec![],
            },
            truncated: false,
        };
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![issue("o/r#1"), issue("o/r#2")],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        let first = text.find("o/r#1").unwrap();
        let second = text.find("o/r#2").unwrap();
        assert!(first < second, "{text}");
        assert!(
            text.contains("o/r#1 — t\n  failed: e\n\no/r#2 — t\n  failed: e"),
            "{text}"
        );
    }

    #[test]
    fn render_route_text_ends_with_the_model_and_summed_usage() {
        let report = RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![],
            ignored_closed: vec![],
            usage: Usage {
                input_tokens: 10,
                output_tokens: 20,
            },
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert_eq!(
            text,
            "model: jev-1.13.0, usage: 10 input tokens, 20 output tokens\n"
        );
    }

    #[test]
    fn terminal_style_requires_a_usable_tty() {
        assert_eq!(
            TerminalStyle::new(false, "xterm", false, true),
            TerminalStyle::default()
        );
        assert_eq!(
            TerminalStyle::new(true, "dumb", false, true),
            TerminalStyle::default()
        );
        assert_eq!(
            TerminalStyle::new(true, "", false, true),
            TerminalStyle::default()
        );
        assert_eq!(
            TerminalStyle::new(true, "xterm", true, true),
            TerminalStyle {
                color: false,
                hyperlinks: true
            }
        );
        assert_eq!(
            TerminalStyle::new(true, "xterm", false, false),
            TerminalStyle {
                color: true,
                hyperlinks: false
            }
        );
    }

    #[test]
    fn complexity_uses_tier_order_for_built_in_and_custom_ladders() {
        let anthropic = class_only(Provider::Anthropic).unwrap();
        assert_eq!(
            choice_complexity(NO_DESIGN, &anthropic),
            Some(Complexity::Low)
        );
        assert_eq!(
            choice_complexity("sonnet", &anthropic),
            Some(Complexity::Low)
        );
        assert_eq!(
            choice_complexity("opus", &anthropic),
            Some(Complexity::High)
        );
        let custom = |names: &[&str]| {
            use std::fmt::Write;

            let mut yaml = String::from("tiers:\n");
            for name in names {
                writeln!(yaml, "  - {{name: {name}, description: work}}").unwrap();
            }
            Ladder::named("custom".to_string(), Tiers::parse(&yaml).unwrap())
        };
        let two = custom(&["a", "b"]);
        assert_eq!(choice_complexity("a", &two), Some(Complexity::Low));
        assert_eq!(choice_complexity("b", &two), Some(Complexity::High));
        let four = custom(&["a", "b", "c", "d"]);
        assert_eq!(choice_complexity("b", &four), Some(Complexity::Medium));
        assert_eq!(choice_complexity("c", &four), Some(Complexity::Medium));
        assert_eq!(choice_complexity("d", &four), Some(Complexity::High));
        assert_eq!(choice_complexity("unknown", &four), None);
    }

    #[test]
    fn hyperlink_uses_exact_osc_8_framing_and_rejects_unsafe_urls() {
        let style = TerminalStyle {
            color: false,
            hyperlinks: true,
        };
        let url = "https://github.com/other/repo/pull/42";
        assert_eq!(
            hyperlink("PR #42", Some(url), style),
            format!("\x1b]8;;{url}\x1b\\PR #42\x1b]8;;\x1b\\")
        );
        for bad in [
            "https://example.com/o/r/issues/1",
            "http://github.com/o/r/issues/1",
            "https://github.com/o/r/issues/1\x1b]8;;evil",
            "https://github.com/o/r/issues/nope",
            "not a valid url",
        ] {
            assert_eq!(hyperlink("#1", Some(bad), style), "#1");
        }
        assert_eq!(hyperlink("#1", None, style), "#1");
    }

    #[test]
    fn colorize_applies_ansi_codes_per_complexity_when_color_enabled() {
        let color = TerminalStyle {
            color: true,
            hyperlinks: false,
        };
        assert_eq!(colorize("x", Complexity::Low, color), "\x1b[32mx\x1b[0m");
        assert_eq!(colorize("x", Complexity::Medium, color), "\x1b[33mx\x1b[0m");
        assert_eq!(colorize("x", Complexity::High, color), "\x1b[31mx\x1b[0m");
        assert_eq!(
            colorize("x", Complexity::Medium, TerminalStyle::default()),
            "x"
        );
    }

    #[test]
    fn styled_report_colors_classes_stages_and_failure_and_links_refs() {
        let issue = IssueRoute {
            draft_comments: vec![],
            item_ref: "o/r#1".to_string(),
            url: "https://github.com/o/r/issues/1".to_string(),
            title: "t".to_string(),
            state: ItemState::Open,
            outcome: RouteOutcome::Routed {
                open_questions: Some(test_open_questions()),
                providers: BTreeMap::from([(
                    "anthropic".to_string(),
                    ProviderRoute {
                        stages: stages(NO_DESIGN, "opus", "sonnet"),
                        class: "opus".to_string(),
                        class_from: ClassSource::Implement,
                        close_calls: vec![],
                    },
                )]),
                depends_on: vec![DependencyEntry {
                    item_ref: "#42".to_string(),
                    url: Some("https://github.com/other/repo/pull/42".to_string()),
                    state: ItemState::Open,
                    relation: CitationRelation::Unspecified,
                    could_be_cheaper: BTreeMap::new(),
                }],
                reference_fetch_failures: vec![],
            },
            truncated: false,
        };
        let failed = IssueRoute {
            draft_comments: vec![],
            item_ref: "o/r#2".to_string(),
            url: "https://github.com/o/r/issues/2".to_string(),
            title: "failed".to_string(),
            state: ItemState::Open,
            outcome: RouteOutcome::Failed {
                error: "HTTP 529".to_string(),
                reference_fetch_failures: vec![],
            },
            truncated: false,
        };
        let report = RouteReport {
            model: "jev".to_string(),
            issues: vec![issue, failed],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let style = TerminalStyle {
            color: true,
            hyperlinks: true,
        };
        let text = render_route_text_styled(
            &report,
            DEFAULT_MAX_INPUT_CHARS,
            &[class_only(Provider::Anthropic).unwrap()],
            style,
        );
        assert!(
            text.contains(
                "\x1b[32m\x1b]8;;https://github.com/o/r/issues/1\x1b\\o/r#1\x1b]8;;\x1b\\\x1b[0m"
            ),
            "{text}"
        );
        assert!(
            text.contains(
                "\x1b[31mopus\x1b[0m (from implementation) — design needs \x1b[32mno further work\x1b[0m"
            ),
            "{text}"
        );
        assert!(text.contains("review \x1b[32msonnet\x1b[0m"), "{text}");
        assert!(
            text.contains("\x1b]8;;https://github.com/other/repo/pull/42\x1b\\#42\x1b]8;;\x1b\\"),
            "{text}"
        );
        assert!(text.contains("\x1b[31mfailed: HTTP 529\x1b[0m"), "{text}");
        let plain = render_route_text_styled(
            &report,
            DEFAULT_MAX_INPUT_CHARS,
            &[],
            TerminalStyle::default(),
        );
        assert_eq!(plain, render_route_text(&report, DEFAULT_MAX_INPUT_CHARS));
        assert!(!plain.contains('\x1b'));
        let json = serde_json::to_string(&report).unwrap();
        assert!(!json.contains("https://github.com/other/repo/pull/42"));
    }

    #[test]
    fn styled_multi_model_layout_colors_the_class_and_stage_choices() {
        let tier = "model-a,model-b";
        let ladder = Ladder::named(
            "custom".to_string(),
            Tiers::parse(&format!(
                "tiers:\n  - {{name: basic, description: work}}\n  - {{name: '{tier}', description: work}}\n"
            ))
            .unwrap(),
        );
        let report = RouteReport {
            model: "jev".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "https://github.com/o/r/issues/1".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "custom".to_string(),
                        ProviderRoute {
                            stages: stages(NO_DESIGN, tier, "basic"),
                            class: tier.to_string(),
                            class_from: ClassSource::Implement,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        };
        let text = render_route_text_styled(
            &report,
            DEFAULT_MAX_INPUT_CHARS,
            &[ladder],
            TerminalStyle {
                color: true,
                hyperlinks: false,
            },
        );
        assert!(
            text.contains(&format!("  class: \x1b[31m{tier}\x1b[0m")),
            "{text}"
        );
        assert!(
            text.contains(&format!("  implementation: \x1b[31m{tier}\x1b[0m")),
            "{text}"
        );
        assert!(text.contains("  review: \x1b[32mbasic\x1b[0m"), "{text}");
    }

    /// A two-ladder report with one design-led and one implement-led
    /// routing, for the `class_from` serialisation and text tests (#2051).
    fn mixed_source_report() -> RouteReport {
        RouteReport {
            model: "jev-1.13.0".to_string(),
            issues: vec![IssueRoute {
                draft_comments: vec![],
                item_ref: "o/r#1".to_string(),
                url: "u".to_string(),
                title: "t".to_string(),
                state: ItemState::Open,
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([
                        (
                            "anthropic".to_string(),
                            ProviderRoute {
                                stages: stages("opus", "sonnet", "sonnet"),
                                class: "opus".to_string(),
                                class_from: ClassSource::Design,
                                close_calls: vec![],
                            },
                        ),
                        (
                            "openai".to_string(),
                            ProviderRoute {
                                stages: stages(NO_DESIGN, "sol", "terra"),
                                class: "sol".to_string(),
                                class_from: ClassSource::Implement,
                                close_calls: vec![],
                            },
                        ),
                    ]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                truncated: false,
            }],
            ignored_closed: vec![],
            usage: Usage::default(),
        }
    }

    #[test]
    fn class_from_is_serialised_per_provider_in_json_and_yaml() {
        let report = mixed_source_report();
        let json = serde_json::to_value(&report).unwrap();
        let providers = &json["issues"][0]["providers"];
        assert_eq!(providers["anthropic"]["class_from"], "design");
        assert_eq!(providers["openai"]["class_from"], "implement");

        let yaml = serde_yaml::to_string(&report).unwrap();
        assert!(
            yaml.contains("class: opus\n      class_from: design\n"),
            "{yaml}"
        );
        assert!(
            yaml.contains("class: sol\n      class_from: implement\n"),
            "{yaml}"
        );
    }

    #[test]
    fn text_output_names_the_class_source_for_each_ladder() {
        let text = render_route_text(&mixed_source_report(), DEFAULT_MAX_INPUT_CHARS);
        assert!(
            text.contains("  anthropic: opus (from design) — "),
            "{text}"
        );
        assert!(
            text.contains("  openai: sol (from implementation) — "),
            "{text}"
        );
    }

    #[test]
    fn text_output_names_the_class_source_in_the_multi_line_layout() {
        let multi = "a,b";
        let report = RouteReport {
            issues: vec![IssueRoute {
                outcome: RouteOutcome::Routed {
                    open_questions: Some(test_open_questions()),
                    providers: BTreeMap::from([(
                        "anthropic".to_string(),
                        ProviderRoute {
                            stages: StageAnswers {
                                design: answer(multi, 0.9),
                                implement: answer("basic", 0.9),
                                review: answer("basic", 0.9),
                            },
                            class: multi.to_string(),
                            class_from: ClassSource::Design,
                            close_calls: vec![],
                        },
                    )]),
                    depends_on: vec![],
                    reference_fetch_failures: vec![],
                },
                ..mixed_source_report().issues.remove(0)
            }],
            ..mixed_source_report()
        };
        let text = render_route_text(&report, DEFAULT_MAX_INPUT_CHARS);
        assert!(text.contains("  class: a,b (from design)\n"), "{text}");
    }

    #[test]
    fn design_stage_with_a_named_tier_renders_needs_prefix() {
        let line = render_stage_line(
            Stage::Design,
            &stages("opus", "sonnet", "sonnet"),
            &[],
            None,
            TerminalStyle::default(),
        );
        assert_eq!(line, "design: needs opus (0.90)");
    }

    #[test]
    fn with_thousands_groups_digits() {
        assert_eq!(with_thousands(0), "0");
        assert_eq!(with_thousands(999), "999");
        assert_eq!(with_thousands(60_000), "60,000");
        assert_eq!(with_thousands(1_000_000), "1,000,000");
    }
}