vcs-github 0.12.0

Automate GitHub from Rust: a typed, async wrapper for the GitHub CLI (gh) — pull requests, issues, releases, and CI checks.
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
#![cfg_attr(docsrs, feature(doc_cfg))]
#![deny(rustdoc::broken_intra_doc_links)]
//! `vcs-github` — automate GitHub from Rust by driving the `gh` CLI.
//!
//! You call typed `async` methods; `vcs-github` runs the real `gh`, parses its
//! output, and hands you structured values — so you get *gh's own* behaviour, auth,
//! and host resolution, not a reimplementation of the GitHub REST/GraphQL API.
//! Async, structured errors, mockable. Every command runs inside an OS **job** (an
//! OS-level container that kills the whole process tree if your program exits, via
//! [`processkit`]) so a `gh` subprocess is never orphaned, with an optional
//! per-client [timeout](GitHub::default_timeout). Read-style methods ask `gh` for
//! `--json` and deserialize it; nothing scrapes human-readable output.
//!
//! # What you can do
//!
//! Check auth · view the repo · the full pull-request lifecycle (list / view /
//! create / merge / mark-ready / close, review / comment, CI checks, feedback) ·
//! issues · releases · GitHub Actions workflows and runs (list / view / watch,
//! plus dispatch a workflow / rerun / cancel a run). One tiny call to start:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_github::{GitHub, GitHubApi};
//! # async fn demo() -> Result<(), processkit::Error> {
//! let gh = GitHub::new();
//! let prs = gh.pr_list(Path::new(".")).await?; // up to 100 open PRs
//! # let _ = prs; Ok(()) }
//! ```
//!
//! # The surface (engineering reference)
//!
//! - **[`GitHubApi`]** — the object-safe trait every operation lives on. Depend
//!   on `&dyn GitHubApi` (or generically on `impl GitHubApi`) so a test can swap
//!   the real client for a double. Repo-scoped methods take the working
//!   directory as the first argument and return typed results ([`PullRequest`],
//!   [`Issue`], [`RepoView`], [`CheckRun`], [`Workflow`], [`WorkflowRun`], [`Release`],
//!   [`PrFeedback`], …) or a structured [`Error`].
//! - **[`GitHub`]** — the real client. [`GitHub::new`] uses the job-backed
//!   runner; [`GitHub::with_runner`] injects a fake one for tests. It is generic
//!   over the [`ProcessRunner`] seam, defaulting to the production runner.
//!   [`with_credentials`](GitHub::with_credentials) attaches a
//!   [`CredentialProvider`] to supply a token per operation (injected as
//!   `GH_TOKEN`, never in `argv`) — opt-in, off by default (ambient `gh` auth).
//!   [`with_host`](GitHub::with_host) targets a specific host (a [`GitHubHost`] —
//!   github.com or a GitHub Enterprise Server host), so the credential lands in
//!   the env var `gh` reads for *that* host (`GH_TOKEN` vs `GH_ENTERPRISE_TOKEN`)
//!   and [`auth_status_for`](GitHubApi::auth_status_for) probes just that host.
//! - **[`GitHubAt`]** — a cwd-bound view ([`GitHub::at`]) whose methods drop the
//!   leading `dir`, so `gh.at(dir).pr_list()` reads as `gh.pr_list(dir)` — handy
//!   when one client drives one checkout.
//! - **Method groups** on the trait: PRs ([`pr_list`](GitHubApi::pr_list),
//!   [`pr_view`](GitHubApi::pr_view), [`pr_create`](GitHubApi::pr_create),
//!   [`pr_merge`](GitHubApi::pr_merge), [`pr_mark_ready`](GitHubApi::pr_mark_ready),
//!   [`pr_close`](GitHubApi::pr_close), [`pr_checkout`](GitHubApi::pr_checkout),
//!   [`pr_review`](GitHubApi::pr_review),
//!   [`pr_comment`](GitHubApi::pr_comment), [`pr_edit`](GitHubApi::pr_edit), [`pr_checks`](GitHubApi::pr_checks),
//!   [`pr_feedback`](GitHubApi::pr_feedback), [`pr_diff`](GitHubApi::pr_diff), …); Actions
//!   workflows ([`workflow_list`](GitHubApi::workflow_list),
//!   [`workflow_view`](GitHubApi::workflow_view)) and runs
//!   ([`run_list`](GitHubApi::run_list), [`run_view`](GitHubApi::run_view),
//!   [`run_watch`](GitHubApi::run_watch) — *blocking*, bounded by the client
//!   timeout — plus the run-control verbs
//!   [`workflow_dispatch`](GitHubApi::workflow_dispatch),
//!   [`run_rerun`](GitHubApi::run_rerun), [`run_cancel`](GitHubApi::run_cancel));
//!   issues & releases ([`issue_create`](GitHubApi::issue_create),
//!   [`issue_close`](GitHubApi::issue_close), [`issue_reopen`](GitHubApi::issue_reopen),
//!   [`issue_comment`](GitHubApi::issue_comment),
//!   [`release_view`](GitHubApi::release_view), …); plus the escape hatches
//!   [`run`](GitHubApi::run) / [`api`](GitHubApi::api) for anything unmodelled.
//! - **Builder specs** for the multi-option commands — [`PrList`] / [`IssueList`]
//!   select state and limit while the parameterless list methods remain open/100;
//!   [`WorkflowList`] selects disabled inclusion and a limit while its shorthand
//!   remains active-only/50;
//!   [`PrCreate`] (title/body
//!   with optional `head`/`base`), [`PrEdit`] (optional `title` and/or `body`
//!   for `pr edit`), [`PrMerge`] (strategy [`MergeStrategy`],
//!   `--auto`, `--delete-branch`), [`PrClose`] (optional `--delete-branch`),
//!   [`WorkflowDispatch`] (a `workflow_dispatch` event's target `ref` + inputs),
//!   [`ReleaseCreate`] (a release's title/notes/draft/prerelease), and
//!   [`ReviewAction`] (whose private fields make
//!   an empty-body request-changes unrepresentable) — each `#[non_exhaustive]`,
//!   built with a constructor and chained setters, named after the flags they emit.
//!   A single-toggle verb takes a direct argument instead ([`run_rerun`](GitHubApi::run_rerun)'s
//!   [`RerunScope`]).
//!
//! # Recipes
//!
//! Read state — depend on the trait so the same code takes a real client or a mock:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_github::{GitHub, GitHubApi};
//! # async fn demo() -> Result<(), processkit::Error> {
//! let gh = GitHub::new();
//! let dir = Path::new(".");
//! let authed = gh.auth_status().await?;          // is `gh` logged in?
//! let open = gh.pr_list(dir).await?;             // up to 100 open PRs
//! # let _ = (authed, open); Ok(()) }
//! ```
//!
//! Mutate through the builder specs — open a PR, approve it, then squash-merge:
//!
//! ```no_run
//! use std::path::Path;
//! use vcs_github::{GitHub, GitHubApi, PrCreate, PrMerge, ReviewAction};
//! # async fn demo(gh: &GitHub) -> Result<(), processkit::Error> {
//! let dir = Path::new(".");
//! let url = gh.pr_create(dir, PrCreate::new("Add X", "…").base("main")).await?;
//! gh.pr_review(dir, 7, ReviewAction::approve().with_body("LGTM")).await?;
//! gh.pr_merge(dir, 7, PrMerge::squash().delete_branch()).await?;
//! # let _ = url; Ok(()) }
//! ```
//!
//! # Testing
//!
//! Two seams: enable the **`mock`** feature for a `mockall`-generated
//! `MockGitHubApi` (stub whole methods), or inject a
//! [`ScriptedRunner`](processkit::testing::ScriptedRunner) with [`GitHub::with_runner`]
//! to exercise the *real* argv-building and parsing against canned output — no
//! `gh` binary or network needed, so it runs on CI. The cross-cutting testing
//! patterns live in
//! [vcs-testkit's guide](https://docs.rs/vcs-testkit/latest/vcs_testkit/guide/testing/).
//!
//! # Safety
//!
//! Caller values placed in a bare positional argv slot (an `api` endpoint, a
//! release `tag`) are refused before spawning if empty or starting with `-` —
//! `gh` would parse them as flags. Flag-value slots (`--body <b>`,
//! `--branch <b>`) are consumed verbatim and need no guard.
//!
//! # In-depth guide
//!
//! Beyond this page, this crate ships a full how-to guide — rendered on docs.rs
//! from `docs/`. See the [`guide`] module.

use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

// The credential seam (the shared managed client behind `GitHub` is generated by
// `vcs_cli_support::managed_client!`) — re-exported so a consumer can supply a
// token provider.
pub use vcs_cli_support::{
    Credential, CredentialProvider, CredentialRequest, CredentialService, EnvToken, FnProvider,
    OutputBudget, Secret, StaticCredential, provider_fn,
};
// Re-export the processkit types in this crate's public API, so consumers needn't
// depend on processkit directly — incl. `ProcessRunner` (the `with_runner`/
// `GitHub<R>` seam) and the `JobRunner` default. (Also brings
// `Error`/`Result`/`ProcessResult`/`ProcessRunner` into scope here.)
// `ErrorReason` and `ErrorKind` ride along deliberately: since processkit 3.0
// `Error` is an opaque wrapper, so *classifying* a failure means reaching
// `err.reason()` (variant-grain) or `err.kind()` (flat) — types a consumer cannot
// name without them. Omitting them would leave the re-exported `Error` unmatched,
// a silent capability regression rather than a mechanical rename.
pub use processkit::{
    Error, ErrorKind, ErrorReason, JobRunner, ProcessResult, ProcessRunner, Result,
};
// Re-exported so a consumer can name the token for `default_cancel_on` without
// taking a direct `processkit` dependency. (Cancellation is core in processkit
// 0.10 — always available, no feature.)
pub use processkit::CancellationToken;

mod parse;
pub use parse::{
    CheckBucket, CheckRun, Comment, Issue, PrFeedback, PullRequest, Release, RepoView, Review,
    Workflow, WorkflowRun,
};
// Re-exported so `vcs_github::FileDiff` (and the types nested in it) resolve
// without a direct `vcs-diff` dependency — `pr_diff` returns `vcs-diff`'s model
// verbatim (`gh pr diff` emits the same git-format diff `git diff`/`jj diff
// --git` do; `crates/diff/src/diff.rs`'s parser is shared, not duplicated).
pub use vcs_diff::{ChangeKind, DiffLine, FileDiff, Hunk};
// The parsed `gh --version`, re-exported as `GitHubVersion` — the shared
// `major.minor.patch` type `vcs-git`/`vcs-jj` also gate on (an alias of
// `vcs_diff::Version`), so a consumer needn't name `vcs-diff` to read
// [`GitHubCapabilities::version`].
pub use vcs_diff::Version as GitHubVersion;

/// Which pull requests [`GitHubApi::pr_list_with`] returns.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PrListState {
    /// Open pull requests (the CLI default).
    #[default]
    Open,
    /// Closed, unmerged pull requests.
    Closed,
    /// Merged pull requests.
    Merged,
    /// Pull requests in every state.
    All,
}

impl PrListState {
    fn as_arg(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Closed => "closed",
            Self::Merged => "merged",
            Self::All => "all",
        }
    }
}

/// Filters for [`GitHubApi::pr_list_with`] (`gh pr list`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrList {
    /// State filter (`--state`).
    pub state: PrListState,
    /// Maximum number of pull requests (`--limit`).
    pub limit: usize,
}

impl PrList {
    /// Open pull requests, up to 100 — the compatibility default used by
    /// [`GitHubApi::pr_list`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Select a pull-request state.
    pub fn state(mut self, state: PrListState) -> Self {
        self.state = state;
        self
    }

    /// Set the maximum number of pull requests returned.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }
}

impl Default for PrList {
    fn default() -> Self {
        Self {
            state: PrListState::Open,
            limit: 100,
        }
    }
}

/// Which issues [`GitHubApi::issue_list_with`] returns.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum IssueListState {
    /// Open issues (the CLI default).
    #[default]
    Open,
    /// Closed issues.
    Closed,
    /// Issues in every state.
    All,
}

impl IssueListState {
    fn as_arg(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Closed => "closed",
            Self::All => "all",
        }
    }
}

/// Filters for [`GitHubApi::issue_list_with`] (`gh issue list`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct IssueList {
    /// State filter (`--state`).
    pub state: IssueListState,
    /// Maximum number of issues (`--limit`).
    pub limit: usize,
}

impl IssueList {
    /// Open issues, up to 100 — the compatibility default used by
    /// [`GitHubApi::issue_list`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Select an issue state.
    pub fn state(mut self, state: IssueListState) -> Self {
        self.state = state;
        self
    }

    /// Set the maximum number of issues returned.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }
}

impl Default for IssueList {
    fn default() -> Self {
        Self {
            state: IssueListState::Open,
            limit: 100,
        }
    }
}

/// Filters for [`GitHubApi::workflow_list_with`] (`gh workflow list`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WorkflowList {
    /// Include disabled workflows (`--all`). Disabled workflows are hidden by
    /// default by `gh`.
    pub include_disabled: bool,
    /// Maximum number of workflows (`--limit`).
    pub limit: usize,
}

impl WorkflowList {
    /// Active workflows, up to gh's default of 50 — the compatibility default
    /// used by [`GitHubApi::workflow_list`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Include disabled workflows (`--all`).
    pub fn all(mut self) -> Self {
        self.include_disabled = true;
        self
    }

    /// Set the maximum number of workflows returned.
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }
}

impl Default for WorkflowList {
    fn default() -> Self {
        Self {
            include_disabled: false,
            limit: 50,
        }
    }
}

/// Name of the underlying CLI binary this crate drives.
pub const BINARY: &str = "gh";

const PR_FIELDS: &str = "number,title,state,isDraft,headRefName,baseRefName,url,labels,assignees,author,createdAt,updatedAt,milestone";
const REPO_FIELDS: &str = "name,owner,description,url,isPrivate,defaultBranchRef";
const ISSUE_LIST_FIELDS: &str =
    "number,title,state,body,url,labels,assignees,author,createdAt,updatedAt,milestone";
const ISSUE_VIEW_FIELDS: &str =
    "number,title,state,body,url,labels,assignees,author,createdAt,updatedAt,milestone";
const RUN_FIELDS: &str =
    "databaseId,name,displayTitle,status,conclusion,workflowName,headBranch,event,url,createdAt";
const WORKFLOW_FIELDS: &str = "id,name,path,state";
// `gh workflow view` has no JSON mode. Resolve a typed view through the JSON
// inventory instead; this signed-32-bit maximum asks gh to paginate until the
// repository is exhausted without overflowing gh's `int` on 32-bit builds.
const WORKFLOW_VIEW_LOOKUP_LIMIT: usize = i32::MAX as usize;
// `gh run watch` refreshes its table about every three seconds. Five minutes without
// either stream progressing therefore signals a wedged watcher, while still allowing
// an otherwise healthy CI run to last for hours.
const RUN_WATCH_INACTIVITY_TIMEOUT: Duration = Duration::from_secs(5 * 60);
const CHECK_FIELDS: &str = "name,state,bucket,workflow,link,startedAt,completedAt";
const RELEASE_LIST_FIELDS: &str = "tagName,name,isLatest,isDraft,isPrerelease,publishedAt";
const RELEASE_VIEW_FIELDS: &str = "tagName,name,body,url,publishedAt,isDraft,isPrerelease,author";

/// Injection guard for bare positional argv slots: a caller-supplied value
/// with a leading `-` is parsed by gh's CLI as a *flag* (verified: `gh api -evil` →
/// flag parsing), and an empty value changes a command's
/// meaning. Refuse both before anything spawns. Most flag-VALUE positions
/// (`--body <b>`, `--branch <b>`) need no guard because gh consumes the next
/// token verbatim; public PR list filters additionally use this guard as a
/// defense-in-depth boundary for untrusted branch input.
fn reject_flag_like(what: &str, value: &str) -> Result<()> {
    vcs_cli_support::reject_flag_like(BINARY, what, value)
}

fn reject_zero_limit(operation: &str, limit: usize) -> Result<()> {
    if limit == 0 {
        return Err(Error::spawn(
            BINARY,
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("{operation} limit must be greater than zero"),
            ),
        ));
    }
    Ok(())
}

/// Reject a label mutation that cannot change anything, or a label name the CLI
/// cannot resolve. Label names otherwise stay unfiltered: they are always passed
/// in a flag-value slot, so a leading `-` is data rather than another option.
fn reject_invalid_labels(operation: &str, labels: &[String]) -> Result<()> {
    if labels.is_empty() || labels.iter().any(|label| label.trim().is_empty()) {
        return Err(Error::spawn(
            BINARY,
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("{operation} requires at least one non-empty label"),
            ),
        ));
    }
    Ok(())
}

/// Reject workflow-dispatch input keys that would make gh parse a different
/// `key=value` pair, or which cannot be passed to a process. Values intentionally
/// remain unconstrained: `--raw-field` receives them as literal flag-value data.
fn reject_invalid_workflow_dispatch_fields(fields: &[(String, String)]) -> Result<()> {
    for (key, _) in fields {
        let reason = if key.trim().is_empty() {
            "must not be empty"
        } else if key.contains('=') {
            "must not contain `=`"
        } else if key.contains('\0') {
            "must not contain NUL"
        } else {
            continue;
        };
        return Err(Error::spawn(
            BINARY,
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("workflow_dispatch input key {key:?} {reason}"),
            ),
        ));
    }
    Ok(())
}

fn resolve_workflow(workflows: Vec<Workflow>, selector: &str) -> Result<Workflow> {
    if selector.is_empty() {
        return Err(Error::spawn(
            BINARY,
            std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "workflow_view selector must not be empty",
            ),
        ));
    }

    let numeric_id = selector.parse::<u64>().ok();
    let selector_lower = selector.to_lowercase();
    let is_file = selector_lower.ends_with(".yml") || selector_lower.ends_with(".yaml");
    let mut matches: Vec<_> = workflows
        .into_iter()
        .filter(|workflow| {
            if let Some(id) = numeric_id {
                workflow.id == id
            } else if is_file {
                workflow.path == selector
                    || workflow
                        .path
                        .rsplit('/')
                        .next()
                        .is_some_and(|file| file == selector)
            } else {
                workflow.name.to_lowercase() == selector_lower
            }
        })
        .collect();

    match matches.len() {
        1 => Ok(matches.pop().expect("length checked")),
        0 => Err(Error::parse(
            BINARY,
            format!("could not find workflow {selector:?}"),
        )),
        count => Err(Error::parse(
            BINARY,
            format!("workflow selector {selector:?} is ambiguous ({count} matches)"),
        )),
    }
}

/// The GitHub host an operation targets: SaaS `github.com` or a **GitHub
/// Enterprise Server** (GHES) host. `gh` picks the credential environment variable
/// it reads *per host* — `GH_TOKEN` for github.com, `GH_ENTERPRISE_TOKEN` for a
/// GHES host — and its `auth status` can be scoped to a single host, so this type
/// carries that host so the client (1) injects a supplied credential into the
/// variable `gh` actually reads for it (see [`GitHub::with_host`]) and (2) can
/// probe auth for exactly that host (see [`GitHubApi::auth_status_for`]).
///
/// Build it for github.com ([`github_com`](GitHubHost::github_com)), from a bare
/// hostname ([`new`](GitHubHost::new)), or from a repository's remote URL
/// ([`from_remote_url`](GitHubHost::from_remote_url)). A hostname that cannot be
/// determined is an **error**, never a silent fall back to github.com — so an
/// ambiguous or unknown host is a diagnosable result at the call site rather than
/// a quiet authentication against the wrong host with the github.com token.
///
/// ```
/// # use vcs_github::GitHubHost;
/// let saas = GitHubHost::github_com();
/// assert!(saas.is_github_com() && !saas.is_enterprise());
///
/// let ghes = GitHubHost::new("ghe.example.com").unwrap();
/// assert!(ghes.is_enterprise());
/// assert_eq!(ghes.as_str(), "ghe.example.com");
///
/// // github.com (any case) classifies as SaaS; every other valid host is GHES.
/// assert!(GitHubHost::new("GitHub.com").unwrap().is_github_com());
/// // An unparseable / hostless remote is an error, not a github.com guess.
/// assert!(GitHubHost::from_remote_url("not-a-url").is_err());
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GitHubHost {
    /// The canonical (lower-cased) hostname, e.g. `github.com` / `ghe.example.com`.
    host: String,
    /// `true` for a GitHub Enterprise Server host; `false` for SaaS github.com.
    enterprise: bool,
}

impl GitHubHost {
    /// The SaaS GitHub hostname (`github.com`).
    pub const SAAS_HOST: &'static str = "github.com";

    /// The SaaS github.com host — a supplied credential is injected as `GH_TOKEN`.
    #[must_use]
    pub fn github_com() -> Self {
        Self {
            host: Self::SAAS_HOST.to_string(),
            enterprise: false,
        }
    }

    /// Classify a bare `host`: `github.com` (case-insensitive) is SaaS; any other
    /// valid hostname is treated as a GitHub Enterprise Server host (its credential
    /// goes to `GH_ENTERPRISE_TOKEN`). Returns an error for an empty, flag-like, or
    /// otherwise malformed hostname (a scheme, path, port, userinfo, or whitespace)
    /// rather than guessing — the value must be a bare DNS-style host.
    pub fn new(host: impl AsRef<str>) -> Result<Self> {
        let host = validate_host(host.as_ref())?;
        let enterprise = host != Self::SAAS_HOST;
        Ok(Self { host, enterprise })
    }

    /// Derive the host from a repository **remote URL** and classify it. Handles
    /// `scheme://[user@]host[:port]/…` (HTTPS/SSH/…) and the scp-like
    /// `[user@]host:path` SSH form; any userinfo and port are dropped. A remote
    /// whose host can't be determined (unparseable, hostless, or ambiguous — an
    /// IPv6 literal, a bare single-label scp authority, a local path) is an
    /// **error**, not a silent github.com fallback, so the caller can surface an
    /// ambiguous remote as a diagnosable result.
    pub fn from_remote_url(url: &str) -> Result<Self> {
        match host_from_remote_url(url) {
            Some(host) => Self::new(host),
            None => Err(invalid_host_error(
                url,
                "no GitHub host could be determined from the remote URL",
            )),
        }
    }

    /// The canonical hostname (`github.com`, `ghe.example.com`).
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.host
    }

    /// Whether this is a GitHub Enterprise Server host (anything but github.com).
    #[must_use]
    pub fn is_enterprise(&self) -> bool {
        self.enterprise
    }

    /// Whether this is SaaS github.com.
    #[must_use]
    pub fn is_github_com(&self) -> bool {
        !self.enterprise
    }

    /// The environment variable `gh` reads for a credential on this host —
    /// `GH_TOKEN` for github.com, `GH_ENTERPRISE_TOKEN` for a GHES host. `'static`
    /// so it can seed the client's token-env binding.
    fn token_env_var(&self) -> &'static str {
        if self.enterprise {
            "GH_ENTERPRISE_TOKEN"
        } else {
            "GH_TOKEN"
        }
    }
}

/// Validate a bare gh hostname, returning it **lower-cased** (its canonical form —
/// hostnames are case-insensitive and `gh` stores them lower-cased). A host must
/// be a non-empty DNS-style name (ASCII letters/digits/`.`/`-`), not start with
/// `-`/`.` nor end with `.`, and carry no scheme, path, port, userinfo, or
/// whitespace. Anything else is refused as invalid input — `gh` would misread it,
/// or it is not a host at all.
fn validate_host(host: &str) -> Result<String> {
    let trimmed = host.trim();
    let well_formed = !trimmed.is_empty()
        && !trimmed.starts_with('-')
        && !trimmed.starts_with('.')
        && !trimmed.ends_with('.')
        && trimmed
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-');
    if !well_formed {
        return Err(invalid_host_error(host, "not a valid GitHub hostname"));
    }
    Ok(trimmed.to_ascii_lowercase())
}

/// The `ErrorReason::Spawn` / `InvalidInput` the crate raises for a rejected caller
/// value (the same shape as [`reject_flag_like`], classified by
/// `vcs_cli_support::is_invalid_input`), naming the bad host and why.
fn invalid_host_error(value: &str, reason: &str) -> Error {
    Error::spawn(
        BINARY,
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("GitHub host {value:?}: {reason}"),
        ),
    )
}

/// Extract the hostname from a repository remote URL (HTTPS / SSH / scp-like),
/// dropping any userinfo and port. Returns `None` when no unambiguous host is
/// present, so [`GitHubHost::from_remote_url`] surfaces a diagnosable error rather
/// than defaulting to github.com. An IPv6-literal authority (`[::1]`) and a bare
/// single-label scp authority (indistinguishable from a Windows drive path) return
/// `None` too — a GitHub host is a dotted DNS name.
fn host_from_remote_url(url: &str) -> Option<String> {
    let url = url.trim();
    if url.is_empty() {
        return None;
    }
    // scheme://[user@]host[:port]/…  (https, http, ssh, git, …). The authority
    // ends at the first `/`, `?`, or `#`; drop any `user:pass@` userinfo.
    if let Some((_scheme, rest)) = url.split_once("://") {
        let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
        let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
        return strip_port(host_port);
    }
    // scp-like SSH: `[user@]host:path` (no scheme). The host ends at the first `:`.
    if let Some((authority, _path)) = url.split_once(':') {
        let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
        // Require a dotted host so a Windows drive path (`C:\…`) or a bare
        // single-label authority isn't misread as a remote host — those are
        // ambiguous, and the caller gets a diagnosable error instead of a guess.
        if host.contains('.') && !host.contains('/') && !host.contains('\\') {
            return Some(host.to_string());
        }
    }
    None
}

/// Drop a trailing `:port` from `host[:port]`, refusing an IPv6-literal authority
/// (`[::1]`) — a GitHub host is never a bracketed literal, and gh names hosts
/// without a port.
fn strip_port(host_port: &str) -> Option<String> {
    if host_port.is_empty() || host_port.starts_with('[') {
        return None;
    }
    Some(
        host_port
            .split_once(':')
            .map_or(host_port, |(h, _)| h)
            .to_string(),
    )
}

/// How [`GitHubApi::pr_merge`] merges the PR — exactly one of gh's mutually
/// exclusive strategy flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MergeStrategy {
    /// A merge commit (`--merge`).
    Merge,
    /// Squash into one commit (`--squash`).
    Squash,
    /// Rebase the commits onto the base (`--rebase`).
    Rebase,
}

impl MergeStrategy {
    fn flag(self) -> &'static str {
        match self {
            MergeStrategy::Merge => "--merge",
            MergeStrategy::Squash => "--squash",
            MergeStrategy::Rebase => "--rebase",
        }
    }
}

/// Options for [`GitHubApi::pr_merge`] (`gh pr merge`).
///
/// `#[non_exhaustive]`, so build it through the strategy constructors —
/// [`merge`](PrMerge::merge) / [`squash`](PrMerge::squash) /
/// [`rebase`](PrMerge::rebase), then [`auto`](PrMerge::auto) /
/// [`delete_branch`](PrMerge::delete_branch) — rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PrMerge {
    /// The merge strategy (exactly one of gh's `--merge`/`--squash`/`--rebase`).
    pub strategy: MergeStrategy,
    /// Enable auto-merge: merge once requirements are met (`--auto`).
    pub auto: bool,
    /// Delete the head branch after the merge (`--delete-branch`).
    pub delete_branch: bool,
}

impl PrMerge {
    /// Merge with a merge commit (`gh pr merge --merge`).
    pub fn merge() -> Self {
        Self::with(MergeStrategy::Merge)
    }

    /// Squash-merge (`gh pr merge --squash`).
    pub fn squash() -> Self {
        Self::with(MergeStrategy::Squash)
    }

    /// Rebase-merge (`gh pr merge --rebase`).
    pub fn rebase() -> Self {
        Self::with(MergeStrategy::Rebase)
    }

    fn with(strategy: MergeStrategy) -> Self {
        Self {
            strategy,
            auto: false,
            delete_branch: false,
        }
    }

    /// Merge automatically once requirements are met (`--auto`).
    pub fn auto(mut self) -> Self {
        self.auto = true;
        self
    }

    /// Delete the head branch after merging (`--delete-branch`).
    pub fn delete_branch(mut self) -> Self {
        self.delete_branch = true;
        self
    }
}

/// Options for [`GitHubApi::pr_close`] (`gh pr close`).
///
/// `#[non_exhaustive]`, so build it through [`PrClose::new`] and the chained
/// [`delete_branch`](PrClose::delete_branch) setter rather than a bare `bool`
/// (`pr_close(n, true)` doesn't say what `true` does).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrClose {
    /// Delete the head branch after closing the PR (`--delete-branch`).
    pub delete_branch: bool,
}

impl PrClose {
    /// Close the PR, leaving the head branch in place.
    pub fn new() -> Self {
        Self::default()
    }

    /// Delete the head branch after closing (`--delete-branch`).
    pub fn delete_branch(mut self) -> Self {
        self.delete_branch = true;
        self
    }
}

/// Options for [`GitHubApi::pr_create`] (`gh pr create`).
///
/// `#[non_exhaustive]`, so build it through [`PrCreate::new`] (title + body)
/// and the chained [`head`](PrCreate::head) / [`base`](PrCreate::base) setters
/// rather than a struct literal.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PrCreate {
    /// The PR title (`--title`).
    pub title: String,
    /// The PR body (`--body`).
    pub body: String,
    /// The source branch (`--head`); `None` = the current branch.
    pub head: Option<String>,
    /// The target branch (`--base`); `None` = the repo default.
    pub base: Option<String>,
    /// Labels to apply (`--label <name>`, repeated).
    pub labels: Vec<String>,
}

impl PrCreate {
    /// A PR with the given title and body, opened from the current branch into
    /// the repo default (`gh pr create --title <title> --body <body>`).
    pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            body: body.into(),
            head: None,
            base: None,
            labels: Vec::new(),
        }
    }

    /// Set the source branch (`--head`).
    pub fn head(mut self, head: impl Into<String>) -> Self {
        self.head = Some(head.into());
        self
    }

    /// Set the target branch (`--base`).
    pub fn base(mut self, base: impl Into<String>) -> Self {
        self.base = Some(base.into());
        self
    }

    /// Apply these labels when opening the pull request.
    pub fn labels(mut self, labels: impl Into<Vec<String>>) -> Self {
        self.labels = labels.into();
        self
    }
}

/// Options for [`GitHubApi::issue_create_with`] (`gh issue create`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct IssueCreate {
    /// The issue title (`--title`).
    pub title: String,
    /// The issue body (`--body`).
    pub body: String,
    /// Labels to apply (`--label <name>`, repeated).
    pub labels: Vec<String>,
}

impl IssueCreate {
    /// An issue with no labels.
    pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            body: body.into(),
            labels: Vec::new(),
        }
    }

    /// Apply these labels when opening the issue.
    pub fn labels(mut self, labels: impl Into<Vec<String>>) -> Self {
        self.labels = labels.into();
        self
    }
}

/// Options for [`GitHubApi::pr_edit`] (`gh pr edit`).
///
/// `#[non_exhaustive]`, so build it through [`PrEdit::new`] and the chained
/// [`title`](PrEdit::title) / [`body`](PrEdit::body) setters rather than a
/// struct literal. At least one of `title` or `body` must be `Some`; both
/// `None` is rejected by the facade before spawning (an explicit error, not a
/// silent no-op). An empty string is a real value — gh clears the field on
/// `--title ""` / `--body ""` — not a `None`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrEdit {
    /// The new title (`--title`); `None` leaves the title alone.
    pub title: Option<String>,
    /// The new body (`--body`); `None` leaves the body alone.
    pub body: Option<String>,
}

impl PrEdit {
    /// An edit that leaves both fields alone (the facade rejects both-`None`
    /// before reaching the wrapper). Start with this and add what you want to
    /// change via [`title`](PrEdit::title) / [`body`](PrEdit::body).
    pub fn new() -> Self {
        Self {
            title: None,
            body: None,
        }
    }

    /// Set the new title (`--title`).
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the new body (`--body`).
    pub fn body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(body.into());
        self
    }
}

impl Default for PrEdit {
    fn default() -> Self {
        Self::new()
    }
}

/// Which kind of review [`GitHubApi::pr_review`] submits — match on
/// [`ReviewAction::kind`] to read it back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReviewKind {
    /// Approve (`--approve`).
    Approve,
    /// Request changes (`--request-changes`).
    RequestChanges,
    /// A comment-only review (`--comment`).
    Comment,
}

/// What [`GitHubApi::pr_review`] submits (`gh pr review`).
///
/// The fields are **private** so the invariant holds by construction: gh
/// *requires* a body for request-changes/comment reviews, so those are only
/// reachable through [`request_changes`](ReviewAction::request_changes) /
/// [`comment`](ReviewAction::comment), which both take the body — an empty-body
/// request-changes is unrepresentable. Approve's body is optional
/// ([`approve`](ReviewAction::approve) starts with none; attach one with
/// [`with_body`](ReviewAction::with_body)). Read the parts back via
/// [`kind`](ReviewAction::kind) / [`body`](ReviewAction::body).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReviewAction {
    kind: ReviewKind,
    body: Option<String>,
}

impl ReviewAction {
    /// Approve, with no body (`--approve`). Attach one with
    /// [`with_body`](ReviewAction::with_body).
    pub fn approve() -> Self {
        Self {
            kind: ReviewKind::Approve,
            body: None,
        }
    }

    /// Request changes; gh requires the body
    /// (`--request-changes --body <body>`).
    pub fn request_changes(body: impl Into<String>) -> Self {
        Self {
            kind: ReviewKind::RequestChanges,
            body: Some(body.into()),
        }
    }

    /// A comment-only review; gh requires the body (`--comment --body <body>`).
    pub fn comment(body: impl Into<String>) -> Self {
        Self {
            kind: ReviewKind::Comment,
            body: Some(body.into()),
        }
    }

    /// Attach or replace the body — mainly to give an [`approve`](ReviewAction::approve)
    /// a message.
    pub fn with_body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Which kind of review this is.
    pub fn kind(&self) -> ReviewKind {
        self.kind
    }

    /// The review body, if any.
    pub fn body(&self) -> Option<&str> {
        self.body.as_deref()
    }
}

/// Options for [`GitHubApi::release_create`] (`gh release create`).
///
/// `#[non_exhaustive]`, so build it through [`ReleaseCreate::new`] (the tag) and
/// the chained [`title`](ReleaseCreate::title) / [`notes`](ReleaseCreate::notes) /
/// [`draft`](ReleaseCreate::draft) / [`prerelease`](ReleaseCreate::prerelease)
/// setters rather than a struct literal. Asset uploads are deliberately **out of
/// scope** — attach files with [`run`](GitHubApi::run) if you need them.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ReleaseCreate {
    /// The Git tag the release is attached to (gh's bare `<tag>` positional). If no
    /// such tag exists, `gh` creates one from the default branch's latest state.
    pub tag: String,
    /// The release title (`--title`); `None` lets gh default it (to the tag).
    pub title: Option<String>,
    /// The release notes / body (`--notes`); `None` leaves notes unset. Note that
    /// `gh` **requires** notes when run non-interactively, so a headless create
    /// should set this (or drive `--notes-file`/`--generate-notes` via
    /// [`run`](GitHubApi::run)) — otherwise gh errors asking for notes.
    pub notes: Option<String>,
    /// Save the release as a draft instead of publishing it (`--draft`).
    pub draft: bool,
    /// Mark the release as a prerelease (`--prerelease`).
    pub prerelease: bool,
}

impl ReleaseCreate {
    /// A published release on `tag`, with gh's default title/notes and neither
    /// draft nor prerelease set. Chain the setters to change any of those.
    pub fn new(tag: impl Into<String>) -> Self {
        Self {
            tag: tag.into(),
            title: None,
            notes: None,
            draft: false,
            prerelease: false,
        }
    }

    /// Set the release title (`--title`).
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the release notes / body (`--notes`).
    pub fn notes(mut self, notes: impl Into<String>) -> Self {
        self.notes = Some(notes.into());
        self
    }

    /// Save as a draft instead of publishing (`--draft`).
    pub fn draft(mut self) -> Self {
        self.draft = true;
        self
    }

    /// Mark the release as a prerelease (`--prerelease`).
    pub fn prerelease(mut self) -> Self {
        self.prerelease = true;
        self
    }
}

/// Options for [`GitHubApi::workflow_dispatch`] (`gh workflow run`), which fires a
/// `workflow_dispatch` event for a workflow that declares an `on: workflow_dispatch`
/// trigger.
///
/// `#[non_exhaustive]`, so build it through [`WorkflowDispatch::new`] (the workflow
/// selector) and the chained [`git_ref`](WorkflowDispatch::git_ref) /
/// [`field`](WorkflowDispatch::field) setters rather than a struct literal — the
/// `≥2 options → builder` rule (a target `ref` **and** any number of inputs) the
/// crate applies to its multi-option commands.
///
/// Inputs are emitted as `-f/--raw-field key=value` (the **raw** string form),
/// **not** gh's `-F/--field`: the latter interprets a value beginning with `@` as a
/// *file to read* (`gh help api`'s `@` syntax), so a caller-supplied value like
/// `@/etc/passwd` would exfiltrate a file into the dispatch. `--raw-field` treats
/// every value as a literal string, so an arbitrary input value (including a leading
/// `-` or `@`) is passed verbatim and safely.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct WorkflowDispatch {
    /// The workflow to run — its file name (`ci.yml` / `release.yml`) or its display
    /// name (gh's `[<workflow-id> | <workflow-name>]` positional). A bare positional,
    /// so it is flag-injection guarded (a leading `-` / empty value is refused before
    /// spawning), like [`release_view`](GitHubApi::release_view)'s tag.
    pub workflow: String,
    /// The branch or tag whose version of the workflow file to run (`--ref`); `None`
    /// runs the version on the repository's default branch. Rides in a flag-VALUE
    /// slot (gh consumes the next token verbatim, like `--branch`), so no positional
    /// guard applies.
    pub git_ref: Option<String>,
    /// `workflow_dispatch` inputs, as ordered `(key, value)` pairs. Each is emitted as
    /// `--raw-field key=value` (see the type-level note on why `--raw-field`, not
    /// `--field`). Keys must be non-empty after trimming and cannot contain `=` or
    /// NUL; values can be any string (a leading `-`/`@` is safe in this flag-VALUE
    /// slot).
    pub fields: Vec<(String, String)>,
}

impl WorkflowDispatch {
    /// Dispatch `workflow` on the repository's default branch with no inputs. Chain
    /// [`git_ref`](WorkflowDispatch::git_ref) to target a branch/tag and
    /// [`field`](WorkflowDispatch::field) to add inputs.
    pub fn new(workflow: impl Into<String>) -> Self {
        Self {
            workflow: workflow.into(),
            git_ref: None,
            fields: Vec::new(),
        }
    }

    /// Set the branch or tag whose version of the workflow file to run (`--ref`).
    /// (Named `git_ref` because `ref` is a Rust keyword.)
    pub fn git_ref(mut self, git_ref: impl Into<String>) -> Self {
        self.git_ref = Some(git_ref.into());
        self
    }

    /// Add one `workflow_dispatch` input (`--raw-field key=value`). Call it once per
    /// input; inputs are emitted in the order added.
    pub fn field(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.push((key.into(), value.into()));
        self
    }
}

/// Which jobs [`GitHubApi::run_rerun`] reruns (`gh run rerun`) — a direct argument
/// rather than a builder, since a single toggle doesn't reach the crate's
/// `≥2 options → builder` bar. `#[non_exhaustive]` so a future rerun mode is not a
/// breaking change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RerunScope {
    /// Rerun the **entire** run — every job (`gh run rerun <id>`).
    All,
    /// Rerun **only the failed jobs**, plus their dependencies
    /// (`gh run rerun <id> --failed`).
    FailedOnly,
}

/// What the installed `gh` binary supports, probed via
/// [`GitHubApi::capabilities`]. A value type — the client holds no state, so
/// probe once and keep the result (callers cache it). Mirrors
/// [`vcs_git::GitCapabilities`](../vcs_git/struct.GitCapabilities.html) /
/// [`vcs_jj::JjCapabilities`](../vcs_jj/struct.JjCapabilities.html).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct GitHubCapabilities {
    /// The binary's parsed version.
    pub version: GitHubVersion,
}

/// The oldest `gh` this crate is written against — **2.0.0**, the first release of
/// the modern `gh` line. Every command this crate's argv drives lives in 2.x: the
/// `--json` read surface (`pr`/`issue`/`repo`/`release … --json`, incl.
/// `pr checks --json`), the `pr edit` / `pr checkout` / `pr ready` lifecycle verbs,
/// and `api`. A `gh` from the 1.x line is missing parts of that surface, so gating
/// here lets [`ensure_supported`](GitHubCapabilities::ensure_supported) reject a
/// too-old binary up front with a clear message instead of letting an operation
/// fail deep inside gh with a cryptic `unknown command`/`unknown flag`.
const MIN_SUPPORTED: GitHubVersion = GitHubVersion {
    major: 2,
    minor: 0,
    patch: 0,
};

impl GitHubCapabilities {
    /// Whether the binary meets the supported floor (gh ≥ 2.0). Every typed
    /// operation on [`GitHubApi`] is guaranteed against this minimum.
    pub fn is_supported(&self) -> bool {
        self.version >= MIN_SUPPORTED
    }

    /// Error unless [`is_supported`](Self::is_supported) — a clear "needs gh ≥ 2.0,
    /// found 1.14.0" instead of a cryptic `unknown command`/`unknown flag` failure
    /// once an operation reaches a command the old binary lacks. The pre-flight
    /// check a caller runs before driving operations against an untrusted `gh`.
    pub fn ensure_supported(&self) -> Result<()> {
        if self.is_supported() {
            return Ok(());
        }
        Err(Error::spawn(
            BINARY,
            std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                format!(
                    "vcs-github requires gh >= {MIN_SUPPORTED}, found {}",
                    self.version
                ),
            ),
        ))
    }
}

/// The GitHub operations this crate exposes — the interface consumers code
/// against and mock in tests.
#[cfg_attr(feature = "mock", mockall::automock)]
#[async_trait::async_trait]
pub trait GitHubApi: Send + Sync {
    /// Run `gh <args>` **in the process's current directory**, returning trimmed
    /// stdout (throws on a non-zero exit). A raw escape hatch — you supply the whole
    /// argv, so pass `-R owner/repo` to target a specific repo. This method on the
    /// client is the **process-cwd** escape hatch; the `at(dir)` bound view's
    /// [`run`](GitHubAt::run) is instead **bound to `dir`** (it forwards to
    /// [`GitHub::run_in`], so `gh.at(dir).run(…)` runs in the bound repo's cwd, like
    /// [`api`](GitHubApi::api)). Use `gh.at(dir).run(…)` (or [`GitHub::run_in`]) for
    /// the bound repo (T-035).
    async fn run(&self, args: &[String]) -> Result<String>;
    /// Like [`GitHubApi::run`] but never errors on a non-zero exit — returns the
    /// captured [`ProcessResult`].
    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>>;
    /// Installed GitHub CLI version (`gh --version`).
    async fn version(&self) -> Result<String>;
    /// The installed binary's parsed version, as [`GitHubCapabilities`]
    /// (`gh --version`). A value type — probe once and keep it; an unrecognisable
    /// version banner is an [`ErrorReason::Parse`]. Gate an operation on a minimum `gh`
    /// with [`GitHubCapabilities::ensure_supported`].
    async fn capabilities(&self) -> Result<GitHubCapabilities>;
    /// Whether the user is authenticated (`gh auth status` exits zero). Reflects
    /// the exit code as a bool — any non-zero exit reads as `false`, never an
    /// error; only a spawn failure or timeout errors. Unscoped: it inspects
    /// *every* configured host, so a broken session for one host can make it
    /// report `false` even when the host you care about is fine — reach for
    /// [`auth_status_for`](GitHubApi::auth_status_for) to scope it.
    async fn auth_status(&self) -> Result<bool>;
    /// Whether the user is authenticated **for `host`** (`gh auth status
    /// --hostname <host>` exits zero) — the host-scoped twin of
    /// [`auth_status`](GitHubApi::auth_status). Scoping to the repository's host
    /// (build a [`GitHubHost`] from its remote, e.g.
    /// [`GitHubHost::from_remote_url`]) means a broken or absent session for
    /// *another* host can't turn this into a false negative for the host you
    /// target. Like `auth_status`, it folds only the exit code into the bool (any
    /// non-zero exit → `false`); a spawn failure or timeout still errors.
    /// **Defaulted** to `ErrorReason::Unsupported` so external implementers of the trait
    /// keep compiling when the crate bumps (only the `GitHub` concrete impl and the
    /// regenerated `MockGitHubApi` override it).
    #[allow(unused_variables)]
    async fn auth_status_for(&self, host: &GitHubHost) -> Result<bool> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "auth_status_for".into(),
        }))
    }
    /// The repository for `dir` (`gh repo view --json …`).
    async fn repo_view(&self, dir: &Path) -> Result<RepoView>;
    /// Pull requests for `dir` (`gh pr list --limit 100 --json …`). Returns up to
    /// 100 open PRs; use [`run`](GitHubApi::run) for more.
    async fn pr_list(&self, dir: &Path) -> Result<Vec<PullRequest>>;
    /// Pull requests selected by `spec` (`--state` / `--limit`). A zero limit is
    /// rejected before spawning. **Defaulted** to `ErrorReason::Unsupported` so
    /// external trait implementers keep compiling when the crate bumps.
    #[allow(unused_variables)]
    async fn pr_list_with(&self, dir: &Path, spec: PrList) -> Result<Vec<PullRequest>> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "pr_list_with".into(),
        }))
    }
    /// Pull requests whose source branch is `head`, in any state — open, closed,
    /// or merged (`gh pr list --head <head> --state all --limit 100 --json …`).
    /// Empty when none match; returns up to 100. A flag-like or empty `head` is
    /// rejected before spawning so an untrusted branch cannot alter the command.
    ///
    /// **Defaulted** to `ErrorReason::Unsupported` so external trait implementers keep
    /// compiling when the crate bumps.
    #[allow(unused_variables)]
    async fn pr_list_for_source_branch(&self, dir: &Path, head: &str) -> Result<Vec<PullRequest>> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "pr_list_for_source_branch".into(),
        }))
    }
    /// Pull requests that merge `head` into `base`, in any state — open, closed,
    /// or merged (`gh pr list --head <head> --base <base> --state all --limit 100
    /// --json …`). Each carries its title, URL, and `state`. Empty when none
    /// match; returns up to 100 (use [`run`](GitHubApi::run) for more).
    async fn pr_list_for_branch(
        &self,
        dir: &Path,
        head: &str,
        base: &str,
    ) -> Result<Vec<PullRequest>>;
    /// A single pull request by number (`gh pr view <n> --json …`).
    async fn pr_view(&self, dir: &Path, number: u64) -> Result<PullRequest>;
    /// Issues for `dir` (`gh issue list --limit 100 --json …`). Returns up to 100
    /// open issues; use [`run`](GitHubApi::run) for more.
    async fn issue_list(&self, dir: &Path) -> Result<Vec<Issue>>;
    /// Issues selected by `spec` (`--state` / `--limit`). A zero limit is
    /// rejected before spawning. **Defaulted** to `ErrorReason::Unsupported` so
    /// external trait implementers keep compiling when the crate bumps.
    #[allow(unused_variables)]
    async fn issue_list_with(&self, dir: &Path, spec: IssueList) -> Result<Vec<Issue>> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "issue_list_with".into(),
        }))
    }
    /// Open a pull request, returning its URL (`gh pr create`) — see
    /// [`PrCreate`] for the title/body and the optional `head` (source branch;
    /// `None` = current branch) / `base` (target; `None` = repo default).
    async fn pr_create(&self, dir: &Path, spec: PrCreate) -> Result<String>;
    /// Raw GitHub REST/GraphQL response body (`gh api <endpoint>`), run in `dir` so
    /// a relative endpoint's `{owner}/{repo}` placeholder resolves against the bound
    /// repository — not whatever repo the process's current directory happens to be in.
    async fn api(&self, dir: &Path, endpoint: &str) -> Result<String>;

    // --- PR lifecycle ----------------------------------------------------

    /// Merge a pull request (`gh pr merge <n> --merge|--squash|--rebase
    /// [--auto] [--delete-branch]`) — see [`PrMerge`].
    async fn pr_merge(&self, dir: &Path, number: u64, merge: PrMerge) -> Result<()>;
    /// Mark a draft pull request as ready for review (`gh pr ready <n>`).
    async fn pr_mark_ready(&self, dir: &Path, number: u64) -> Result<()>;
    /// Close a pull request without merging (`gh pr close <n>
    /// [--delete-branch]`); see [`PrClose`].
    async fn pr_close(&self, dir: &Path, number: u64, spec: PrClose) -> Result<()>;
    /// Add labels to an existing pull request (`gh pr edit <n> --add-label <name>`).
    #[allow(unused_variables)]
    async fn pr_add_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "pr_add_labels".into(),
        }))
    }
    /// Remove labels from an existing pull request (`gh pr edit <n> --remove-label <name>`).
    #[allow(unused_variables)]
    async fn pr_remove_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "pr_remove_labels".into(),
        }))
    }
    /// Check out a pull request's branch into the working copy at `dir`
    /// (`gh pr checkout <n>`) — the head branch is fetched and switched to, so a
    /// subsequent build/test/edit runs against the PR locally. Mutates the working
    /// copy. **Defaulted** to `ErrorReason::Unsupported` so external implementers of the
    /// trait keep compiling when the crate bumps (only the `GitHub` concrete impl
    /// and the regenerated `MockGitHubApi` override it).
    #[allow(unused_variables)]
    async fn pr_checkout(&self, dir: &Path, number: u64) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "pr_checkout".into(),
        }))
    }
    /// The PR's checks (`gh pr checks <n> --json …`). gh signals the overall
    /// outcome through its exit code — 0 all passed, 8 still pending, 1 some
    /// failed — and emits the same JSON either way, so all three return the
    /// parsed list; branch on each entry's [`bucket`](CheckRun::bucket). A PR
    /// with no checks at all yields an empty list (gh's "no checks reported"
    /// exit). Any other exit (no such PR, auth required, …) errors.
    async fn pr_checks(&self, dir: &Path, number: u64) -> Result<Vec<CheckRun>>;
    /// Submit a review (`gh pr review <n> --approve|--request-changes|--comment
    /// [--body <body>]`) — see [`ReviewAction`] (request-changes/comment carry a
    /// required body by construction).
    async fn pr_review(&self, dir: &Path, number: u64, action: ReviewAction) -> Result<()>;
    /// Add a conversation comment, returning its URL
    /// (`gh pr comment <n> --body <body>`).
    async fn pr_comment(&self, dir: &Path, number: u64, body: &str) -> Result<String>;
    /// Edit a pull request's title and/or body
    /// (`gh pr edit <n> [--title <title>] [--body <body>]`). At least one of
    /// `title` or `body` must be `Some` — the facade rejects both-`None`
    /// before reaching the wrapper, so the default implementation is
    /// unreachable in normal use. **Defaulted** to `ErrorReason::Unsupported` so
    /// external implementers of the trait keep compiling when the crate
    /// bumps.
    #[allow(unused_variables)]
    async fn pr_edit(&self, dir: &Path, number: u64, edit: PrEdit) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "pr_edit".into(),
        }))
    }
    /// The PR's submitted reviews and conversation comments
    /// (`gh pr view <n> --json reviews,comments`).
    async fn pr_feedback(&self, dir: &Path, number: u64) -> Result<PrFeedback>;
    /// The PR's diff, one [`FileDiff`] per changed file (`gh pr diff <n>
    /// --color never`), through the same unified-diff parser
    /// [`vcs-git`](https://docs.rs/vcs-git)/[`vcs-jj`](https://docs.rs/vcs-jj)
    /// use — `gh pr diff` emits the same git-format diff `git diff` does.
    async fn pr_diff(&self, dir: &Path, number: u64) -> Result<Vec<FileDiff>>;

    // --- Actions workflows and runs ---------------------------------------

    /// Active workflow definitions (`gh workflow list --limit 50 --json …`).
    /// Disabled workflows are hidden; use [`workflow_list_with`](GitHubApi::workflow_list_with)
    /// with [`WorkflowList::all`] to include them. **Defaulted** to
    /// `ErrorReason::Unsupported` so external trait implementers keep compiling.
    #[allow(unused_variables)]
    async fn workflow_list(&self, dir: &Path) -> Result<Vec<Workflow>> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "workflow_list".into(),
        }))
    }
    /// Workflow definitions selected by `spec` (`--all` / `--limit`). A zero
    /// limit is rejected before spawning. **Defaulted** to
    /// `ErrorReason::Unsupported` so external trait implementers keep compiling.
    #[allow(unused_variables)]
    async fn workflow_list_with(&self, dir: &Path, spec: WorkflowList) -> Result<Vec<Workflow>> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "workflow_list_with".into(),
        }))
    }
    /// Resolve one workflow by numeric id, display name (case-insensitive), or
    /// workflow filename/path. Current `gh workflow view` has no `--json` mode,
    /// so this resolves against the complete disabled-inclusive JSON inventory
    /// from `gh workflow list` rather than scraping human-readable output.
    /// **Defaulted** to `ErrorReason::Unsupported` so external trait implementers
    /// keep compiling.
    #[allow(unused_variables)]
    async fn workflow_view(&self, dir: &Path, selector: &str) -> Result<Workflow> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "workflow_view".into(),
        }))
    }

    /// Recent workflow runs, newest first (`gh run list --limit <n>
    /// [--branch <b>] --json …`). `branch` is an owned `Option<String>` to keep
    /// the trait `mockall`-friendly.
    async fn run_list(
        &self,
        dir: &Path,
        limit: u64,
        branch: Option<String>,
    ) -> Result<Vec<WorkflowRun>>;
    /// A single workflow run by id (`gh run view <id> --json …`); the id is
    /// [`WorkflowRun::database_id`].
    async fn run_view(&self, dir: &Path, id: u64) -> Result<WorkflowRun>;
    /// Block until the run finishes, then return its final state
    /// (`gh run watch <id>`, then a `run view`). Inspect
    /// [`conclusion`](WorkflowRun::conclusion) for the outcome — exit codes
    /// can't distinguish a failed run from a cancelled one.
    ///
    /// **Blocks for the whole run.** A client
    /// [`default_timeout`](GitHub::default_timeout) kills the watch when it
    /// elapses (`ErrorReason::Timeout`) — drive this from a client with no (or a
    /// generous) timeout.
    async fn run_watch(&self, dir: &Path, id: u64) -> Result<WorkflowRun>;
    /// Fire a `workflow_dispatch` event for a workflow, driven by a
    /// [`WorkflowDispatch`] spec (the workflow selector plus an optional target `ref`
    /// and inputs) — the whole span kept on one line so rustdoc doesn't read the
    /// angle-bracket placeholders as HTML:
    /// `gh workflow run <workflow> [--ref <ref>] [--raw-field key=value …]`.
    /// The workflow file must declare an `on: workflow_dispatch` trigger.
    ///
    /// Returns `Result<()>`, **not** a run URL: the underlying GitHub API replies
    /// `204 No Content` with no run identifier (the dispatch is asynchronous — the
    /// run may not exist yet), so any URL gh prints is best-effort. To find the run
    /// this started, poll [`run_list`](GitHubApi::run_list) for the workflow/branch.
    /// Exit codes follow gh's convention (`gh help exit-codes`): **0** dispatched,
    /// **1** on failure — e.g. an unknown workflow (`HTTP 404: workflow … not found`),
    /// a workflow lacking a `workflow_dispatch` trigger, or an unknown input —
    /// surfaced as [`ErrorReason::Exit`]; **4** if `gh` is not authenticated.
    ///
    /// **Defaulted** to `ErrorReason::Unsupported` so external implementers of the trait
    /// keep compiling when the crate bumps (only the `GitHub` concrete impl and the
    /// regenerated `MockGitHubApi` override it).
    #[allow(unused_variables)]
    async fn workflow_dispatch(&self, dir: &Path, spec: WorkflowDispatch) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "workflow_dispatch".into(),
        }))
    }
    /// Rerun a completed workflow run (`gh run rerun <id> [--failed]`); pass a
    /// [`RerunScope`] to rerun every job ([`All`](RerunScope::All)) or only the
    /// failed jobs and their dependencies ([`FailedOnly`](RerunScope::FailedOnly)).
    /// The id is [`WorkflowRun::database_id`]; being a `u64`, the bare positional can
    /// never look like a flag — nothing to guard.
    ///
    /// gh queues the rerun and returns; the new run is a *separate*
    /// [`WorkflowRun`] — poll [`run_list`](GitHubApi::run_list) or
    /// [`run_watch`](GitHubApi::run_watch) for it. Exit codes follow gh's convention
    /// (`gh help exit-codes`): **0** queued, **1** on failure — e.g. no such run
    /// (`failed to get run: HTTP 404`), or `--failed` on a run with no failed jobs —
    /// as [`ErrorReason::Exit`]; **4** if unauthenticated.
    ///
    /// **Defaulted** to `ErrorReason::Unsupported` so external implementers keep compiling
    /// when the crate bumps.
    #[allow(unused_variables)]
    async fn run_rerun(&self, dir: &Path, id: u64, scope: RerunScope) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "run_rerun".into(),
        }))
    }
    /// Cancel an in-progress workflow run (`gh run cancel <id>`). The id is
    /// [`WorkflowRun::database_id`]; being a `u64`, the bare positional can never look
    /// like a flag — nothing to guard.
    ///
    /// Cancellation is a *request* — gh returns once GitHub accepts it, before jobs
    /// actually wind down; read the run's terminal state with
    /// [`run_view`](GitHubApi::run_view)/[`run_watch`](GitHubApi::run_watch) (a
    /// cancelled run's [`conclusion`](WorkflowRun::conclusion) is `"cancelled"`). Exit
    /// codes follow gh's convention (`gh help exit-codes`): **0** accepted, **1** on
    /// failure — e.g. no such run (`Could not find any workflow run with ID …`), or a
    /// run that is already completed (`Cannot cancel a workflow run that is
    /// completed`) — as [`ErrorReason::Exit`]; **4** if unauthenticated.
    ///
    /// **Defaulted** to `ErrorReason::Unsupported` so external implementers keep compiling
    /// when the crate bumps.
    #[allow(unused_variables)]
    async fn run_cancel(&self, dir: &Path, id: u64) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "run_cancel".into(),
        }))
    }

    // --- Issues / releases ---------------------------------------------------

    /// Open an issue, returning its URL
    /// (`gh issue create --title <title> --body <body>`).
    async fn issue_create(&self, dir: &Path, title: &str, body: &str) -> Result<String>;
    /// Open an issue from an extensible spec, including labels. The default keeps
    /// old external trait implementations source-compatible and supports the
    /// label-free case through [`issue_create`](GitHubApi::issue_create).
    async fn issue_create_with(&self, dir: &Path, spec: IssueCreate) -> Result<String> {
        if spec.labels.is_empty() {
            self.issue_create(dir, &spec.title, &spec.body).await
        } else {
            Err(Error::from(ErrorReason::Unsupported {
                operation: "issue_create_with(labels)".into(),
            }))
        }
    }
    /// Add labels to an existing issue (`gh issue edit <n> --add-label <name>`).
    #[allow(unused_variables)]
    async fn issue_add_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "issue_add_labels".into(),
        }))
    }
    /// Remove labels from an existing issue (`gh issue edit <n> --remove-label <name>`).
    #[allow(unused_variables)]
    async fn issue_remove_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "issue_remove_labels".into(),
        }))
    }
    /// A single issue by number, with `body`/`url` filled
    /// (`gh issue view <n> --json …`).
    async fn issue_view(&self, dir: &Path, number: u64) -> Result<Issue>;
    /// Close an issue (`gh issue close <n>`). `number` is a `u64`, so the bare
    /// positional can never look like a flag — nothing to guard. **Defaulted** to
    /// `ErrorReason::Unsupported` so external implementers of the trait keep compiling
    /// when the crate bumps (only the `GitHub` concrete impl and the regenerated
    /// `MockGitHubApi` override it).
    #[allow(unused_variables)]
    async fn issue_close(&self, dir: &Path, number: u64) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "issue_close".into(),
        }))
    }
    /// Reopen a closed issue (`gh issue reopen <n>`). `number` is a `u64`, so the
    /// bare positional can never look like a flag — nothing to guard. **Defaulted**
    /// to `ErrorReason::Unsupported` so external implementers of the trait keep compiling
    /// when the crate bumps (only the `GitHub` concrete impl and the regenerated
    /// `MockGitHubApi` override it).
    #[allow(unused_variables)]
    async fn issue_reopen(&self, dir: &Path, number: u64) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "issue_reopen".into(),
        }))
    }
    /// Add a comment to an issue, returning its URL
    /// (`gh issue comment <n> --body <body>`). The body rides in a flag-VALUE slot,
    /// so a leading `-` is safe and no argv guard is needed (same as
    /// [`pr_comment`](GitHubApi::pr_comment)). **Defaulted** to `ErrorReason::Unsupported`
    /// so external implementers of the trait keep compiling when the crate bumps
    /// (only the `GitHub` concrete impl and the regenerated `MockGitHubApi` override
    /// it).
    #[allow(unused_variables)]
    async fn issue_comment(&self, dir: &Path, number: u64, body: &str) -> Result<String> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "issue_comment".into(),
        }))
    }
    /// Releases, newest first (`gh release list --limit 100 --json …`); `body`/`url`
    /// are not fetched here — use [`release_view`](GitHubApi::release_view).
    /// Returns up to 100 releases; use [`run`](GitHubApi::run) for more.
    async fn release_list(&self, dir: &Path) -> Result<Vec<Release>>;
    /// A single release by tag, with `body`/`url` filled
    /// (`gh release view <tag> --json …`). gh reports `is_latest` only from
    /// [`release_list`](GitHubApi::release_list); here it defaults to `false`.
    async fn release_view(&self, dir: &Path, tag: &str) -> Result<Release>;
    /// Create a release, returning its URL
    /// (`gh release create <tag> [--title <title>] [--notes <notes>] [--draft] [--prerelease]`)
    /// — see [`ReleaseCreate`].
    /// gh creates the git tag from the default branch's latest state if it doesn't
    /// yet exist. Asset uploads are out of scope (attach files with
    /// [`run`](GitHubApi::run)). **Defaulted** to `ErrorReason::Unsupported` so external
    /// implementers of the trait keep compiling when the crate bumps (only the
    /// `GitHub` concrete impl and the regenerated `MockGitHubApi` override it).
    #[allow(unused_variables)]
    async fn release_create(&self, dir: &Path, spec: ReleaseCreate) -> Result<String> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "release_create".into(),
        }))
    }
    /// Delete a release by tag (`gh release delete <tag> --yes`). `--yes` skips gh's
    /// confirmation prompt so a headless caller never hangs. Deletes the release
    /// only, not the underlying git tag (use `gh release delete --cleanup-tag` via
    /// [`run`](GitHubApi::run) for that). **Defaulted** to `ErrorReason::Unsupported` so
    /// external implementers keep compiling when the crate bumps.
    #[allow(unused_variables)]
    async fn release_delete(&self, dir: &Path, tag: &str) -> Result<()> {
        Err(Error::from(ErrorReason::Unsupported {
            operation: "release_delete".into(),
        }))
    }
}

vcs_cli_support::managed_client! {
    /// The real GitHub client. Generic over the [`ProcessRunner`] so tests can inject
    /// a fake process executor; [`GitHub::new`] uses the real job-backed runner.
    ///
    /// Wraps a [`ManagedClient`](vcs_cli_support::ManagedClient). By default it authenticates through `gh`'s own
    /// ambient login; attach a [`CredentialProvider`] with
    /// [`with_credentials`](GitHub::with_credentials) to supply a token per operation
    /// — it is injected as `GH_TOKEN` on every `gh` invocation (or, after
    /// [`with_host`](GitHub::with_host) targets a GitHub Enterprise Server host,
    /// as `GH_ENTERPRISE_TOKEN` — the variable `gh` reads for that host).
    pub struct GitHub => BINARY, token_env = (CredentialService::GitHub, "GH_TOKEN")
}

impl<R: ProcessRunner> GitHub<R> {
    /// Supply credentials per operation via a [`CredentialProvider`] — opt-in, off
    /// by default (ambient `gh` auth). The resolved token is injected as `GH_TOKEN`
    /// on every `gh` invocation, overriding the ambient login for this client.
    #[must_use]
    pub fn with_credentials(mut self, provider: Arc<dyn CredentialProvider>) -> Self {
        self.core = self.core.with_credentials(provider);
        self
    }

    /// Convenience for the common case: authenticate with a single static `token`,
    /// injected as `GH_TOKEN`. Shorthand for
    /// `with_credentials(Arc::new(StaticCredential::token(token)))`.
    #[must_use]
    pub fn with_token(self, token: impl Into<Secret>) -> Self {
        self.with_credentials(Arc::new(StaticCredential::token(token)))
    }

    /// Convenience: read the token from environment variable `var` at request time
    /// (injected as `GH_TOKEN`); if `var` is unset/empty, fall back to ambient auth.
    /// Shorthand for `with_credentials(Arc::new(EnvToken::new(var)))`.
    #[must_use]
    pub fn with_env_token(self, var: impl Into<String>) -> Self {
        self.with_credentials(Arc::new(EnvToken::new(var)))
    }

    /// Bind this client to a GitHub `host`, so a supplied credential is injected
    /// into the environment variable `gh` reads for **that** host, and gh's default
    /// host is set accordingly:
    ///
    /// - **github.com** ([`GitHubHost::github_com`]) → the token goes to `GH_TOKEN`
    ///   (the SaaS default, unchanged) and `GH_HOST` is `github.com`.
    /// - a **GitHub Enterprise Server** host → the token goes to
    ///   `GH_ENTERPRISE_TOKEN` (the variable `gh` uses for a non-github.com host)
    ///   and `GH_HOST` is set to that host, so gh's non-repo commands resolve
    ///   against it. The github.com `GH_TOKEN` is **not** set, so an enterprise
    ///   secret never lands in the github.com token env (nor vice versa).
    ///
    /// Compose with [`with_credentials`](GitHub::with_credentials) /
    /// [`with_token`](GitHub::with_token) / [`with_env_token`](GitHub::with_env_token)
    /// in either order — the host selects the env var, the provider supplies the
    /// secret. The bound host also travels in each operation's [`CredentialRequest`],
    /// so a **host-keyed** provider returns the secret for *this* host and never a
    /// neighbouring instance's. For several hosts, build **one client per host**:
    /// each injects only its own host's token, so a broken or missing credential for
    /// one host can't leak into another. Without a host binding the client behaves
    /// exactly as before — github.com semantics, credential injected as `GH_TOKEN`,
    /// and the request carries no host (a host-keyed provider that can't place it
    /// defers to ambient auth).
    ///
    /// `GH_HOST` only steers gh's host inference for commands with **no repository
    /// context**; a repo-scoped command still resolves its host from the working
    /// directory's remote, so binding a host does not override a repo you point a
    /// method at — use a host-bound client with repositories on that host.
    #[must_use]
    pub fn with_host(mut self, host: GitHubHost) -> Self {
        self.core = self
            .core
            .with_token_env(CredentialService::GitHub, host.token_env_var())
            // Carry the (canonical, lower-cased) host into every operation's
            // `CredentialRequest`, so a host-keyed `CredentialProvider` resolves the
            // secret for *this* host and nothing else — one instance's token can't
            // land in another host's `gh` command.
            .with_expected_host(host.as_str())
            .default_env("GH_HOST", host.as_str());
        self
    }
}

#[async_trait::async_trait]
impl<R: ProcessRunner> GitHubApi for GitHub<R> {
    async fn run(&self, args: &[String]) -> Result<String> {
        self.core.run(args).await
    }

    async fn run_raw(&self, args: &[String]) -> Result<ProcessResult<String>> {
        self.core.output_string(args).await
    }

    async fn version(&self) -> Result<String> {
        self.core.run(["--version"]).await
    }

    async fn capabilities(&self) -> Result<GitHubCapabilities> {
        let raw = self.version().await?;
        let version = parse::parse_gh_version(&raw).ok_or_else(|| {
            Error::parse(
                BINARY,
                format!("unrecognisable `gh --version` output: {raw:?}"),
            )
        })?;
        Ok(GitHubCapabilities { version })
    }

    async fn auth_status(&self) -> Result<bool> {
        // `gh auth status` exits 0 when authenticated, non-zero when not — an
        // exit-code answer. `exit_code` reads the exit code without erroring on a
        // non-zero one (a spawn failure or timeout still errors), so ANY non-zero
        // exit — not just the documented 1 — maps to "not authenticated" rather
        // than surfacing as an error. `probe` would reject an unusual exit code.
        Ok(self.core.exit_code(["auth", "status"]).await? == 0)
    }

    async fn auth_status_for(&self, host: &GitHubHost) -> Result<bool> {
        // `--hostname <host>` scopes the probe to one host: `gh auth status` with
        // no hostname inspects *every* configured host, so a single broken session
        // (a different host, an expired enterprise login) can flip the exit code
        // non-zero — a false negative for the host we actually target. Same
        // exit-code-as-bool contract as `auth_status` (a spawn failure or timeout
        // still errors — see `exit_code`). `host` is a validated `GitHubHost`, so
        // the `--hostname` value can never be flag-like or empty.
        Ok(self
            .core
            .exit_code(["auth", "status", "--hostname", host.as_str()])
            .await?
            == 0)
    }

    async fn repo_view(&self, dir: &Path) -> Result<RepoView> {
        self.core
            .try_parse(
                self.core
                    .command_in(dir, ["repo", "view", "--json", REPO_FIELDS]),
                parse::parse_repo,
            )
            .await
    }

    async fn pr_list(&self, dir: &Path) -> Result<Vec<PullRequest>> {
        self.pr_list_with(dir, PrList::default()).await
    }

    async fn pr_list_with(&self, dir: &Path, spec: PrList) -> Result<Vec<PullRequest>> {
        reject_zero_limit("pr_list_with", spec.limit)?;
        let limit = spec.limit.to_string();
        self.core
            .try_parse(
                self.core.command_in(
                    dir,
                    [
                        "pr",
                        "list",
                        "--state",
                        spec.state.as_arg(),
                        "--limit",
                        limit.as_str(),
                        "--json",
                        PR_FIELDS,
                    ],
                ),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn pr_list_for_branch(
        &self,
        dir: &Path,
        head: &str,
        base: &str,
    ) -> Result<Vec<PullRequest>> {
        reject_flag_like("head", head)?;
        reject_flag_like("base", base)?;
        // `--state all` so a closed/merged PR for this branch pair is reported
        // too, not just open ones (gh's default); the caller filters on `state`.
        self.core
            .try_parse(
                self.core.command_in(
                    dir,
                    [
                        "pr", "list", "--head", head, "--base", base, "--state", "all", "--limit",
                        "100", "--json", PR_FIELDS,
                    ],
                ),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn pr_list_for_source_branch(&self, dir: &Path, head: &str) -> Result<Vec<PullRequest>> {
        reject_flag_like("head", head)?;
        self.core
            .try_parse(
                self.core.command_in(
                    dir,
                    [
                        "pr", "list", "--head", head, "--state", "all", "--limit", "100", "--json",
                        PR_FIELDS,
                    ],
                ),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn pr_view(&self, dir: &Path, number: u64) -> Result<PullRequest> {
        let n = number.to_string();
        self.core
            .try_parse(
                self.core
                    .command_in(dir, ["pr", "view", n.as_str(), "--json", PR_FIELDS]),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn issue_list(&self, dir: &Path) -> Result<Vec<Issue>> {
        self.issue_list_with(dir, IssueList::default()).await
    }

    async fn issue_list_with(&self, dir: &Path, spec: IssueList) -> Result<Vec<Issue>> {
        reject_zero_limit("issue_list_with", spec.limit)?;
        let limit = spec.limit.to_string();
        self.core
            .try_parse(
                self.core.command_in(
                    dir,
                    [
                        "issue",
                        "list",
                        "--state",
                        spec.state.as_arg(),
                        "--limit",
                        limit.as_str(),
                        "--json",
                        ISSUE_LIST_FIELDS,
                    ],
                ),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn pr_create(&self, dir: &Path, spec: PrCreate) -> Result<String> {
        let mut args = vec![
            "pr",
            "create",
            "--title",
            spec.title.as_str(),
            "--body",
            spec.body.as_str(),
        ];
        if let Some(head) = spec.head.as_deref() {
            args.push("--head");
            args.push(head);
        }
        if let Some(base) = spec.base.as_deref() {
            args.push("--base");
            args.push(base);
        }
        if !spec.labels.is_empty() {
            reject_invalid_labels("pr_create", &spec.labels)?;
            for label in &spec.labels {
                args.push("--label");
                args.push(label);
            }
        }
        self.core.run(self.core.command_in(dir, args)).await
    }

    async fn api(&self, dir: &Path, endpoint: &str) -> Result<String> {
        reject_flag_like("endpoint", endpoint)?;
        self.core
            .run(self.core.command_in(dir, ["api", endpoint]))
            .await
    }

    async fn pr_merge(&self, dir: &Path, number: u64, merge: PrMerge) -> Result<()> {
        let n = number.to_string();
        let mut args = vec!["pr", "merge", n.as_str(), merge.strategy.flag()];
        if merge.auto {
            args.push("--auto");
        }
        if merge.delete_branch {
            args.push("--delete-branch");
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn pr_mark_ready(&self, dir: &Path, number: u64) -> Result<()> {
        let n = number.to_string();
        self.core
            .run_unit(self.core.command_in(dir, ["pr", "ready", n.as_str()]))
            .await
    }

    async fn pr_close(&self, dir: &Path, number: u64, spec: PrClose) -> Result<()> {
        let n = number.to_string();
        let mut args = vec!["pr", "close", n.as_str()];
        if spec.delete_branch {
            args.push("--delete-branch");
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn pr_checkout(&self, dir: &Path, number: u64) -> Result<()> {
        // `number` is a `u64`, so it can never look like a flag — nothing to
        // guard with `reject_flag_like`. `gh pr checkout` fetches the PR's head
        // branch and switches the working copy to it (no structured output).
        let n = number.to_string();
        self.core
            .run_unit(self.core.command_in(dir, ["pr", "checkout", n.as_str()]))
            .await
    }

    async fn pr_checks(&self, dir: &Path, number: u64) -> Result<Vec<CheckRun>> {
        let n = number.to_string();
        let res = self
            .core
            .output_string(
                self.core
                    .command_in(dir, ["pr", "checks", n.as_str(), "--json", CHECK_FIELDS]),
            )
            .await?;
        match res.code() {
            // gh's exit code carries the *overall* outcome (0 = all pass,
            // 8 = pending, 1 = some failed) but prints the same JSON for all
            // three — parse it and let the caller branch on each `bucket`.
            // A parse failure here is a real schema problem and must surface
            // as `ErrorReason::Parse`, not be masked by the exit code.
            Some(0) => vcs_cli_support::json::from_json(BINARY, res.stdout()),
            Some(1 | 8) if !res.stdout().trim().is_empty() => {
                vcs_cli_support::json::from_json(BINARY, res.stdout())
            }
            // gh exits 1 with NO JSON for a PR that simply has no checks — the
            // one bare non-zero we read as an empty list (cf. jj's
            // `resolve_list` and its "No conflicts" exit). Matched
            // case-insensitively so a capitalization tweak in gh's wording
            // ("no checks reported on the 'X' branch") doesn't turn the empty case
            // into a hard error.
            _ if res
                .stderr()
                .to_ascii_lowercase()
                .contains("no checks reported") =>
            {
                Ok(Vec::new())
            }
            // Anything else (no such PR, auth required, timeout, signal…) is a
            // genuine failure; `ensure_success` builds the faithful error.
            _ => {
                let _ = res.ensure_success()?;
                Ok(Vec::new()) // unreachable: a non-zero exit always errors above.
            }
        }
    }

    async fn pr_review(&self, dir: &Path, number: u64, action: ReviewAction) -> Result<()> {
        let n = number.to_string();
        let mut args = vec!["pr", "review", n.as_str()];
        args.push(match action.kind() {
            ReviewKind::Approve => "--approve",
            ReviewKind::RequestChanges => "--request-changes",
            ReviewKind::Comment => "--comment",
        });
        if let Some(body) = action.body() {
            args.push("--body");
            args.push(body);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn pr_comment(&self, dir: &Path, number: u64, body: &str) -> Result<String> {
        // `--body` is mandatory here: without it gh falls back to an
        // interactive prompt, which would hang a headless run.
        let n = number.to_string();
        self.core
            .run(
                self.core
                    .command_in(dir, ["pr", "comment", n.as_str(), "--body", body]),
            )
            .await
    }

    async fn pr_edit(&self, dir: &Path, number: u64, edit: PrEdit) -> Result<()> {
        // `--title` and `--body` are flag-VALUE positions: gh consumes the
        // next token verbatim, so the leading-`-` check is not needed here.
        // The facade rejects both-`None` before reaching this; an empty string
        // is intentional (clears the field). We still skip absent fields so
        // the argv doesn't carry a stray `--title` with no value.
        let n = number.to_string();
        let mut args = vec!["pr", "edit", n.as_str()];
        if let Some(title) = edit.title.as_deref() {
            args.push("--title");
            args.push(title);
        }
        if let Some(body) = edit.body.as_deref() {
            args.push("--body");
            args.push(body);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn pr_feedback(&self, dir: &Path, number: u64) -> Result<PrFeedback> {
        let n = number.to_string();
        self.core
            .try_parse(
                self.core.command_in(
                    dir,
                    ["pr", "view", n.as_str(), "--json", "reviews,comments"],
                ),
                parse::parse_feedback,
            )
            .await
    }

    async fn pr_diff(&self, dir: &Path, number: u64) -> Result<Vec<FileDiff>> {
        self.pr_diff_within(dir, number, self.core.output_budget())
            .await
    }

    async fn workflow_list(&self, dir: &Path) -> Result<Vec<Workflow>> {
        self.workflow_list_with(dir, WorkflowList::default()).await
    }

    async fn workflow_list_with(&self, dir: &Path, spec: WorkflowList) -> Result<Vec<Workflow>> {
        reject_zero_limit("workflow_list_with", spec.limit)?;
        let limit = spec.limit.to_string();
        let mut args = vec!["workflow", "list", "--limit", limit.as_str()];
        if spec.include_disabled {
            args.push("--all");
        }
        args.extend(["--json", WORKFLOW_FIELDS]);
        self.core
            .try_parse(self.core.command_in(dir, args), |s| {
                vcs_cli_support::json::from_json(BINARY, s)
            })
            .await
    }

    async fn workflow_view(&self, dir: &Path, selector: &str) -> Result<Workflow> {
        if selector.is_empty() {
            return resolve_workflow(Vec::new(), selector);
        }
        // `gh workflow view` deliberately has no JSON exporter. `workflow list`
        // delegates to gh's paginated Actions workflow API and exposes exactly the
        // typed fields we need, so request an effectively-unbounded inventory and
        // resolve the same id/name/file selector forms without scraping text.
        let workflows = self
            .workflow_list_with(
                dir,
                WorkflowList::new().all().limit(WORKFLOW_VIEW_LOOKUP_LIMIT),
            )
            .await?;
        resolve_workflow(workflows, selector)
    }

    async fn run_list(
        &self,
        dir: &Path,
        limit: u64,
        branch: Option<String>,
    ) -> Result<Vec<WorkflowRun>> {
        let limit = limit.to_string();
        let mut args = vec!["run", "list", "--limit", limit.as_str()];
        if let Some(branch) = branch.as_deref() {
            args.push("--branch");
            args.push(branch);
        }
        args.extend(["--json", RUN_FIELDS]);
        self.core
            .try_parse(self.core.command_in(dir, args), |s| {
                vcs_cli_support::json::from_json(BINARY, s)
            })
            .await
    }

    async fn run_view(&self, dir: &Path, id: u64) -> Result<WorkflowRun> {
        let id = id.to_string();
        self.core
            .try_parse(
                self.core
                    .command_in(dir, ["run", "view", id.as_str(), "--json", RUN_FIELDS]),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn run_watch(&self, dir: &Path, id: u64) -> Result<WorkflowRun> {
        // Block until the run completes. `--exit-status` is deliberately NOT
        // passed: it would map the run's outcome onto the exit code (1 failed,
        // 2 cancelled), which can't be reported faithfully — the follow-up
        // `run view`'s `conclusion` can. Without it, a non-zero watch exit is a
        // genuine error (no such run, auth, …). `output_string` does NOT error on a
        // timeout (it returns the result with a timeout flag), so
        // `ensure_success` is what surfaces a killed watch as `ErrorReason::Timeout`
        // instead of reading a half-finished run below.
        let id_str = id.to_string();
        // `gh run watch` re-prints the full job table every ~3 s until the run ends,
        // so over a multi-hour run its stdout grows to tens of MB — all of which we
        // discard (only the exit status matters; the result comes from `run_view`). A
        // five-minute output-inactivity watchdog detects a wedged `gh` without
        // constraining the run's total duration.
        // Bound the retained buffer (drop-oldest) so a long watch can't accumulate
        // unboundedly; the last 256 lines / 256 KiB are plenty for a failure message.
        // (`docs/audit-2026-07.md` R5.)
        //
        // Expressed through the shared [`OutputBudget`] so this fixed watch cap and
        // the configurable content-op budget are the *same* mechanism (T-049): this
        // is the drop-oldest *diagnostic* projection (`diagnostic_policy`) — a bounded
        // tail that never turns a real watch failure into `OutputTooLarge` — not the
        // fail-loud *content* projection the diff/show verbs use.
        let watch_budget = OutputBudget::bytes(256 * 1024).with_max_lines(256);
        let cmd = self
            .core
            .command_in(dir, ["run", "watch", id_str.as_str()])
            .inactivity_timeout(RUN_WATCH_INACTIVITY_TIMEOUT)
            .output_buffer(
                watch_budget
                    .diagnostic_policy()
                    .expect("a byte/line budget yields a diagnostic policy"),
            );
        let _ = self.core.output_string(cmd).await?.ensure_success()?;
        self.run_view(dir, id).await
    }

    async fn workflow_dispatch(&self, dir: &Path, spec: WorkflowDispatch) -> Result<()> {
        // `<workflow>` is a bare positional — guard it against flag-injection/empty
        // exactly like `release_view`/`api`. `--ref <ref>` and each input
        // `--raw-field key=value` ride in flag-VALUE slots, so gh consumes the next
        // token verbatim (a leading `-` is safe there, same as `--branch`/`--body`)
        // — no positional guard applies. Inputs use `--raw-field` (NOT `--field`,
        // whose `@value` reads a FILE), so a caller value like `@/etc/passwd` stays a
        // literal string. gh's dispatch API returns 204 No Content, so there is no
        // run id to return — hence `run_unit` (poll `run_list` to find the run).
        reject_flag_like("workflow", spec.workflow.as_str())?;
        reject_invalid_workflow_dispatch_fields(&spec.fields)?;
        // Own the `key=value` tokens before `args` borrows them (declared first so it
        // outlives `args`, which holds `&str` into it).
        let fields: Vec<String> = spec
            .fields
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect();
        let mut args = vec!["workflow", "run", spec.workflow.as_str()];
        if let Some(git_ref) = spec.git_ref.as_deref() {
            args.push("--ref");
            args.push(git_ref);
        }
        for field in &fields {
            args.push("--raw-field");
            args.push(field.as_str());
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn run_rerun(&self, dir: &Path, id: u64, scope: RerunScope) -> Result<()> {
        // `<run-id>` is a `u64`, so the bare positional can never look like a flag —
        // nothing to guard (same as `issue_close`). `--failed` is presence-only.
        let id = id.to_string();
        let mut args = vec!["run", "rerun", id.as_str()];
        if scope == RerunScope::FailedOnly {
            args.push("--failed");
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn run_cancel(&self, dir: &Path, id: u64) -> Result<()> {
        // `<run-id>` is a `u64`, so the bare positional can never look like a flag —
        // nothing to guard.
        let id = id.to_string();
        self.core
            .run_unit(self.core.command_in(dir, ["run", "cancel", id.as_str()]))
            .await
    }

    async fn issue_create(&self, dir: &Path, title: &str, body: &str) -> Result<String> {
        self.issue_create_with(dir, IssueCreate::new(title, body))
            .await
    }

    async fn issue_create_with(&self, dir: &Path, spec: IssueCreate) -> Result<String> {
        if !spec.labels.is_empty() {
            reject_invalid_labels("issue_create_with", &spec.labels)?;
        }
        let mut args = vec![
            "issue",
            "create",
            "--title",
            spec.title.as_str(),
            "--body",
            spec.body.as_str(),
        ];
        for label in &spec.labels {
            args.push("--label");
            args.push(label);
        }
        self.core.run(self.core.command_in(dir, args)).await
    }

    async fn pr_add_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        reject_invalid_labels("pr_add_labels", labels)?;
        let number = number.to_string();
        let mut args = vec!["pr", "edit", number.as_str()];
        for label in labels {
            args.push("--add-label");
            args.push(label);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn pr_remove_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        reject_invalid_labels("pr_remove_labels", labels)?;
        let number = number.to_string();
        let mut args = vec!["pr", "edit", number.as_str()];
        for label in labels {
            args.push("--remove-label");
            args.push(label);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn issue_add_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        reject_invalid_labels("issue_add_labels", labels)?;
        let number = number.to_string();
        let mut args = vec!["issue", "edit", number.as_str()];
        for label in labels {
            args.push("--add-label");
            args.push(label);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn issue_remove_labels(&self, dir: &Path, number: u64, labels: &[String]) -> Result<()> {
        reject_invalid_labels("issue_remove_labels", labels)?;
        let number = number.to_string();
        let mut args = vec!["issue", "edit", number.as_str()];
        for label in labels {
            args.push("--remove-label");
            args.push(label);
        }
        self.core.run_unit(self.core.command_in(dir, args)).await
    }

    async fn issue_view(&self, dir: &Path, number: u64) -> Result<Issue> {
        let n = number.to_string();
        self.core
            .try_parse(
                self.core.command_in(
                    dir,
                    ["issue", "view", n.as_str(), "--json", ISSUE_VIEW_FIELDS],
                ),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn issue_close(&self, dir: &Path, number: u64) -> Result<()> {
        let n = number.to_string();
        self.core
            .run_unit(self.core.command_in(dir, ["issue", "close", n.as_str()]))
            .await
    }

    async fn issue_reopen(&self, dir: &Path, number: u64) -> Result<()> {
        let n = number.to_string();
        self.core
            .run_unit(self.core.command_in(dir, ["issue", "reopen", n.as_str()]))
            .await
    }

    async fn issue_comment(&self, dir: &Path, number: u64, body: &str) -> Result<String> {
        // `--body` is mandatory here: without it gh falls back to an interactive
        // prompt, which would hang a headless run (same as `pr_comment`). The body
        // rides in a flag-VALUE slot, so a leading `-` is safe — no argv guard.
        let n = number.to_string();
        self.core
            .run(
                self.core
                    .command_in(dir, ["issue", "comment", n.as_str(), "--body", body]),
            )
            .await
    }

    async fn release_list(&self, dir: &Path) -> Result<Vec<Release>> {
        self.core
            .try_parse(
                self.core.command_in(
                    dir,
                    [
                        "release",
                        "list",
                        "--limit",
                        "100",
                        "--json",
                        RELEASE_LIST_FIELDS,
                    ],
                ),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn release_view(&self, dir: &Path, tag: &str) -> Result<Release> {
        reject_flag_like("tag", tag)?;
        self.core
            .try_parse(
                self.core
                    .command_in(dir, ["release", "view", tag, "--json", RELEASE_VIEW_FIELDS]),
                |s| vcs_cli_support::json::from_json(BINARY, s),
            )
            .await
    }

    async fn release_create(&self, dir: &Path, spec: ReleaseCreate) -> Result<String> {
        // `<tag>` is a bare positional — guard it against flag-injection/empty the
        // same way `release_view` does. `--title`/`--notes` are flag-VALUE slots (gh
        // consumes the next token verbatim), so they need no guard; `--draft`/
        // `--prerelease` are presence-only. gh prints the new release's URL.
        reject_flag_like("tag", spec.tag.as_str())?;
        let mut args = vec!["release", "create", spec.tag.as_str()];
        if let Some(title) = spec.title.as_deref() {
            args.push("--title");
            args.push(title);
        }
        if let Some(notes) = spec.notes.as_deref() {
            args.push("--notes");
            args.push(notes);
        }
        if spec.draft {
            args.push("--draft");
        }
        if spec.prerelease {
            args.push("--prerelease");
        }
        self.core.run(self.core.command_in(dir, args)).await
    }

    async fn release_delete(&self, dir: &Path, tag: &str) -> Result<()> {
        // `<tag>` is a bare positional — guarded like `release_view`. `--yes` skips
        // gh's interactive confirmation so a headless delete never hangs on a prompt.
        reject_flag_like("tag", tag)?;
        self.core
            .run_unit(
                self.core
                    .command_in(dir, ["release", "delete", tag, "--yes"]),
            )
            .await
    }
}

impl<R: ProcessRunner> GitHub<R> {
    /// [`pr_diff`](GitHubApi::pr_diff) with an explicit per-call [`OutputBudget`],
    /// instead of this client's [`default_output_budget`](GitHub::default_output_budget).
    /// Past the ceiling the read errors with
    /// [`ErrorReason::OutputTooLarge`] (actual and
    /// allowed sizes) rather than buffering an unbounded diff — the override for a
    /// legitimately huge PR.
    pub async fn pr_diff_within(
        &self,
        dir: &Path,
        number: u64,
        budget: OutputBudget,
    ) -> Result<Vec<FileDiff>> {
        // `run_untrimmed_within`: a diff's trailing content is meaningful (a hunk's
        // last line, a missing trailing newline) — trimming it before parsing could
        // desync the parser from `git`'s own byte-exact output. `--color never` keeps
        // the output free of ANSI even if stdout were ever a tty. The budget bounds it.
        let n = number.to_string();
        let text = self
            .core
            .run_untrimmed_within(
                self.core
                    .command_in(dir, ["pr", "diff", n.as_str(), "--color", "never"]),
                budget,
            )
            .await?;
        Ok(vcs_diff::parse_diff(&text))
    }

    /// Bind this client to `dir`, returning a [`GitHubAt`] handle whose `dir`-taking
    /// methods omit that argument: `gh.at(dir).pr_list()` runs
    /// [`pr_list`](GitHubApi::pr_list) against `dir`.
    pub fn at<'a>(&'a self, dir: &'a Path) -> GitHubAt<'a, R> {
        GitHubAt { gh: self, dir }
    }
}

// The six raw escape-hatch helpers (`run_args`/`run_raw_args`/`run_in`/… and the
// `*_in` twins) are byte-identical forwards into `core` across all five CLI
// wrappers, so the shared macro in `vcs-cli-support` generates them (see
// `vcs_cli_support::raw_run_forwarders!`).
vcs_cli_support::raw_run_forwarders! {
    GitHub, "gh", "\"pr\", \"list\"", ", so `gh` infers the repo from `dir`'s remote",
    "only the working directory is bound, no `-R`/extra flag is injected"
}

/// A [`GitHub`] client with a working directory bound, so its repo-scoped methods
/// drop the leading `dir` argument (`gh.at(dir).pr_list()`). Construct one with
/// [`GitHub::at`].
pub struct GitHubAt<'a, R: ProcessRunner = processkit::JobRunner> {
    gh: &'a GitHub<R>,
    dir: &'a Path,
}

// Hand-written rather than derived: holding only references, the view is `Copy`
// for *every* runner. `#[derive(Copy)]` would add a spurious `R: Copy` bound the
// default `JobRunner` doesn't satisfy, silently dropping `Copy` on the handle.
impl<R: ProcessRunner> Clone for GitHubAt<'_, R> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<R: ProcessRunner> Copy for GitHubAt<'_, R> {}

// Generate [`GitHubAt`] forwarders: `bare` methods forward verbatim, `dir`
// methods inject `self.dir` as the first argument. The shared macro lives in
// `vcs-cli-support` (see `vcs_cli_support::at_forwarders!`).
vcs_cli_support::at_forwarders! {
    GitHubAt, gh, "GitHub",
    bare {
        fn version() -> Result<String>;
        fn capabilities() -> Result<GitHubCapabilities>;
        fn auth_status() -> Result<bool>;
        fn auth_status_for(host: &GitHubHost) -> Result<bool>;
    }
    dir {
        fn api(endpoint: &str) -> Result<String>;
        fn repo_view() -> Result<RepoView>;
        fn pr_list() -> Result<Vec<PullRequest>>;
        fn pr_list_with(spec: PrList) -> Result<Vec<PullRequest>>;
        fn pr_list_for_source_branch(head: &str) -> Result<Vec<PullRequest>>;
        fn pr_list_for_branch(head: &str, base: &str) -> Result<Vec<PullRequest>>;
        fn pr_view(number: u64) -> Result<PullRequest>;
        fn issue_list() -> Result<Vec<Issue>>;
        fn issue_list_with(spec: IssueList) -> Result<Vec<Issue>>;
        fn pr_create(spec: PrCreate) -> Result<String>;
        fn pr_add_labels(number: u64, labels: &[String]) -> Result<()>;
        fn pr_remove_labels(number: u64, labels: &[String]) -> Result<()>;
        fn pr_merge(number: u64, merge: PrMerge) -> Result<()>;
        fn pr_mark_ready(number: u64) -> Result<()>;
        fn pr_close(number: u64, spec: PrClose) -> Result<()>;
        fn pr_checkout(number: u64) -> Result<()>;
        fn pr_checks(number: u64) -> Result<Vec<CheckRun>>;
        fn pr_review(number: u64, action: ReviewAction) -> Result<()>;
        fn pr_comment(number: u64, body: &str) -> Result<String>;
        fn pr_edit(number: u64, edit: PrEdit) -> Result<()>;
        fn pr_feedback(number: u64) -> Result<PrFeedback>;
        fn pr_diff(number: u64) -> Result<Vec<FileDiff>>;
        fn workflow_list() -> Result<Vec<Workflow>>;
        fn workflow_list_with(spec: WorkflowList) -> Result<Vec<Workflow>>;
        fn workflow_view(selector: &str) -> Result<Workflow>;
        fn run_list(limit: u64, branch: Option<String>) -> Result<Vec<WorkflowRun>>;
        fn run_view(id: u64) -> Result<WorkflowRun>;
        fn run_watch(id: u64) -> Result<WorkflowRun>;
        fn workflow_dispatch(spec: WorkflowDispatch) -> Result<()>;
        fn run_rerun(id: u64, scope: RerunScope) -> Result<()>;
        fn run_cancel(id: u64) -> Result<()>;
        fn issue_create(title: &str, body: &str) -> Result<String>;
        fn issue_create_with(spec: IssueCreate) -> Result<String>;
        fn issue_add_labels(number: u64, labels: &[String]) -> Result<()>;
        fn issue_remove_labels(number: u64, labels: &[String]) -> Result<()>;
        fn issue_view(number: u64) -> Result<Issue>;
        fn issue_close(number: u64) -> Result<()>;
        fn issue_reopen(number: u64) -> Result<()>;
        fn issue_comment(number: u64, body: &str) -> Result<String>;
        fn release_list() -> Result<Vec<Release>>;
        fn release_view(tag: &str) -> Result<Release>;
        fn release_create(spec: ReleaseCreate) -> Result<String>;
        fn release_delete(tag: &str) -> Result<()>;
    }
    // Raw escape hatches: bound to `self.dir` (forward to the client's `*_in`
    // twins) so `gh.at(dir).run(…)` targets the bound repo's cwd, not the process
    // cwd. For the process-cwd hatch call `run`/`run_raw`/… on `GitHub` directly.
    raw {
        fn run(args: &[String]) -> Result<String> => run_in;
        fn run_raw(args: &[String]) -> Result<ProcessResult<String>> => run_raw_in;
        fn run_args(args: &[&str]) -> Result<String> => run_args_in;
        fn run_raw_args(args: &[&str]) -> Result<ProcessResult<String>> => run_raw_args_in;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use processkit::testing::{RecordReplayRunner, RecordingRunner, Reply, ScriptedRunner};

    /// The [`ErrorReason`] behind a failed result. Since processkit 3.0 `Error` is
    /// an opaque wrapper, so the variant assertions below reach the reason through
    /// it instead of matching the error directly.
    fn err_reason<T>(out: &Result<T>) -> Option<&ErrorReason> {
        out.as_ref().err().map(Error::reason)
    }

    #[test]
    fn binary_name_is_gh() {
        assert_eq!(BINARY, "gh");
    }

    /// Path to a cassette recorded by `crates/github/tests/cli.rs`'s
    /// `record_*` tests. See CONTRIBUTING.md, "Updating a `gh` CLI cassette",
    /// for the re-recording procedure — a cassette here is a fixture that
    /// captures "what `gh` actually printed", not our guess at its shape.
    fn cassette_path(name: &str) -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/cassettes")
            .join(name)
    }

    // `capabilities()` parses the real `gh --version` banner and gates on the 2.0
    // floor — covering the minimum, a modern release, and an unrecognisable banner
    // (the three cases the scheduled-drift lane also exercises against a real gh).
    #[tokio::test]
    async fn capability_version_gate_parses_and_gates() {
        // Modern gh (the `(date)` trailer and release-URL line are ignored).
        let gh = GitHub::with_runner(ScriptedRunner::new().on(
            ["gh", "--version"],
            Reply::ok(
                "gh version 2.40.1 (2024-01-05)\nhttps://github.com/cli/cli/releases/tag/v2.40.1\n",
            ),
        ));
        let caps = gh.capabilities().await.expect("capabilities");
        assert_eq!(caps.version.to_string(), "2.40.1");
        assert!(caps.is_supported());
        caps.ensure_supported().expect("supported");

        // Exactly at the floor (2.0.0) is supported.
        let at_floor = GitHub::with_runner(
            ScriptedRunner::new().on(["gh", "--version"], Reply::ok("gh version 2.0.0\n")),
        );
        assert!(
            at_floor.capabilities().await.unwrap().is_supported(),
            "2.0.0 is exactly the floor"
        );

        // An old 1.x gh is rejected with a clear message naming the floor + found.
        let old = GitHub::with_runner(ScriptedRunner::new().on(
            ["gh", "--version"],
            Reply::ok("gh version 1.14.0 (2021-11-02)\n"),
        ));
        let caps = old.capabilities().await.expect("capabilities");
        assert_eq!(
            caps.version,
            GitHubVersion {
                major: 1,
                minor: 14,
                patch: 0
            }
        );
        assert!(!caps.is_supported(), "1.14 is below the 2.0 floor");
        let err = caps.ensure_supported().expect_err("unsupported");
        let ErrorReason::Spawn { source, .. } = err.reason() else {
            panic!("expected Spawn, got {err:?}");
        };
        let message = source.to_string();
        assert!(message.contains(">= 2.0.0"), "names the floor: {message}");
        assert!(
            message.contains("1.14.0"),
            "names the found version: {message}"
        );

        // A banner with no version token is a parse error, not a silent zero.
        let garbage = GitHub::with_runner(
            ScriptedRunner::new().on(["gh", "--version"], Reply::ok("gh version unknowable\n")),
        );
        let err = garbage.capabilities().await.expect_err("unrecognisable");
        assert!(
            matches!(err.reason(), ErrorReason::Parse { .. }),
            "got {err:?}"
        );
    }

    // Compile-time guard: the bound view stays `Copy` for the default `JobRunner`.
    #[allow(dead_code)]
    fn bound_view_is_copy_for_default_runner() {
        fn assert_copy<T: Copy>() {}
        assert_copy::<GitHubAt<'static, processkit::JobRunner>>();
    }

    // The bound view (`gh.at(dir)`) must produce byte-identical argv to the
    // dir-taking call.
    #[tokio::test]
    async fn bound_view_matches_dir_taking_calls() {
        let dir = Path::new("/repo");
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec);

        gh.pr_list_for_branch(dir, "feat", "main").await.unwrap();
        gh.at(dir).pr_list_for_branch("feat", "main").await.unwrap();
        // One of the new lifecycle methods.
        gh.run_list(dir, 3, None).await.unwrap();
        gh.at(dir).run_list(3, None).await.unwrap();
        // A new run-control verb (spec-carrying) forwards identically too.
        let disp = || WorkflowDispatch::new("ci.yml").git_ref("main");
        gh.workflow_dispatch(dir, disp()).await.unwrap();
        gh.at(dir).workflow_dispatch(disp()).await.unwrap();

        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), calls[1].args_str());
        assert_eq!(calls[2].args_str(), calls[3].args_str());
        assert_eq!(calls[4].args_str(), calls[5].args_str());
        assert_eq!(calls[1].cwd.as_deref(), Some(dir));
    }

    // T-035: the raw escape hatches reached *through* the bound view
    // (`gh.at(dir).run…`) now run in the bound `dir`, while the same-named methods
    // on the client stay in the process cwd.
    #[tokio::test]
    async fn bound_view_raw_hatch_runs_in_bound_dir() {
        let dir = Path::new("/repo");
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);

        // Through the bound view: every raw form carries the bound dir as its cwd.
        gh.at(dir)
            .run(&["pr".to_string(), "list".to_string()])
            .await
            .unwrap();
        let _ = gh
            .at(dir)
            .run_raw(&["pr".to_string(), "list".to_string()])
            .await
            .unwrap();
        gh.at(dir).run_args(&["pr", "list"]).await.unwrap();
        let _ = gh.at(dir).run_raw_args(&["pr", "list"]).await.unwrap();
        // On the client directly: the process-cwd escape hatch (no bound dir).
        gh.run(&["pr".to_string(), "list".to_string()])
            .await
            .unwrap();
        let _ = gh
            .run_raw(&["pr".to_string(), "list".to_string()])
            .await
            .unwrap();
        gh.run_args(&["pr", "list"]).await.unwrap();
        let _ = gh.run_raw_args(&["pr", "list"]).await.unwrap();

        let calls = rec.calls();
        for c in &calls[0..4] {
            assert_eq!(
                c.cwd.as_deref(),
                Some(dir),
                "raw call through the bound view runs in the bound dir"
            );
            assert_eq!(c.args_str(), ["pr", "list"]);
        }
        for c in &calls[4..8] {
            assert_eq!(
                c.cwd.as_deref(),
                None,
                "raw call on the client stays in the process cwd"
            );
            assert_eq!(c.args_str(), ["pr", "list"]);
        }
    }

    #[tokio::test]
    async fn run_args_forwards_str_slices() {
        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "api", "user"], Reply::ok("ok\n")));
        assert_eq!(gh.run_args(&["api", "user"]).await.unwrap(), "ok");
    }

    // Hermetic: real pr_list() arg-building + JSON deserialization against canned
    // output — no `gh` binary or network needed, so this runs on CI.
    #[tokio::test]
    async fn pr_list_parses_scripted_json() {
        let json = r#"[{"number":7,"title":"Add X","state":"OPEN","headRefName":"feat/x","baseRefName":"main","url":"u"}]"#;
        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "pr", "list"], Reply::ok(json)));
        let prs = gh.pr_list(Path::new(".")).await.expect("pr_list");
        assert_eq!(prs.len(), 1);
        assert_eq!(prs[0].number, 7);
        assert_eq!(prs[0].base_ref_name, "main");
    }

    // Hermetic: auth_status reflects the exit code without erroring. ANY non-zero
    // exit — not just the documented 1 — must read as `false`, never an error
    // (an unusual exit code must not be mistaken for a hard failure).
    #[tokio::test]
    async fn auth_status_reads_exit_code() {
        let yes = GitHub::with_runner(ScriptedRunner::new().on(["gh", "auth"], Reply::ok("")));
        assert!(yes.auth_status().await.unwrap());
        let no = GitHub::with_runner(
            ScriptedRunner::new().on(["gh", "auth"], Reply::fail(1, "not logged in")),
        );
        assert!(!no.auth_status().await.unwrap());
        // An unexpected exit code (e.g. 2) is still just "not authenticated".
        let weird =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "auth"], Reply::fail(2, "boom")));
        assert!(!weird.auth_status().await.unwrap());
    }

    // Regression guard for the timeout fix: a timed-out auth check must error,
    // not silently report "not authenticated" (the old hand-rolled mapping bug).
    // Relies on processkit surfacing a timed-out run as `ErrorReason::Timeout`.
    #[tokio::test]
    async fn auth_status_errors_on_timeout() {
        let gh = GitHub::with_runner(ScriptedRunner::new().on(["gh", "auth"], Reply::timeout()));
        assert!(matches!(
            gh.auth_status().await.unwrap_err().reason(),
            ErrorReason::Timeout { .. }
        ));
    }

    // pr_create appends `--base <branch>` when given one, and returns the trimmed
    // PR URL. The exact command (incl. --base) is the only scripted rule.
    #[tokio::test]
    async fn pr_create_appends_base_and_returns_url() {
        let gh = GitHub::with_runner(ScriptedRunner::new().on(
            [
                "gh", "pr", "create", "--title", "T", "--body", "B", "--base", "main",
            ],
            Reply::ok("https://gh/pr/1\n"),
        ));
        let url = gh
            .pr_create(Path::new("."), PrCreate::new("T", "B").base("main"))
            .await
            .expect("should build `pr create … --base main`");
        assert_eq!(url, "https://gh/pr/1");
    }

    // With an explicit head, `pr_create` inserts `--head <branch>` before
    // `--base` — so a PR can target an arbitrary source→target pair.
    #[tokio::test]
    async fn pr_create_appends_head_and_base() {
        use processkit::testing::RecordingRunner;
        let rec = RecordingRunner::replying(Reply::ok("https://gh/pr/9\n"));
        let gh = GitHub::with_runner(&rec);
        gh.pr_create(
            Path::new("/repo"),
            PrCreate::new("T", "B").head("feat/x").base("main"),
        )
        .await
        .expect("pr_create");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "pr", "create", "--title", "T", "--body", "B", "--head", "feat/x", "--base", "main"
            ]
        );
    }

    // pr_list_for_branch filters by head + base and parses the PR list (title +
    // url available on each result).
    #[tokio::test]
    async fn pr_list_for_branch_filters_and_parses() {
        use processkit::testing::RecordingRunner;
        let json = r#"[{"number":9,"title":"Merge feat","state":"OPEN","headRefName":"feat/x","baseRefName":"main","url":"https://gh/pr/9"}]"#;
        let rec = RecordingRunner::replying(Reply::ok(json));
        let gh = GitHub::with_runner(&rec);
        let prs = gh
            .pr_list_for_branch(Path::new("/repo"), "feat/x", "main")
            .await
            .expect("pr_list_for_branch");
        assert_eq!(prs.len(), 1);
        assert_eq!(prs[0].title, "Merge feat");
        assert_eq!(prs[0].url, "https://gh/pr/9");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "pr", "list", "--head", "feat/x", "--base", "main", "--state", "all", "--limit",
                "100", "--json", PR_FIELDS
            ]
        );
    }

    // A source-branch lookup deliberately omits `--base`, so a branch with PRs
    // against different targets still finds every state of each PR.
    #[tokio::test]
    async fn pr_list_for_source_branch_filters_all_states_and_guards_head() {
        use processkit::testing::RecordingRunner;
        let json = r#"[{"number":9,"title":"Merge feat","state":"CLOSED","headRefName":"feat/x","baseRefName":"release","url":"https://gh/pr/9"}]"#;
        let rec = RecordingRunner::replying(Reply::ok(json));
        let gh = GitHub::with_runner(&rec);
        let prs = gh
            .pr_list_for_source_branch(Path::new("/repo"), "feat/x")
            .await
            .expect("pr_list_for_source_branch");
        assert_eq!(prs[0].state, "CLOSED");
        assert_eq!(
            rec.only_call().args_str(),
            [
                "pr", "list", "--head", "feat/x", "--state", "all", "--limit", "100", "--json",
                PR_FIELDS
            ]
        );

        let guarded = GitHub::with_runner(ScriptedRunner::new());
        assert!(
            guarded
                .pr_list_for_source_branch(Path::new("/repo"), "--state=open")
                .await
                .is_err()
        );
        // Existing head/base filtering has the same pre-spawn guard.
        assert!(
            guarded
                .pr_list_for_branch(Path::new("/repo"), "feat", "--state=open")
                .await
                .is_err()
        );
    }

    // The list methods pin an explicit `--limit 100` so the CLI's default page
    // size (30) does not silently truncate the result.
    #[tokio::test]
    async fn list_methods_pin_limit_100() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec);
        gh.pr_list(Path::new("/r")).await.expect("pr_list");
        gh.issue_list(Path::new("/r")).await.expect("issue_list");
        gh.release_list(Path::new("/r"))
            .await
            .expect("release_list");
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            [
                "pr", "list", "--state", "open", "--limit", "100", "--json", PR_FIELDS
            ]
        );
        assert_eq!(
            calls[1].args_str(),
            [
                "issue",
                "list",
                "--state",
                "open",
                "--limit",
                "100",
                "--json",
                ISSUE_LIST_FIELDS
            ]
        );
        assert_eq!(
            calls[2].args_str(),
            [
                "release",
                "list",
                "--limit",
                "100",
                "--json",
                RELEASE_LIST_FIELDS
            ]
        );
    }

    #[tokio::test]
    async fn list_specs_map_state_and_limit_and_reject_zero() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec);
        gh.pr_list_with(
            Path::new("/r"),
            PrList::new().state(PrListState::Merged).limit(7),
        )
        .await
        .expect("merged PR list");
        gh.issue_list_with(
            Path::new("/r"),
            IssueList::new().state(IssueListState::All).limit(9),
        )
        .await
        .expect("all issue list");
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            [
                "pr", "list", "--state", "merged", "--limit", "7", "--json", PR_FIELDS
            ]
        );
        assert_eq!(
            calls[1].args_str(),
            [
                "issue",
                "list",
                "--state",
                "all",
                "--limit",
                "9",
                "--json",
                ISSUE_LIST_FIELDS
            ]
        );

        let guarded = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&guarded);
        assert!(
            gh.pr_list_with(Path::new("/r"), PrList::new().limit(0))
                .await
                .is_err()
        );
        assert!(guarded.calls().is_empty(), "zero limit must not spawn");
    }

    // Without a base, `pr_create` must omit `--base` entirely. RecordingRunner
    // captures the exact invocation (and `&rec` plumbs through CliClient), so we
    // can assert flag *absence* and the cwd — which prefix matching can't.
    #[tokio::test]
    async fn pr_create_omits_base_when_none() {
        use processkit::testing::RecordingRunner;
        let rec = RecordingRunner::replying(Reply::ok("https://gh/pr/2\n"));
        let gh = GitHub::with_runner(&rec);
        let url = gh
            .pr_create(Path::new("/repo"), PrCreate::new("T", "B"))
            .await
            .expect("pr_create");
        assert_eq!(url, "https://gh/pr/2");

        let call = rec.only_call();
        assert_eq!(call.cwd.as_deref(), Some(Path::new("/repo")));
        assert_eq!(
            call.args_str(),
            ["pr", "create", "--title", "T", "--body", "B"]
        );
        assert!(!call.has_flag("--base"), "no base was given");
        assert!(!call.has_flag("--head"), "no head was given");
    }

    // The injection guard on gh's exposed positionals.
    #[tokio::test]
    async fn flag_like_positionals_are_rejected_before_spawning() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        assert!(gh.api(Path::new("."), "-evil").await.is_err());
        assert!(gh.release_view(Path::new("."), "-evil").await.is_err());
        assert!(
            gh.api(Path::new("."), "").await.is_err(),
            "empty refused too"
        );
        assert!(rec.calls().is_empty(), "nothing may spawn");
    }

    // release_create pins the empirically-verified `gh release create` argv
    // (gh 2.95.0): the bare `<tag>` positional plus the flag-VALUE title/notes
    // and presence-only --draft/--prerelease, in that order; gh prints the URL.
    #[tokio::test]
    async fn release_create_builds_argv_and_returns_url() {
        let rec = RecordingRunner::replying(Reply::ok("https://gh/releases/v1.2.0\n"));
        let gh = GitHub::with_runner(&rec);
        let url = gh
            .release_create(
                Path::new("/repo"),
                ReleaseCreate::new("v1.2.0")
                    .title("v1.2.0")
                    .notes("Notes")
                    .draft()
                    .prerelease(),
            )
            .await
            .expect("release_create");
        assert_eq!(url, "https://gh/releases/v1.2.0");
        let call = rec.only_call();
        assert_eq!(call.cwd.as_deref(), Some(Path::new("/repo")));
        assert_eq!(
            call.args_str(),
            [
                "release",
                "create",
                "v1.2.0",
                "--title",
                "v1.2.0",
                "--notes",
                "Notes",
                "--draft",
                "--prerelease"
            ]
        );
    }

    // With only the tag, release_create emits neither the optional flags nor the
    // presence-only booleans — a minimal `gh release create <tag>`.
    #[tokio::test]
    async fn release_create_omits_unset_options() {
        let rec = RecordingRunner::replying(Reply::ok("https://gh/releases/v2\n"));
        let gh = GitHub::with_runner(&rec);
        gh.release_create(Path::new("/r"), ReleaseCreate::new("v2"))
            .await
            .expect("release_create");
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["release", "create", "v2"]);
        assert!(!call.has_flag("--title"));
        assert!(!call.has_flag("--notes"));
        assert!(!call.has_flag("--draft"));
        assert!(!call.has_flag("--prerelease"));
    }

    // release_delete pins `gh release delete <tag> --yes` (--yes so a headless
    // delete never hangs on gh's confirmation prompt).
    #[tokio::test]
    async fn release_delete_builds_argv_with_yes() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.release_delete(Path::new("/r"), "v1.2.0")
            .await
            .expect("release_delete");
        assert_eq!(
            rec.only_call().args_str(),
            ["release", "delete", "v1.2.0", "--yes"]
        );
    }

    // Both release mutators guard their bare `<tag>` positional against flag-like
    // or empty input before anything spawns (same guard as `release_view`/`api`).
    #[tokio::test]
    async fn release_mutators_reject_flag_like_tag() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        assert!(
            gh.release_create(Path::new("."), ReleaseCreate::new("-evil"))
                .await
                .is_err()
        );
        assert!(
            gh.release_create(Path::new("."), ReleaseCreate::new(""))
                .await
                .is_err()
        );
        assert!(gh.release_delete(Path::new("."), "-evil").await.is_err());
        assert!(gh.release_delete(Path::new("."), "").await.is_err());
        assert!(rec.calls().is_empty(), "nothing may spawn");
    }

    #[tokio::test]
    async fn api_runs_in_the_bound_repo_dir() {
        let rec = RecordingRunner::replying(Reply::ok("{}\n"));
        let gh = GitHub::with_runner(&rec);
        gh.api(Path::new("/repo"), "repos/o/r/pulls")
            .await
            .expect("api");
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["api", "repos/o/r/pulls"]);
        // H9: the request runs in the bound repo dir, so gh resolves a relative
        // endpoint's `{owner}/{repo}` from *that* repo — not the process cwd.
        assert_eq!(call.cwd, Some(std::path::PathBuf::from("/repo")));
    }

    // pr_merge builds the strategy flag plus the optional --auto/--delete-branch.
    #[tokio::test]
    async fn pr_merge_builds_strategy_and_flags() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.pr_merge(Path::new("/r"), 7, PrMerge::squash().auto().delete_branch())
            .await
            .expect("pr_merge");
        assert_eq!(
            rec.only_call().args_str(),
            ["pr", "merge", "7", "--squash", "--auto", "--delete-branch"]
        );

        let bare = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&bare);
        gh.pr_merge(Path::new("/r"), 7, PrMerge::merge())
            .await
            .expect("pr_merge");
        let call = bare.only_call();
        assert_eq!(call.args_str(), ["pr", "merge", "7", "--merge"]);
        assert!(!call.has_flag("--auto"));
        assert!(!call.has_flag("--delete-branch"));
    }

    #[tokio::test]
    async fn pr_mark_ready_and_close_build_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.pr_mark_ready(Path::new("/r"), 3)
            .await
            .expect("pr_mark_ready");
        gh.pr_close(Path::new("/r"), 3, PrClose::new().delete_branch())
            .await
            .expect("close");
        gh.pr_close(Path::new("/r"), 4, PrClose::new())
            .await
            .expect("close");
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["pr", "ready", "3"]);
        assert_eq!(calls[1].args_str(), ["pr", "close", "3", "--delete-branch"]);
        assert_eq!(calls[2].args_str(), ["pr", "close", "4"]);
    }

    // pr_checkout maps to `pr checkout <n>` and runs in the bound repo dir.
    #[tokio::test]
    async fn pr_checkout_builds_args_in_repo_dir() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.pr_checkout(Path::new("/repo"), 7)
            .await
            .expect("pr_checkout");
        let call = rec.only_call();
        assert_eq!(call.args_str(), ["pr", "checkout", "7"]);
        assert_eq!(call.cwd.as_deref(), Some(Path::new("/repo")));
        // The bound view produces byte-identical argv.
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.at(Path::new("/repo"))
            .pr_checkout(7)
            .await
            .expect("pr_checkout");
        assert_eq!(rec.only_call().args_str(), ["pr", "checkout", "7"]);
    }

    // gh signals the checks outcome via exit code (0 pass / 8 pending / 1 some
    // failed) but emits the same JSON for all three — all must parse. Other
    // exits (and timeouts) are genuine errors.
    #[tokio::test]
    async fn pr_checks_parses_all_outcome_exit_codes() {
        let json = r#"[{"name":"build","state":"SUCCESS","bucket":"pass",
            "workflow":"CI","link":"l","startedAt":"s","completedAt":"c"}]"#;
        for reply in [
            Reply::ok(json),
            Reply::fail(8, "checks pending").with_stdout(json),
            Reply::fail(1, "some checks failed").with_stdout(json),
        ] {
            let gh = GitHub::with_runner(ScriptedRunner::new().on(["gh", "pr", "checks"], reply));
            let checks = gh.pr_checks(Path::new("."), 7).await.expect("pr_checks");
            assert_eq!(checks.len(), 1);
            assert_eq!(checks[0].bucket, CheckBucket::Pass);
        }

        // A PR with no checks at all: gh exits 1 with NO JSON and a
        // "no checks reported" message — an empty list, not an error. Matched
        // case-insensitively, so a capitalized variant is still the empty case.
        for stderr in [
            "no checks reported on the 'feat/x' branch",
            "No Checks Reported on the 'feat/x' branch",
        ] {
            let gh = GitHub::with_runner(
                ScriptedRunner::new().on(["gh", "pr", "checks"], Reply::fail(1, stderr)),
            );
            assert!(
                gh.pr_checks(Path::new("."), 7)
                    .await
                    .expect("no checks → empty")
                    .is_empty(),
                "no-checks must read as empty for stderr {stderr:?}"
            );
        }
        // …while a bare exit 1 for a different reason stays an error.
        let gh = GitHub::with_runner(ScriptedRunner::new().on(
            ["gh", "pr", "checks"],
            Reply::fail(1, "no pull requests found for branch 'feat/x'"),
        ));
        assert!(matches!(
            gh.pr_checks(Path::new("."), 7).await.unwrap_err().reason(),
            ErrorReason::Exit { .. }
        ));

        // Exit 4 (auth required) is a real failure, not an outcome.
        let gh = GitHub::with_runner(
            ScriptedRunner::new().on(["gh", "pr", "checks"], Reply::fail(4, "auth required")),
        );
        assert!(matches!(
            gh.pr_checks(Path::new("."), 7).await.unwrap_err().reason(),
            ErrorReason::Exit { .. }
        ));

        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "pr", "checks"], Reply::timeout()));
        assert!(matches!(
            gh.pr_checks(Path::new("."), 7).await.unwrap_err().reason(),
            ErrorReason::Timeout { .. }
        ));
    }

    // Hermetic: real pr_diff() arg-building (incl. `--color never`) + the
    // shared unified-diff parser against canned `gh pr diff` output.
    #[tokio::test]
    async fn pr_diff_builds_args_and_parses_scripted_output() {
        let out = "diff --git a/m b/m\n--- a/m\n+++ b/m\n@@ -1 +1 @@\n-a\n+b\n";
        let rec = RecordingRunner::replying(Reply::ok(out));
        let gh = GitHub::with_runner(&rec);
        let files = gh.pr_diff(Path::new("/r"), 7).await.expect("pr_diff");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, std::path::Path::new("m"));
        assert_eq!(files[0].change, ChangeKind::Modified);
        assert_eq!(
            rec.only_call().args_str(),
            ["pr", "diff", "7", "--color", "never"]
        );
    }

    // T-049: `pr_diff` over the client's default OutputBudget is refused with
    // `OutputTooLarge` (actual + allowed sizes), never a silently truncated diff.
    // T-130: audited against processkit 3.0's raw-pipe-byte accounting and kept as
    // is — a content read captures RAW stdout, whose accounting 3.0 left untouched,
    // and the fixture is ~2x the ceiling under either unit. The exact boundary is
    // pinned in `vcs_cli_support`'s `content_budget_*` tests.
    #[tokio::test]
    async fn pr_diff_over_budget_errors_output_too_large() {
        let big = "diff --git a/m b/m\n".to_string() + &"+line\n".repeat(20_000);
        assert!(big.len() > 64 * 1024, "fixture must exceed the budget");
        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "pr", "diff"], Reply::ok(&big)))
                .default_output_budget(OutputBudget::bytes(64 * 1024));
        match gh
            .pr_diff(Path::new("/r"), 7)
            .await
            .map_err(Error::into_reason)
        {
            Err(ErrorReason::OutputTooLarge {
                program,
                max_bytes,
                total_bytes,
                ..
            }) => {
                assert_eq!(program, "gh");
                assert_eq!(max_bytes, Some(64 * 1024));
                assert!(total_bytes > 64 * 1024, "actual exceeds allowed");
            }
            other => panic!("expected OutputTooLarge, got {other:?}"),
        }
    }

    // The per-call override reads a legitimately large PR diff past the tight
    // client default that would otherwise refuse it.
    #[tokio::test]
    async fn pr_diff_within_override_reads_past_the_default() {
        let out = "diff --git a/m b/m\n--- a/m\n+++ b/m\n@@ -1 +1 @@\n-a\n+b\n";
        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "pr", "diff"], Reply::ok(out)))
                .default_output_budget(OutputBudget::bytes(4)); // absurdly tight default
        assert!(matches!(
            err_reason(&gh.pr_diff(Path::new("/r"), 7).await),
            Some(ErrorReason::OutputTooLarge { .. })
        ));
        let files = gh
            .pr_diff_within(Path::new("/r"), 7, OutputBudget::unlimited())
            .await
            .expect("override reads the diff");
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, std::path::Path::new("m"));
    }

    // T-049: `gh run watch`'s fixed cap is reconciled onto the shared OutputBudget
    // as its DROP-OLDEST *diagnostic* projection — a bounded tail that NEVER turns a
    // long, chatty watch into `OutputTooLarge`. A watch that reprints far past the
    // 256 KiB / 256-line cap still succeeds and reads the final run state.
    // T-130: unaffected by processkit 3.0's raw-pipe-byte accounting — that change
    // re-based the fail-loud `OverflowMode::Error` ceiling only, while a drop-mode
    // buffer still bounds what it RETAINS by decoded line-content bytes. The 256 KiB
    // / 256-line watch cap therefore keeps exactly the tail it kept before.
    #[tokio::test]
    async fn run_watch_bounds_output_without_failing_loud() {
        // ~5 MiB of repeated job-table frames — well past the watch cap.
        let flood = "watching run… job A: running\n".repeat(180_000);
        let run_json = r#"{"databaseId":42,"name":"CI","displayTitle":"t",
            "status":"completed","conclusion":"success","workflowName":"CI",
            "headBranch":"main","event":"push","url":"u","createdAt":"c"}"#;
        let gh = GitHub::with_runner(
            ScriptedRunner::new()
                .on(["gh", "run", "watch"], Reply::ok(&flood))
                .on(["gh", "run", "view"], Reply::ok(run_json)),
        );
        // Must NOT error out with OutputTooLarge — the diagnostic projection drops
        // the oldest frames and keeps going, then `run view` yields the state.
        let run = gh
            .run_watch(Path::new("/r"), 42)
            .await
            .expect("a chatty watch is bounded, not failed loud");
        assert_eq!(run.database_id, 42);
    }

    // Each review action maps to its flag; the body is carried on the action
    // (approve's is optional and omitted when absent).
    #[tokio::test]
    async fn pr_review_builds_action_args() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.pr_review(Path::new("/r"), 7, ReviewAction::approve())
            .await
            .expect("approve");
        gh.pr_review(
            Path::new("/r"),
            7,
            ReviewAction::request_changes("fix the parser"),
        )
        .await
        .expect("request changes");
        gh.pr_review(Path::new("/r"), 7, ReviewAction::comment("nice"))
            .await
            .expect("comment");
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["pr", "review", "7", "--approve"]);
        assert!(!calls[0].has_flag("--body"));
        assert_eq!(
            calls[1].args_str(),
            [
                "pr",
                "review",
                "7",
                "--request-changes",
                "--body",
                "fix the parser"
            ]
        );
        assert_eq!(
            calls[2].args_str(),
            ["pr", "review", "7", "--comment", "--body", "nice"]
        );
    }

    // `approve().with_body(..)` attaches the optional approve message, emitting
    // `--approve --body <body>`; the accessors read the parts back.
    #[tokio::test]
    async fn pr_review_approve_with_body() {
        let action = ReviewAction::approve().with_body("LGTM");
        assert_eq!(action.kind(), ReviewKind::Approve);
        assert_eq!(action.body(), Some("LGTM"));

        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.pr_review(Path::new("/r"), 7, action)
            .await
            .expect("approve with body");
        assert_eq!(
            rec.only_call().args_str(),
            ["pr", "review", "7", "--approve", "--body", "LGTM"]
        );
    }

    #[tokio::test]
    async fn pr_comment_and_issue_create_return_urls() {
        let rec = RecordingRunner::replying(Reply::ok("https://gh/x\n"));
        let gh = GitHub::with_runner(&rec);
        assert_eq!(
            gh.pr_comment(Path::new("/r"), 7, "hello").await.unwrap(),
            "https://gh/x"
        );
        assert_eq!(
            gh.issue_create(Path::new("/r"), "T", "B").await.unwrap(),
            "https://gh/x"
        );
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            ["pr", "comment", "7", "--body", "hello"]
        );
        assert_eq!(
            calls[1].args_str(),
            ["issue", "create", "--title", "T", "--body", "B"]
        );
    }

    // `issue close`/`issue reopen` take only the bare `u64` index (no flags, no
    // structured output); `issue comment` puts the body in a flag-VALUE `--body`
    // slot and returns the new comment's URL.
    #[tokio::test]
    async fn issue_close_reopen_and_comment_build_argv() {
        let rec = RecordingRunner::replying(Reply::ok("https://gh/i/7#c1\n"));
        let gh = GitHub::with_runner(&rec);

        gh.issue_close(Path::new("/r"), 7).await.expect("close");
        gh.issue_reopen(Path::new("/r"), 7).await.expect("reopen");
        assert_eq!(
            gh.issue_comment(Path::new("/r"), 7, "ping").await.unwrap(),
            "https://gh/i/7#c1"
        );

        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["issue", "close", "7"]);
        assert_eq!(calls[1].args_str(), ["issue", "reopen", "7"]);
        assert_eq!(
            calls[2].args_str(),
            ["issue", "comment", "7", "--body", "ping"]
        );
    }

    // The comment body rides in a flag-VALUE slot, so gh consumes a leading-`-`
    // body verbatim (a Markdown bullet list / `---` rule is legitimate) — the
    // argv is pinned to prove no guard mangles or rejects it.
    #[tokio::test]
    async fn issue_comment_passes_leading_dash_body_verbatim() {
        let rec = RecordingRunner::replying(Reply::ok("https://gh/i/7#c2\n"));
        let gh = GitHub::with_runner(&rec);
        gh.issue_comment(Path::new("/r"), 7, "- a bullet")
            .await
            .expect("dash body");
        assert_eq!(
            rec.only_call().args_str(),
            ["issue", "comment", "7", "--body", "- a bullet"]
        );
    }

    // pr_edit emits only the flags the caller set. The flag-VALUE slots
    // (`--title <t>`, `--body <b>`) are passed verbatim — no argv-guard needed
    // since gh consumes the next token as a value, not as a flag.
    #[tokio::test]
    async fn pr_edit_emits_only_provided_fields() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);

        gh.pr_edit(Path::new("/r"), 7, PrEdit::new().title("New title"))
            .await
            .expect("title-only edit");
        gh.pr_edit(Path::new("/r"), 7, PrEdit::new().body("New body"))
            .await
            .expect("body-only edit");
        gh.pr_edit(Path::new("/r"), 7, PrEdit::new().title("T").body("B"))
            .await
            .expect("both-fields edit");

        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            ["pr", "edit", "7", "--title", "New title"]
        );
        assert_eq!(
            calls[1].args_str(),
            ["pr", "edit", "7", "--body", "New body"]
        );
        assert_eq!(
            calls[2].args_str(),
            ["pr", "edit", "7", "--title", "T", "--body", "B"]
        );
    }

    // An empty string is a real value (clears the field) — it must reach the
    // CLI as `--title ""`, not be silently dropped. The argv is asserted
    // byte-for-byte so a future "treat empty as None" regression would
    // surface here.
    #[tokio::test]
    async fn pr_edit_some_empty_string_clears_field() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.pr_edit(Path::new("/r"), 7, PrEdit::new().title(""))
            .await
            .expect("empty title");
        assert_eq!(
            rec.only_call().args_str(),
            ["pr", "edit", "7", "--title", ""]
        );
    }

    #[tokio::test]
    async fn with_credentials_injects_gh_token_and_default_does_not() {
        // With a provider: the token is set as GH_TOKEN on the command — and never
        // appears in argv (so it can't leak through `ps`).
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec)
            .with_credentials(Arc::new(StaticCredential::token("tok-123")));
        gh.pr_list(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        let token = call
            .envs
            .iter()
            .find(|(k, _)| k.to_str() == Some("GH_TOKEN"))
            .and_then(|(_, v)| v.as_ref())
            .and_then(|v| v.to_str());
        assert_eq!(
            token,
            Some("tok-123"),
            "provider token injected as GH_TOKEN"
        );
        assert!(
            !call.args_str().iter().any(|a| a.contains("tok-123")),
            "secret must never appear in argv"
        );

        // Without a provider: no GH_TOKEN injected — ambient `gh` auth is unchanged.
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec);
        gh.pr_list(Path::new("/r")).await.unwrap();
        assert!(
            !rec.only_call()
                .envs
                .iter()
                .any(|(k, _)| k.to_str() == Some("GH_TOKEN")),
            "no provider → no token env (ambient gh auth)"
        );
    }

    // The `with_token` convenience is the common path: a static token, no `Arc`/
    // `StaticCredential` ceremony, injected as GH_TOKEN.
    #[tokio::test]
    async fn with_token_convenience_injects_gh_token() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec).with_token("tok-conv");
        gh.pr_list(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        let token = call
            .envs
            .iter()
            .find(|(k, _)| k.to_str() == Some("GH_TOKEN"))
            .and_then(|(_, v)| v.as_ref())
            .and_then(|v| v.to_str());
        assert_eq!(token, Some("tok-conv"));
    }

    // A provider that yields `Ok(None)` defers to ambient auth: no GH_TOKEN is
    // injected, exactly as if no provider were attached. Pins the None=ambient
    // contract end-to-end (not just at the provider level).
    #[tokio::test]
    async fn provider_returning_none_falls_back_to_ambient() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec).with_credentials(Arc::new(provider_fn(|_| Ok(None))));
        gh.pr_list(Path::new("/r")).await.unwrap();
        assert!(
            !rec.only_call()
                .envs
                .iter()
                .any(|(k, _)| k.to_str() == Some("GH_TOKEN")),
            "Ok(None) provider injects no token (ambient)"
        );
    }

    #[tokio::test]
    async fn injected_token_overrides_ambient_default_env() {
        // A provider token is applied after any `default_env("GH_TOKEN", …)`, so it
        // wins — "I supplied a provider, use it" beats an ambient env default.
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec)
            .default_env("GH_TOKEN", "ambient-token")
            .with_credentials(Arc::new(StaticCredential::token("provider-token")));
        gh.pr_list(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        let winner = call
            .envs
            .iter()
            .rev()
            .find(|(k, _)| k.to_str() == Some("GH_TOKEN"))
            .and_then(|(_, v)| v.as_ref())
            .and_then(|v| v.to_str());
        assert_eq!(winner, Some("provider-token"), "provider token wins");
    }

    // --- Enterprise host + host-scoped auth (T-046) ------------------------

    // GitHubHost classifies github.com (any case) as SaaS and every other valid
    // host as GHES, canonicalizing to a lower-cased hostname.
    #[test]
    fn github_host_classifies_saas_and_enterprise() {
        let saas = GitHubHost::github_com();
        assert!(saas.is_github_com() && !saas.is_enterprise());
        assert_eq!(saas.as_str(), "github.com");

        for h in ["github.com", "GitHub.com", "GITHUB.COM"] {
            let host = GitHubHost::new(h).unwrap();
            assert!(host.is_github_com(), "{h} should classify as SaaS");
            assert_eq!(host.as_str(), "github.com", "canonicalized to lower-case");
        }

        let ghes = GitHubHost::new("GHE.Example.COM").unwrap();
        assert!(ghes.is_enterprise());
        assert_eq!(ghes.as_str(), "ghe.example.com");
    }

    // A malformed hostname is a diagnosable invalid-input error, not a silent
    // github.com guess — so a bad host can't quietly become the SaaS default.
    #[test]
    fn github_host_new_rejects_malformed_hosts() {
        for bad in [
            "",
            "  ",
            "-evil",
            "has space",
            "https://github.com",
            "github.com/owner",
            "ghe.example.com:8443",
            "user@github.com",
            ".leading",
            "trailing.",
        ] {
            let err = GitHubHost::new(bad).unwrap_err();
            assert!(
                vcs_cli_support::is_invalid_input(&err),
                "{bad:?} should be rejected as invalid input, got {err:?}"
            );
        }
    }

    // from_remote_url derives + classifies the host across HTTPS / SSH / scp-like
    // remotes, dropping userinfo and port.
    #[test]
    fn github_host_from_remote_url_parses_and_classifies() {
        let cases = [
            ("https://github.com/o/r.git", "github.com", false),
            (
                "https://x-access-token:tok@ghe.example.com:8443/o/r",
                "ghe.example.com",
                true,
            ),
            ("http://ghe.internal.corp/o/r", "ghe.internal.corp", true),
            ("ssh://git@github.com/o/r", "github.com", false),
            ("ssh://git@ghe.example.com:22/o/r", "ghe.example.com", true),
            ("git@github.com:o/r.git", "github.com", false),
            ("git@ghe.example.com:o/r.git", "ghe.example.com", true),
        ];
        for (url, host, enterprise) in cases {
            let parsed =
                GitHubHost::from_remote_url(url).unwrap_or_else(|e| panic!("parse {url}: {e:?}"));
            assert_eq!(parsed.as_str(), host, "host for {url}");
            assert_eq!(parsed.is_enterprise(), enterprise, "class for {url}");
        }
    }

    // An unparseable / hostless / ambiguous remote is a diagnosable error, never a
    // silent github.com fallback (which would authenticate the wrong host).
    #[test]
    fn github_host_from_remote_url_rejects_ambiguous() {
        for url in [
            "",
            "   ",
            "not-a-url",
            "https://",
            "ssh://",
            "git@internalhost:repo.git",
            "C:\\repo\\path",
            "https://[::1]:8443/x",
        ] {
            let err = GitHubHost::from_remote_url(url).unwrap_err();
            assert!(
                vcs_cli_support::is_invalid_input(&err),
                "{url:?} should be a diagnosable error, got {err:?}"
            );
        }
    }

    // Binding a github.com host injects the credential as GH_TOKEN (the SaaS
    // default) and pins GH_HOST — never the enterprise env.
    #[tokio::test]
    async fn with_host_github_com_injects_gh_token() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec)
            .with_host(GitHubHost::github_com())
            .with_token("saas-tok");
        gh.pr_list(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        assert!(call.env_is("GH_TOKEN", "saas-tok"));
        assert!(
            !call.has_env("GH_ENTERPRISE_TOKEN"),
            "github.com must not touch the enterprise token env"
        );
        assert!(call.env_is("GH_HOST", "github.com"));
        assert!(!call.args_str().iter().any(|a| a.contains("saas-tok")));
    }

    // Binding a GHES host injects the credential as GH_ENTERPRISE_TOKEN — the env
    // gh reads for a non-github.com host — plus GH_HOST, and NEVER as GH_TOKEN, so
    // an enterprise secret can't leak into the github.com token env. The secret
    // stays out of argv.
    #[tokio::test]
    async fn with_host_enterprise_injects_enterprise_token_and_host() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec)
            .with_host(GitHubHost::new("ghe.example.com").unwrap())
            .with_token("ent-tok");
        gh.pr_list(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        assert!(call.env_is("GH_ENTERPRISE_TOKEN", "ent-tok"));
        assert!(
            !call.has_env("GH_TOKEN"),
            "enterprise token must not land in the github.com env"
        );
        assert!(call.env_is("GH_HOST", "ghe.example.com"));
        assert!(
            !call.args_str().iter().any(|a| a.contains("ent-tok")),
            "secret must never appear in argv"
        );
    }

    // A host-bound client with NO provider injects no token at all (ambient gh
    // login for that host) but still pins GH_HOST, so gh targets the right server.
    #[tokio::test]
    async fn with_host_enterprise_without_credentials_is_ambient() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec).with_host(GitHubHost::new("ghe.corp.example").unwrap());
        gh.pr_list(Path::new("/r")).await.unwrap();
        let call = rec.only_call();
        assert!(!call.has_env("GH_ENTERPRISE_TOKEN"));
        assert!(!call.has_env("GH_TOKEN"));
        assert!(call.env_is("GH_HOST", "ghe.corp.example"));
    }

    // Several hosts, one client each: every client injects only its own host's
    // token/env — a credential for one host never leaks into another.
    #[tokio::test]
    async fn multiple_hosts_inject_independently() {
        let rec_a = RecordingRunner::replying(Reply::ok("[]"));
        GitHub::with_runner(&rec_a)
            .with_host(GitHubHost::new("ghe.a.example").unwrap())
            .with_token("tok-a")
            .pr_list(Path::new("/r"))
            .await
            .unwrap();

        let rec_b = RecordingRunner::replying(Reply::ok("[]"));
        GitHub::with_runner(&rec_b)
            .with_host(GitHubHost::new("ghe.b.example").unwrap())
            .with_token("tok-b")
            .pr_list(Path::new("/r"))
            .await
            .unwrap();

        let rec_saas = RecordingRunner::replying(Reply::ok("[]"));
        GitHub::with_runner(&rec_saas)
            .with_host(GitHubHost::github_com())
            .with_token("tok-saas")
            .pr_list(Path::new("/r"))
            .await
            .unwrap();

        let ca = rec_a.only_call();
        assert!(ca.env_is("GH_ENTERPRISE_TOKEN", "tok-a") && ca.env_is("GH_HOST", "ghe.a.example"));
        assert!(
            !ca.args_str()
                .iter()
                .any(|s| s.contains("tok-b") || s.contains("tok-saas")),
            "host A must not carry another host's secret"
        );

        let cb = rec_b.only_call();
        assert!(cb.env_is("GH_ENTERPRISE_TOKEN", "tok-b") && cb.env_is("GH_HOST", "ghe.b.example"));

        let cs = rec_saas.only_call();
        assert!(cs.env_is("GH_TOKEN", "tok-saas") && cs.env_is("GH_HOST", "github.com"));
        assert!(!cs.has_env("GH_ENTERPRISE_TOKEN"));
    }

    // A HOST-KEYED provider on a host-bound client injects ONLY that host's secret,
    // into the env gh reads for it — and a client bound to a *different* host draws a
    // different secret from the SAME provider, so one instance's token never lands in
    // another's command. (T-045: the bound host now reaches the CredentialRequest, so
    // the provider can tell SaaS from a self-hosted GHES instance.)
    #[tokio::test]
    async fn host_keyed_provider_injects_only_the_bound_hosts_token() {
        // Typed as the trait object so `Arc::clone` yields `Arc<dyn …>` directly
        // (the unsized coercion doesn't flow back through `Arc::clone`'s inference).
        let provider: Arc<dyn CredentialProvider> =
            Arc::new(provider_fn(|r: &CredentialRequest<'_>| {
                Ok(match r.host {
                    Some("github.com") => Some(Credential::token("saas-secret")),
                    Some("ghe.example.com") => Some(Credential::token("ent-secret")),
                    _ => None,
                })
            }));

        // SaaS client → GH_TOKEN carries the github.com secret, never the ent one.
        let rec_saas = RecordingRunner::replying(Reply::ok("[]"));
        GitHub::with_runner(&rec_saas)
            .with_host(GitHubHost::github_com())
            .with_credentials(Arc::clone(&provider))
            .pr_list(Path::new("/r"))
            .await
            .unwrap();
        let cs = rec_saas.only_call();
        assert!(cs.env_is("GH_TOKEN", "saas-secret"));
        assert!(!cs.has_env("GH_ENTERPRISE_TOKEN"));
        assert!(!cs.args_str().iter().any(|a| a.contains("saas-secret")));

        // Enterprise client → the ENT secret in GH_ENTERPRISE_TOKEN only, from the
        // very same provider; the github.com token env is untouched.
        let rec_ent = RecordingRunner::replying(Reply::ok("[]"));
        GitHub::with_runner(&rec_ent)
            .with_host(GitHubHost::new("ghe.example.com").unwrap())
            .with_credentials(Arc::clone(&provider))
            .pr_list(Path::new("/r"))
            .await
            .unwrap();
        let ce = rec_ent.only_call();
        assert!(ce.env_is("GH_ENTERPRISE_TOKEN", "ent-secret"));
        assert!(
            !ce.has_env("GH_TOKEN"),
            "the enterprise command must not carry the github.com token env"
        );
        assert!(!ce.args_str().iter().any(|a| a.contains("ent-secret")));
    }

    // Fallback policy, read vs write — `Ok(None)` (a host-keyed provider with nothing
    // for this host) leaves the command on ambient gh auth (no token env injected)
    // for BOTH a read (`pr_list`) and a write (`pr_merge`). (T-045)
    #[tokio::test]
    async fn provider_none_defers_to_ambient_for_read_and_write() {
        let rec_read = RecordingRunner::replying(Reply::ok("[]"));
        GitHub::with_runner(&rec_read)
            .with_host(GitHubHost::github_com())
            .with_credentials(Arc::new(provider_fn(|_r: &CredentialRequest<'_>| Ok(None))))
            .pr_list(Path::new("/r"))
            .await
            .unwrap();
        let cr = rec_read.only_call();
        assert!(
            !cr.has_env("GH_TOKEN") && !cr.has_env("GH_ENTERPRISE_TOKEN"),
            "read defers to ambient on Ok(None)"
        );

        let rec_write = RecordingRunner::replying(Reply::ok(""));
        GitHub::with_runner(&rec_write)
            .with_host(GitHubHost::github_com())
            .with_credentials(Arc::new(provider_fn(|_r: &CredentialRequest<'_>| Ok(None))))
            .pr_merge(Path::new("/r"), 7, PrMerge::squash())
            .await
            .unwrap();
        let cw = rec_write.only_call();
        assert!(
            !cw.has_env("GH_TOKEN") && !cw.has_env("GH_ENTERPRISE_TOKEN"),
            "write defers to ambient on Ok(None)"
        );
    }

    // Fallback policy, read vs write — a provider `Err` is FAIL-CLOSED: it aborts the
    // operation rather than silently running on ambient auth, proven separately for a
    // read (`pr_list`) and a write (`pr_merge`). gh is never spawned: the error
    // surfaces in `prepare`, before the process. (T-045)
    #[tokio::test]
    async fn provider_error_aborts_read_and_write_fail_closed() {
        fn boom() -> Arc<dyn CredentialProvider> {
            Arc::new(provider_fn(|_r: &CredentialRequest<'_>| {
                Err(Error::spawn(
                    BINARY,
                    std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "vault down"),
                ))
            }))
        }

        let rec_read = RecordingRunner::replying(Reply::ok("[]"));
        let read = GitHub::with_runner(&rec_read)
            .with_host(GitHubHost::github_com())
            .with_credentials(boom())
            .pr_list(Path::new("/r"))
            .await;
        assert!(read.is_err(), "a provider error must abort the read");
        assert!(
            rec_read.calls().is_empty(),
            "gh must not spawn when the provider errored (read)"
        );

        let rec_write = RecordingRunner::replying(Reply::ok(""));
        let write = GitHub::with_runner(&rec_write)
            .with_host(GitHubHost::github_com())
            .with_credentials(boom())
            .pr_merge(Path::new("/r"), 7, PrMerge::squash())
            .await;
        assert!(write.is_err(), "a provider error must abort the write");
        assert!(
            rec_write.calls().is_empty(),
            "gh must not spawn when the provider errored (write)"
        );
    }

    // auth_status_for pins `--hostname <host>` and reflects the exit code as a bool.
    #[tokio::test]
    async fn auth_status_for_scopes_to_hostname() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        let host = GitHubHost::new("ghe.example.com").unwrap();
        assert!(gh.auth_status_for(&host).await.unwrap());
        assert_eq!(
            rec.only_call().args_str(),
            ["auth", "status", "--hostname", "ghe.example.com"]
        );
    }

    // The scoped probe reports the TARGET host truthfully even when a DIFFERENT
    // host's session is broken — no false negative from the aggregate `gh auth
    // status` that the unscoped `auth_status` would fold together.
    #[tokio::test]
    async fn auth_status_for_is_independent_of_other_host_sessions() {
        let runner = ScriptedRunner::new()
            .on(
                ["gh", "auth", "status", "--hostname", "broken.example.com"],
                Reply::fail(1, "not logged in to broken.example.com"),
            )
            .on(
                ["gh", "auth", "status", "--hostname", "good.example.com"],
                Reply::ok(""),
            );
        let gh = GitHub::with_runner(runner);
        assert!(
            gh.auth_status_for(&GitHubHost::new("good.example.com").unwrap())
                .await
                .unwrap(),
            "the healthy target host reads as authenticated"
        );
        assert!(
            !gh.auth_status_for(&GitHubHost::new("broken.example.com").unwrap())
                .await
                .unwrap(),
            "a broken host reads as not authenticated, independently"
        );
    }

    // The bound view forwards auth_status_for verbatim (a bare, dir-independent
    // method): byte-identical argv, no cwd bound.
    #[tokio::test]
    async fn bound_view_auth_status_for_matches_client() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.at(Path::new("/repo"))
            .auth_status_for(&GitHubHost::github_com())
            .await
            .unwrap();
        let call = rec.only_call();
        assert_eq!(
            call.args_str(),
            ["auth", "status", "--hostname", "github.com"]
        );
        assert_eq!(call.cwd.as_deref(), None, "bare method binds no cwd");
    }

    #[tokio::test]
    async fn pr_feedback_requests_reviews_and_comments() {
        let json = r#"{"reviews":[{"author":{"login":"a"},"state":"APPROVED",
            "body":"","submittedAt":""}],"comments":[]}"#;
        let rec =
            RecordingRunner::new(ScriptedRunner::new().on(["gh", "pr", "view"], Reply::ok(json)));
        let gh = GitHub::with_runner(&rec);
        let feedback = gh.pr_feedback(Path::new("."), 7).await.expect("feedback");
        assert_eq!(feedback.reviews[0].author, "a");
        assert!(feedback.comments.is_empty());
        assert_eq!(
            rec.only_call().args_str(),
            ["pr", "view", "7", "--json", "reviews,comments"]
        );
    }

    // run_list appends --branch only when given one.
    #[tokio::test]
    async fn run_list_appends_branch_only_when_some() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec);
        gh.run_list(Path::new("/r"), 5, None).await.expect("list");
        gh.run_list(Path::new("/r"), 5, Some("main".into()))
            .await
            .expect("list");
        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            ["run", "list", "--limit", "5", "--json", RUN_FIELDS]
        );
        assert_eq!(
            calls[1].args_str(),
            [
                "run", "list", "--limit", "5", "--branch", "main", "--json", RUN_FIELDS
            ]
        );
    }

    #[tokio::test]
    async fn workflow_list_builds_default_and_disabled_inclusive_argv() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let gh = GitHub::with_runner(&rec);
        gh.workflow_list(Path::new("/r")).await.expect("list");
        gh.at(Path::new("/r"))
            .workflow_list_with(WorkflowList::new().all().limit(75))
            .await
            .expect("list all");

        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            [
                "workflow",
                "list",
                "--limit",
                "50",
                "--json",
                WORKFLOW_FIELDS
            ]
        );
        assert_eq!(
            calls[1].args_str(),
            [
                "workflow",
                "list",
                "--limit",
                "75",
                "--all",
                "--json",
                WORKFLOW_FIELDS
            ]
        );
        assert_eq!(calls[1].cwd.as_deref(), Some(Path::new("/r")));
    }

    #[tokio::test]
    async fn workflow_list_rejects_zero_limit_before_spawn() {
        let rec = RecordingRunner::replying(Reply::ok("[]"));
        let err = GitHub::with_runner(&rec)
            .workflow_list_with(Path::new("/r"), WorkflowList::new().limit(0))
            .await
            .unwrap_err();
        assert!(vcs_cli_support::is_invalid_input(&err));
        assert!(rec.calls().is_empty());
    }

    #[tokio::test]
    async fn workflow_view_resolves_id_name_filename_and_path_from_json_inventory() {
        let json = r#"[
            {"id":17,"name":"CI","path":".github/workflows/ci.yml","state":"active"},
            {"id":18,"name":"Deploy","path":".github/workflows/deploy.yaml","state":"disabled_manually"}
        ]"#;
        let rec = RecordingRunner::new(
            ScriptedRunner::new().on(["gh", "workflow", "list"], Reply::ok(json)),
        );
        let gh = GitHub::with_runner(&rec);

        assert_eq!(
            gh.workflow_view(Path::new("/r"), "17").await.unwrap().id,
            17
        );
        assert_eq!(
            gh.workflow_view(Path::new("/r"), "ci").await.unwrap().id,
            17
        );
        assert_eq!(
            gh.workflow_view(Path::new("/r"), "deploy.yaml")
                .await
                .unwrap()
                .id,
            18
        );
        assert_eq!(
            gh.workflow_view(Path::new("/r"), ".github/workflows/ci.yml")
                .await
                .unwrap()
                .id,
            17
        );

        for call in rec.calls() {
            assert_eq!(
                call.args_str(),
                [
                    "workflow",
                    "list",
                    "--limit",
                    WORKFLOW_VIEW_LOOKUP_LIMIT.to_string().as_str(),
                    "--all",
                    "--json",
                    WORKFLOW_FIELDS
                ]
            );
        }
    }

    #[tokio::test]
    async fn workflow_view_reports_empty_missing_and_ambiguous_selectors() {
        let rec = RecordingRunner::replying(Reply::ok(
            r#"[
                {"id":17,"name":"CI","path":".github/workflows/ci.yml","state":"active"},
                {"id":18,"name":"ci","path":".github/workflows/other.yml","state":"active"}
            ]"#,
        ));
        let gh = GitHub::with_runner(&rec);

        let empty = gh.workflow_view(Path::new("/r"), "").await.unwrap_err();
        assert!(vcs_cli_support::is_invalid_input(&empty));
        assert!(rec.calls().is_empty(), "empty selector must not spawn");

        for selector in ["missing", "CI"] {
            assert!(matches!(
                gh.workflow_view(Path::new("/r"), selector)
                    .await
                    .unwrap_err()
                    .reason(),
                ErrorReason::Parse { .. }
            ));
        }
        assert_eq!(rec.calls().len(), 2);
    }

    // run_watch blocks on `run watch` (no `--exit-status`, so a failed run still
    // exits 0 — the outcome is read via the follow-up view, the only channel
    // that can distinguish failed from cancelled).
    #[tokio::test]
    async fn run_watch_then_views_final_state() {
        let json = r#"{"databaseId":42,"name":"CI","displayTitle":"t",
            "status":"completed","conclusion":"failure","workflowName":"CI",
            "headBranch":"main","event":"push","url":"u","createdAt":"c"}"#;
        let rec = RecordingRunner::new(
            ScriptedRunner::new()
                .on(["gh", "run", "watch"], Reply::ok("✓ run completed"))
                .on(["gh", "run", "view"], Reply::ok(json)),
        );
        let gh = GitHub::with_runner(&rec);
        let run = gh.run_watch(Path::new("."), 42).await.expect("run_watch");
        assert_eq!(run.conclusion, "failure");
        let calls = rec.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].args_str(), ["run", "watch", "42"]);
        assert_eq!(
            calls[1].args_str(),
            ["run", "view", "42", "--json", RUN_FIELDS]
        );
    }

    // A timed-out or failing watch must error — NOT report a half-finished run
    // via the follow-up view. (`output_string` does not error on a timeout; the
    // `ensure_success` in run_watch is what surfaces it.)
    #[tokio::test]
    async fn run_watch_surfaces_timeout_and_watch_errors() {
        let rec = RecordingRunner::new(
            ScriptedRunner::new().on(["gh", "run", "watch"], Reply::timeout()),
        );
        let gh = GitHub::with_runner(&rec);
        assert!(matches!(
            gh.run_watch(Path::new("."), 42).await.unwrap_err().reason(),
            ErrorReason::Timeout { .. }
        ));
        assert_eq!(rec.calls().len(), 1, "no view after a timed-out watch");

        let gh = GitHub::with_runner(
            ScriptedRunner::new().on(["gh", "run", "watch"], Reply::fail(1, "no such run")),
        );
        assert!(matches!(
            gh.run_watch(Path::new("."), 42).await.unwrap_err().reason(),
            ErrorReason::Exit { .. }
        ));
    }

    // ProcessKit 3.1's watchdog makes a quiet `gh run watch` fail promptly instead
    // of leaving the caller parked forever; a chatty watch is unaffected.
    #[tokio::test(start_paused = true)]
    async fn run_watch_times_out_after_output_inactivity() {
        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "run", "watch"], Reply::pending()));
        match gh.run_watch(Path::new("."), 42).await.unwrap_err().reason() {
            ErrorReason::Timeout {
                timeout,
                inactivity,
                ..
            } => {
                assert_eq!(*timeout, RUN_WATCH_INACTIVITY_TIMEOUT);
                assert!(*inactivity);
            }
            other => panic!("expected output-inactivity timeout, got {other:?}"),
        }
    }

    // Client-level cancellation (processkit 0.8 `cancellation` feature): a client
    // built with `default_cancel_on(token)` threads the token into every command it
    // builds. It still wins over the 3.1 output-inactivity watchdog, so a controller
    // can cancel a long watch without touching the call site (zero new vcs-* API).
    #[tokio::test(start_paused = true)]
    async fn run_watch_cancels_via_client_default_token() {
        use processkit::CancellationToken;
        let token = CancellationToken::new();
        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "run", "watch"], Reply::pending()))
                .default_cancel_on(token.clone());
        let call = gh.run_watch(Path::new("."), 42);
        tokio::pin!(call);
        assert!(
            tokio::time::timeout(Duration::from_secs(1), &mut call)
                .await
                .is_err(),
            "run_watch must remain pending until cancellation or its inactivity deadline"
        );
        token.cancel();
        match call.await.map_err(Error::into_reason) {
            Err(ErrorReason::Cancelled { program }) => assert_eq!(program, "gh"),
            other => panic!("expected ErrorReason::Cancelled, got {other:?}"),
        }
    }

    // workflow_dispatch with a ref and two inputs pins the empirically-verified
    // `gh workflow run` argv (gh 2.95.0): the bare `<workflow>` positional, then
    // `--ref <ref>`, then each input as `--raw-field key=value` in the order added.
    // `--raw-field` (not `--field`) is deliberate — `--field`'s `@value` reads a
    // file, so the raw form keeps an arbitrary input value a literal string.
    #[tokio::test]
    async fn workflow_dispatch_builds_argv_with_ref_and_inputs() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.workflow_dispatch(
            Path::new("/repo"),
            WorkflowDispatch::new("release.yml")
                .git_ref("main")
                .field("name", "scully")
                .field("greeting", "hello"),
        )
        .await
        .expect("workflow_dispatch");
        let call = rec.only_call();
        assert_eq!(call.cwd.as_deref(), Some(Path::new("/repo")));
        assert_eq!(
            call.args_str(),
            [
                "workflow",
                "run",
                "release.yml",
                "--ref",
                "main",
                "--raw-field",
                "name=scully",
                "--raw-field",
                "greeting=hello",
            ]
        );
    }

    // With only the workflow selector, neither `--ref` nor any `--raw-field` is
    // emitted — a minimal `gh workflow run <workflow>`. A value beginning with `-`
    // rides safely in the `--raw-field` flag-VALUE slot (proving it is not guarded
    // away like a bare positional would be).
    #[tokio::test]
    async fn workflow_dispatch_omits_unset_ref_and_allows_dash_value() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.workflow_dispatch(Path::new("/r"), WorkflowDispatch::new("ci.yml"))
            .await
            .expect("workflow_dispatch");
        assert_eq!(rec.calls()[0].args_str(), ["workflow", "run", "ci.yml"]);

        // A leading-`-` input VALUE is legitimate and passed verbatim.
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.workflow_dispatch(
            Path::new("/r"),
            WorkflowDispatch::new("ci.yml").field("flag", "-x"),
        )
        .await
        .expect("workflow_dispatch");
        assert_eq!(
            rec.only_call().args_str(),
            ["workflow", "run", "ci.yml", "--raw-field", "flag=-x"]
        );
    }

    // The bare `<workflow>` positional is flag-injection guarded before spawning,
    // like `release_view`/`api` — a leading-`-` or empty selector is refused and
    // nothing spawns.
    #[tokio::test]
    async fn workflow_dispatch_rejects_flag_like_workflow() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        assert!(
            gh.workflow_dispatch(Path::new("."), WorkflowDispatch::new("-evil"))
                .await
                .is_err()
        );
        assert!(
            gh.workflow_dispatch(Path::new("."), WorkflowDispatch::new(""))
                .await
                .is_err()
        );
        assert!(rec.calls().is_empty(), "nothing may spawn");
    }

    // Input keys name the left side of gh's `--raw-field key=value` boundary, so an
    // empty key or `=` would silently target a different input. Validation must run
    // before the runner; this ScriptedRunner has no matching command on purpose.
    #[tokio::test]
    async fn workflow_dispatch_rejects_invalid_input_keys_before_spawning() {
        let gh = GitHub::with_runner(ScriptedRunner::new());
        for key in ["", "a=b", "\0"] {
            let err = gh
                .workflow_dispatch(
                    Path::new("."),
                    WorkflowDispatch::new("ci.yml").field(key, "value"),
                )
                .await
                .unwrap_err();
            assert!(
                vcs_cli_support::is_invalid_input(&err),
                "{key:?} should be rejected before spawning, got {err:?}"
            );
        }
    }

    // run_rerun pins `gh run rerun <id>` (All) and `gh run rerun <id> --failed`
    // (FailedOnly). The u64 id can never look like a flag, so there is no guard.
    #[tokio::test]
    async fn run_rerun_builds_argv_for_each_scope() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.run_rerun(Path::new("/r"), 42, RerunScope::All)
            .await
            .expect("rerun all");
        gh.run_rerun(Path::new("/r"), 42, RerunScope::FailedOnly)
            .await
            .expect("rerun failed");
        let calls = rec.calls();
        assert_eq!(calls[0].args_str(), ["run", "rerun", "42"]);
        assert!(!calls[0].has_flag("--failed"), "All reruns the whole run");
        assert_eq!(calls[1].args_str(), ["run", "rerun", "42", "--failed"]);
    }

    // run_cancel pins `gh run cancel <id>`.
    #[tokio::test]
    async fn run_cancel_builds_argv() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let gh = GitHub::with_runner(&rec);
        gh.run_cancel(Path::new("/r"), 42).await.expect("cancel");
        assert_eq!(rec.only_call().args_str(), ["run", "cancel", "42"]);
    }

    // A non-zero gh exit on a run-control verb surfaces as `ErrorReason::Exit`, not a
    // swallowed success (e.g. cancelling an already-completed run, gh exit 1).
    #[tokio::test]
    async fn run_control_surfaces_gh_exit_errors() {
        let gh = GitHub::with_runner(ScriptedRunner::new().on(
            ["gh", "run", "cancel"],
            Reply::fail(1, "Cannot cancel a workflow run that is completed"),
        ));
        assert!(matches!(
            gh.run_cancel(Path::new("."), 42)
                .await
                .unwrap_err()
                .reason(),
            ErrorReason::Exit { .. }
        ));

        let gh = GitHub::with_runner(ScriptedRunner::new().on(
            ["gh", "workflow", "run"],
            Reply::fail(
                1,
                "HTTP 404: workflow x.yml not found on the default branch",
            ),
        ));
        assert!(matches!(
            gh.workflow_dispatch(Path::new("."), WorkflowDispatch::new("x.yml"))
                .await
                .unwrap_err()
                .reason(),
            ErrorReason::Exit { .. }
        ));
    }

    // Replays a cassette recorded against a live `gh release list`/`release
    // view` on this very repo (crates/github/tests/cli.rs's
    // `record_release_round_trip`) instead of a hand-invented JSON payload —
    // K-037 exists precisely because a hand-picked field set can silently
    // diverge from what `release view --json` actually returns.
    #[tokio::test]
    async fn release_view_requests_view_fields() {
        let cassette = RecordReplayRunner::replay(cassette_path("release_round_trip.json"))
            .expect("load recorded release cassette");
        let rec = RecordingRunner::new(cassette);
        let gh = GitHub::with_runner(&rec);
        let releases = gh.release_list(Path::new(".")).await.expect("release_list");
        let tag = releases
            .first()
            .expect("recorded cassette has a release")
            .tag_name
            .clone();
        let release = gh
            .release_view(Path::new("."), &tag)
            .await
            .expect("release_view");
        assert_eq!(release.tag_name, tag);
        assert!(
            release.body.as_deref().is_some_and(|b| !b.is_empty()),
            "release notes were recorded"
        );
        assert!(release.url.as_deref().is_some_and(|u| !u.is_empty()));
        let calls = rec.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(
            calls[1].args_str(),
            [
                "release",
                "view",
                tag.as_str(),
                "--json",
                RELEASE_VIEW_FIELDS
            ]
        );
    }

    // Replays a cassette recorded against a live `gh run list`/`run view` on
    // this very repo (crates/github/tests/cli.rs's `record_run_round_trip`);
    // see the analogous `release_view_requests_view_fields` above.
    #[tokio::test]
    async fn run_list_and_view_replay_recorded_cassette() {
        let cassette = RecordReplayRunner::replay(cassette_path("run_round_trip.json"))
            .expect("load recorded run cassette");
        let rec = RecordingRunner::new(cassette);
        let gh = GitHub::with_runner(&rec);
        let runs = gh
            .run_list(Path::new("."), 3, None)
            .await
            .expect("run_list");
        let first = runs.first().expect("recorded cassette has runs");
        assert!(first.database_id > 0);
        assert!(!first.workflow_name.is_empty());
        let run = gh
            .run_view(Path::new("."), first.database_id)
            .await
            .expect("run_view");
        assert_eq!(run.database_id, first.database_id);
        assert_eq!(run.workflow_name, first.workflow_name);
        let calls = rec.calls();
        assert_eq!(calls.len(), 2);
        assert_eq!(
            calls[0].args_str(),
            ["run", "list", "--limit", "3", "--json", RUN_FIELDS]
        );
        assert_eq!(
            calls[1].args_str(),
            [
                "run",
                "view",
                first.database_id.to_string().as_str(),
                "--json",
                RUN_FIELDS
            ]
        );
    }

    // repo_view builds the --json request and flattens gh's nested owner/branch
    // objects into the public RepoView.
    #[tokio::test]
    async fn repo_view_parses_scripted_json() {
        let json = r#"{"name":"r","owner":{"login":"o"},"description":"d","url":"u","isPrivate":false,"defaultBranchRef":{"name":"main"}}"#;
        let gh =
            GitHub::with_runner(ScriptedRunner::new().on(["gh", "repo", "view"], Reply::ok(json)));
        let repo = gh.repo_view(Path::new(".")).await.expect("repo_view");
        assert_eq!(repo.owner, "o");
        assert_eq!(repo.default_branch, "main");
        assert!(!repo.is_private);
    }

    #[cfg(feature = "mock")]
    #[tokio::test]
    async fn consumer_mocks_the_interface() {
        let mut mock = MockGitHubApi::new();
        mock.expect_auth_status().returning(|| Ok(true));
        assert!(mock.auth_status().await.unwrap());
    }
}

#[cfg(test)]
mod label_tests {
    use super::*;
    use processkit::testing::{RecordingRunner, Reply};

    #[tokio::test]
    async fn label_create_and_mutation_argv_are_exact_and_flag_values() {
        let rec = RecordingRunner::replying(Reply::ok("https://example.test/1\n"));
        let gh = GitHub::with_runner(&rec);
        let labels = vec!["-urgent".to_string(), "help wanted".to_string()];

        gh.pr_create(
            Path::new("/repo"),
            PrCreate::new("T", "B").labels(labels.clone()),
        )
        .await
        .unwrap();
        gh.issue_create_with(
            Path::new("/repo"),
            IssueCreate::new("I", "D").labels(labels.clone()),
        )
        .await
        .unwrap();
        gh.at(Path::new("/repo"))
            .pr_add_labels(7, &labels)
            .await
            .unwrap();
        gh.pr_remove_labels(Path::new("/repo"), 7, &labels)
            .await
            .unwrap();
        gh.issue_add_labels(Path::new("/repo"), 9, &labels)
            .await
            .unwrap();
        gh.issue_remove_labels(Path::new("/repo"), 9, &labels)
            .await
            .unwrap();

        let calls = rec.calls();
        assert_eq!(
            calls[0].args_str(),
            [
                "pr",
                "create",
                "--title",
                "T",
                "--body",
                "B",
                "--label",
                "-urgent",
                "--label",
                "help wanted"
            ]
        );
        assert_eq!(
            calls[1].args_str(),
            [
                "issue",
                "create",
                "--title",
                "I",
                "--body",
                "D",
                "--label",
                "-urgent",
                "--label",
                "help wanted"
            ]
        );
        assert_eq!(
            calls[2].args_str(),
            [
                "pr",
                "edit",
                "7",
                "--add-label",
                "-urgent",
                "--add-label",
                "help wanted"
            ]
        );
        assert_eq!(calls[2].cwd.as_deref(), Some(Path::new("/repo")));
        assert_eq!(
            calls[3].args_str(),
            [
                "pr",
                "edit",
                "7",
                "--remove-label",
                "-urgent",
                "--remove-label",
                "help wanted"
            ]
        );
        assert_eq!(
            calls[4].args_str(),
            [
                "issue",
                "edit",
                "9",
                "--add-label",
                "-urgent",
                "--add-label",
                "help wanted"
            ]
        );
        assert_eq!(
            calls[5].args_str(),
            [
                "issue",
                "edit",
                "9",
                "--remove-label",
                "-urgent",
                "--remove-label",
                "help wanted"
            ]
        );
    }

    #[tokio::test]
    async fn empty_label_mutation_is_rejected_before_spawn() {
        let rec = RecordingRunner::replying(Reply::ok(""));
        let err = GitHub::with_runner(&rec)
            .pr_add_labels(Path::new("/repo"), 1, &[])
            .await
            .unwrap_err();
        assert!(vcs_cli_support::is_invalid_input(&err));
        assert!(rec.calls().is_empty());
    }
}

// Long-form how-to guides, rendered from this crate's docs/*.md on docs.rs.
#[doc = include_str!("../docs/github.md")]
#[allow(rustdoc::broken_intra_doc_links)]
pub mod guide {}