onevcs 0.51.2

Version control and remote-host abstraction for agent workflows: host-neutral change requests, sessions, and a rules system.
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
//! The remote-host side of the seam.
//!
//! Host-neutral vocabulary: the review unit is a [`ChangeRequest`]. GitHub maps it
//! to a pull request; a later host maps it to whatever it calls the same thing.

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

use serde::{Deserialize, Serialize};
use url::Url;

use crate::boundary::Visibility;
use crate::error::{invalid, Error, Result};
use crate::event::ArtifactId;
use crate::publish::DraftReason;
use crate::review::{CommentId, PostedReply, ReadCost, ReadMarker, ReviewRead};
use crate::rules::MergePolicy;
use crate::standings::{ChangeStandings, ReviewStandings};
use crate::{gh, git, review, standings, stream};

/// What `gh pr checks` exits with when a check it has just reported has not
/// settled. The rollup it printed is still the answer, so this status is read
/// alongside `0` rather than as a failure.
const CHECKS_PENDING: i32 = 8;

/// How `gh pr checks --required` opens its stderr when the repository declares no
/// required check at all — a repository with no branch protection genuinely has
/// none. The rest of that line names the branch, so only the prefix is fixed.
const NO_REQUIRED_CHECKS: &str = "no required checks reported on the ";

/// Whether a `gh pr checks` answer is one to read.
fn usable(answer: &gh::Answer) -> bool {
    matches!(answer.code, Some(0) | Some(CHECKS_PENDING))
}

/// How `gh pr checks` opens its stderr when the head carries no check **at all** —
/// which is every head for the first seconds after it is pushed. The rest of that
/// line names the branch, so only the prefix is fixed.
const NO_CHECKS_YET: &str = "no checks reported on the ";

/// Whether a failing `gh pr checks --required` failed by *answering* "none".
///
/// The whole shape, not a substring anywhere in the output: `gh` exits `1`, writes
/// nothing to stdout, and opens stderr with [`NO_REQUIRED_CHECKS`]. Measured against
/// real GitHub — a repository with no branch protection answers exactly that. It is
/// held to all three because this is the one place a *failed* `gh` call is read as a
/// meaningful answer, and a looser test would swallow an unrelated failure whose
/// message happened to contain the phrase, reporting "nothing blocks the merge"
/// about a host that never said so.
fn no_required_checks(answer: &gh::Answer) -> bool {
    answer.code == Some(1)
        && answer.stdout.trim().is_empty()
        && answer.stderr.trim_start().starts_with(NO_REQUIRED_CHECKS)
}

/// Whether a failing `gh pr checks` failed by reporting **no check at all** on the
/// head, which is not an answer about what blocks the merge.
///
/// Held to the same three facts as [`no_required_checks`], and one word of `gh`'s own
/// wording apart from it. Reading this one as that one would wave a merge through on
/// a head no verification has begun on.
fn no_checks_yet(answer: &gh::Answer) -> bool {
    answer.code == Some(1)
        && answer.stdout.trim().is_empty()
        && answer.stderr.trim_start().starts_with(NO_CHECKS_YET)
}

/// How `gh api` reports a branch that has no classic protection at all — GitHub's
/// own message, which is an answer (the source names nothing) and not a refusal.
const NOT_PROTECTED: &str = "Branch not protected";

/// Which of the host's check sources a call may consult.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Consult {
    /// The rollup, and Actions when the credential is not allowed to read it.
    Either,
    /// The complete status-check rollup only.
    StatusChecks,
    /// Actions jobs together with the branch rules that say which ones block.
    Actions,
}

/// What [`gh::CHECK_SOURCE_ENV`] narrows a call to, or [`Consult::Either`].
///
/// The knob exists because the fallback is not free: a credential that will never
/// be allowed to read check runs is refused *every* time the rollup is asked,
/// which for a publication polling a change request is one failed call every few
/// seconds. An operator who knows their token is a fine-grained one says so once.
/// The value is checked here rather than acted on loosely — a misspelling that
/// silently meant "auto" would look like the fallback working.
fn consult() -> Result<Consult> {
    let Some(raw) = std::env::var_os(gh::CHECK_SOURCE_ENV) else {
        return Ok(Consult::Either);
    };
    match raw.to_string_lossy().trim().to_ascii_lowercase().as_str() {
        "" | "auto" => Ok(Consult::Either),
        "status-checks" => Ok(Consult::StatusChecks),
        "actions" => Ok(Consult::Actions),
        other => Err(invalid(format!(
            "{} names {other:?}, which is not a check source this build can read: it must be \
             \"auto\", \"status-checks\", or \"actions\"",
            gh::CHECK_SOURCE_ENV
        ))),
    }
}

/// Read the operator's check-source knob and answer whether it names a source.
///
/// Exposed so a publication can refuse a misspelling of it **before** it pushes: the
/// knob is input, and input is rejected at its boundary.
pub(crate) fn check_source_names_a_source() -> Result<()> {
    consult().map(|_| ())
}

/// How many entries an Actions listing is asked for at once, which is the most
/// GitHub will return in one page.
const PAGE: u32 = 100;

/// How GitHub declines something the credential is not allowed to reach, in both
/// the shapes it declines it in: a GraphQL error naming the node it would not
/// produce, and a REST 403. The wording is GitHub's, and it is the whole of the
/// test because it is the whole of what distinguishes the two cases below.
const CHECK_RUN_REFUSAL: &str = "GraphQL: Resource not accessible by personal access token";

/// Whether a refusal is one this credential will *always* get.
///
/// The one distinction the fallback turns on. A credential that may not read check
/// runs will never read them, so asking a narrower source instead is the only way
/// to answer at all — but a rollup that came back garbled, or a host that would not
/// say which of its checks block, is a *complete* answer having gone wrong, and
/// quietly answering from GitHub Actions alone would drop whatever a third-party
/// integration posted. A required check nobody looked at is how a merge that was
/// never gated ends up looking like one that was.
fn check_rollup_refused_for_pat(error: &Error) -> bool {
    let Error::Invalid { reason } = error else {
        return false;
    };
    reason.contains(CHECK_RUN_REFUSAL) && reason.contains("statusCheckRollup")
}

/// Everything `onevcs` asks of a repository's remote host.
pub trait RemoteHost {
    /// Who the host believes is calling.
    fn authenticated_user(&self) -> Result<String>;

    /// Open a change request.
    fn open_change(&self, req: ChangeSpec) -> Result<ChangeRequest>;

    /// Every open change request from `head` into `base`.
    fn find_changes(&self, head: &str, base: &str) -> Result<Vec<ChangeRequest>>;

    /// The checks the host is reporting on a change request, and which of its
    /// sources that answer was read from.
    fn change_checks(&self, cr: &ChangeRequest) -> Result<ChangeChecks>;

    /// Store one check's log as an artifact and return its id.
    fn check_log(&self, cr: &ChangeRequest, check: &Check) -> Result<ArtifactId>;

    /// Merge a change request under a policy.
    fn merge(&self, cr: &ChangeRequest, policy: MergePolicy) -> Result<MergeOutcome>;

    /// The commit a change request reached its base at, or `None` while the host
    /// has not merged it.
    ///
    /// What a publication under `change-auto` watches. The host performs that merge
    /// on its own clock — `merge` arms it and answers
    /// [`MergeOutcome::Queued`] — so the only way to learn that it happened, and at
    /// which commit, is to ask again. `None` is "not yet" and never "somewhere
    /// else": an implementation that cannot say must refuse rather than answer it.
    ///
    /// Defaulted so that an implementation written against the earlier surface
    /// still compiles, and defaulted to the refusal this crate reserves for a seam
    /// with no body rather than to `None` — a host that was never taught to answer
    /// this has not said a change is unmerged, and a publication that read it that
    /// way would watch until its bound and then report checks that were never the
    /// reason.
    fn merged_at(&self, _cr: &ChangeRequest) -> Result<Option<Sha>> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::merged_at",
        })
    }

    /// The commit a change request reached its base at **and the head the host merged
    /// it from**, or `None` while the host has not merged it.
    ///
    /// What a retirement asks before it may call a branch merged: a merge proves the
    /// *branch's* work landed only where the head that merged carries that work, and a
    /// change request whose number happens to match, or whose branch moved on after it
    /// merged, says nothing about what the branch holds now. Both halves come from one
    /// read of the host, so the head is the one the merge was of.
    ///
    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
    /// stays additive — and to the same refusal: a host never taught to say which head
    /// merged has not said that this branch's did, and a retirement reads the refusal
    /// as a question nobody answered, which keeps the branch.
    fn merged_head(&self, _cr: &ChangeRequest) -> Result<Option<MergedChange>> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::merged_head",
        })
    }

    /// When the host says a merged change request reached its base, as the host
    /// spelled it, or `None` while it has not merged it.
    ///
    /// What the record of a landing carries as `landed_at`, and the one way to learn
    /// it for a merge the host performed on its own clock — above all one this crate
    /// reconciles on a later read, whose landing time is the host's and never the
    /// moment somebody asked.
    ///
    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
    /// stays additive — and to the same refusal. A caller reads that refusal as a host
    /// that cannot say, and records the landing's time as unknown.
    fn merge_time(&self, _cr: &ChangeRequest) -> Result<Option<String>> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::merge_time",
        })
    }

    /// Whether a change request can still merge into its base, as the host has
    /// computed it.
    ///
    /// What a publication under `change-auto` reads beside
    /// [`merged_at`](RemoteHost::merged_at) while it waits for the merge it armed: a
    /// base that moved under the change so that it conflicts is a merge the host can
    /// never perform, and [`Mergeability::Conflicting`] ends that wait at once as a
    /// sync conflict rather than at the bound. [`Mergeability::Unknown`] is "not
    /// computed yet" and is never read as a conflict.
    ///
    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
    /// stays additive — and to the same refusal. A publication reads that refusal as a
    /// host that said nothing, which is no conflict, so a host written before this
    /// method watches exactly as it did.
    fn mergeability(&self, _cr: &ChangeRequest) -> Result<Mergeability> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::mergeability",
        })
    }

    /// Take a change request out of its draft state, so the host will let it land.
    ///
    /// What lifts a draft: a publication whose required checks came back green on it
    /// (or whose grace window elapsed with none run), `onevcs change ready`, and a
    /// publication adopting a draft with the lifecycle off. It is always asked
    /// **before** the host is asked to merge or arm a merge, because a host does
    /// neither to a draft.
    ///
    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
    /// stays additive — and to the same refusal: a host that was never taught to
    /// lift a draft has not lifted one, and answering `Ok(())` would report a change
    /// as ready for review while the host goes on holding it.
    fn ready_for_review(&self, _cr: &ChangeRequest) -> Result<()> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::ready_for_review",
        })
    }

    /// Whether the host is holding this change request as a draft.
    ///
    /// Asked on both sides of a draft's life: after one is opened, because a host
    /// that ignored the request would otherwise leave a landable change reported as
    /// held back; and before one is lifted, so a change nobody drafted is asked for
    /// nothing and a second lift changes nothing.
    ///
    /// Defaulted to the refusal, never to `false`: "this host was never taught to
    /// answer" and "this change is not a draft" are different facts, and only the
    /// second is a reason to go on and merge — which is what the `Result` around the
    /// answer carries, rather than a third value inside it.
    ///
    /// The answer is a `bool` because the approved amendment in `docs/contract.md`
    /// declares this seam verbatim as `-> Result<bool>`: a named domain type here would
    /// be a public item the contract does not name, which this repository reports rather
    /// than takes. Nothing is lost to the shape — the *third* state a caller must not
    /// confuse with "not a draft" is "this host would not say", and that is the `Err`
    /// arm rather than a value inside the `Ok`. Both call sites read it as one of three,
    /// and they are `hold_as_draft` and `lift_any_draft` in `publish.rs`.
    // llmlint: ignore[invalid_states_unrepresentable] the doc above: the contract fixes this seam.
    fn is_draft(&self, _cr: &ChangeRequest) -> Result<bool> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::is_draft",
        })
    }

    /// The checks the repository requires before anything merges into `base`, asked
    /// of the branch itself rather than of a change request targeting it.
    ///
    /// What `onevcs repos --audit-gates` names per identity. Which checks a
    /// repository requires is a setting on that repository, and a consumer that
    /// sequences its own work behind another repository's merge path had to keep a
    /// copy of that list — which drifted the day the repository renamed a check, and
    /// cost a whole gate to discover. The host holds the list; this is how it is
    /// read.
    ///
    /// The answer says which protection source it could not consult, because "this
    /// source found nothing" and "this merge path requires nothing" are opposite
    /// facts and only the second is safe to act on: an answer with a source in
    /// [`RequiredChecks::unconsulted`] is incomplete, and an empty one is *unknown*
    /// rather than none. A host that could read no source at all must refuse rather
    /// than answer, for the reason [`change_checks`](RemoteHost::change_checks) may
    /// not answer with an empty source list.
    ///
    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
    /// stays additive — and to the same refusal, which the audit reports as the list
    /// being unreadable rather than as no check being required.
    fn required_checks_on(&self, _base: &str) -> Result<RequiredChecks> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::required_checks_on",
        })
    }

    /// Whether the host requires a branch to be up to date with `base` before it
    /// merges a change request into it — GitHub branch protection's `strict`.
    ///
    /// What a branch whose identity merges its base `on-conflict` asks before leaving
    /// a moved base out of it: a host that requires an up-to-date branch would refuse
    /// to merge one that is not, so the base is merged in after all. Read from the
    /// same protection sources [`required_checks_on`](RemoteHost::required_checks_on)
    /// reads; `true` where any of them requires it, `false` only where every source
    /// was read and none does.
    ///
    /// Defaulted to the refusal for the reason every other added method is. A caller
    /// reads any refusal as "could not be read" and merges the base, which is what
    /// every build before this method did.
    fn requires_up_to_date(&self, _base: &str) -> Result<bool> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::requires_up_to_date",
        })
    }

    /// Whether the repository lets a change request be armed to merge itself once its
    /// required checks pass — GitHub's `allow_auto_merge`.
    ///
    /// What a `change-auto` or `change-direct` publication asks, **before it changes
    /// anything**, when its wait for the checks elapses with none of them red: a host
    /// that allows it has the draft lifted and its merge armed, so the change lands on
    /// the host's clock once the checks pass; one that does not is left as it was.
    ///
    /// Defaulted to the refusal for the reason every other added method is. A caller
    /// reads any refusal as "not allowed" and changes nothing.
    fn allows_auto_merge(&self) -> Result<bool> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::allows_auto_merge",
        })
    }

    /// Replace a change request's description: its body, and its title when one is
    /// given.
    ///
    /// The one write to a change request's prose after it exists. It writes exactly
    /// the caller's bytes — nothing is composed around the body and nothing of a
    /// draft's reason is rendered into it — because a body is what a reviewer reads
    /// and what a drafting caller may rewrite, and `onevcs change describe` is where
    /// a session's own evidence reaches it.
    ///
    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
    /// stays additive — and to the same refusal: a host that was never taught to
    /// describe a change has not described one.
    fn describe_change(
        &self,
        _cr: &ChangeRequest,
        _title: Option<&str>,
        _body: &str,
    ) -> Result<()> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::describe_change",
        })
    }

    /// Whether the repository is public, as the host says.
    ///
    /// Asked at every write that could reach a public destination, because which
    /// terms a write is checked against depends on it, and recorded in the registry.
    /// An organisation-internal repository is [`Visibility::Private`]: it is not
    /// readable by everybody.
    ///
    /// Defaulted for the reason [`merged_at`](RemoteHost::merged_at) is — the seam
    /// stays additive — and to the same refusal, which is recorded as
    /// [`Visibility::Unknown`] and treated as private.
    fn visibility(&self) -> Result<Visibility> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::visibility",
        })
    }

    /// What a change request's description is now: its title and its body, as the
    /// host holds them.
    ///
    /// The read beside [`describe_change`](RemoteHost::describe_change), and what
    /// `onevcs change show` answers with: a caller that wrote a description needs to
    /// see what it wrote, and a caller finishing one off needs to see what it starts
    /// from.
    ///
    /// Defaulted to the refusal for the reason every other added method is.
    fn change_description(&self, _cr: &ChangeRequest) -> Result<Description> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::change_description",
        })
    }

    /// A change request's review feedback: every review-thread comment, review
    /// summary and conversation comment created or edited after `since` (all of them
    /// when `since` is `None`), and every comment whose thread was resolved,
    /// unresolved or outdated since it, with the marker to pass next time.
    ///
    /// What [`review_comments`](crate::review_comments) asks. `ours` and
    /// `reply_marker` are set from the reply marker in a comment's body and from
    /// nothing else, and the marker is the implementation's own to spell.
    ///
    /// Defaulted to the refusal for the reason every other added method is.
    fn review_comments(
        &self,
        _change: &ChangeId,
        _since: Option<&ReadMarker>,
    ) -> Result<ReviewRead> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::review_comments",
        })
    }

    /// Post `body` as a reply to `comment`: in its thread where it is in one, and
    /// otherwise as a new conversation comment whose first line links it. Never
    /// resolves a thread.
    ///
    /// `body` is the whole of what is posted, the reply marker already its last line,
    /// and `key` is the idempotency key that marker carries, handed over for an
    /// implementation that keeps a record of its own. Finding a reply already
    /// carrying `key` is [`reply_to_comment`](crate::reply_to_comment)'s, under its
    /// lock, so this posts.
    ///
    /// Defaulted to the refusal for the reason every other added method is.
    fn reply_to_comment(
        &self,
        _change: &ChangeId,
        _comment: &CommentId,
        _body: &str,
        _key: &str,
    ) -> Result<PostedReply> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::reply_to_comment",
        })
    }

    /// Where each of `changes` stands — its state and the branch it merged into, its
    /// base, head, description, draft flag and its required checks' verdict — one per
    /// change request asked about, in the order asked, with what the read cost.
    ///
    /// `landing` on a merge is true exactly when it merged into `root`; `base_deleted`
    /// on a closed one is whether the origin still has its base. The verdict is the one
    /// a publication's watch would reach from the same rollup, against what the host
    /// declares a merge into each base requires. What [`change_standings`] asks, and
    /// what [`retarget_change`] and [`reopen_change`] read before and after they write.
    ///
    /// [`change_standings`]: crate::change_standings
    /// [`retarget_change`]: crate::retarget_change
    /// [`reopen_change`]: crate::reopen_change
    ///
    /// Defaulted to the refusal for the reason every other added method is.
    fn change_standings(&self, _root: &str, _changes: &[ChangeId]) -> Result<ChangeStandings> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::change_standings",
        })
    }

    /// [`change_standings`](RemoteHost::change_standings) carrying each change
    /// request's review feedback since the marker beside it, in one read: one
    /// [`ReviewRead`] per change request, in the order asked, each the one
    /// [`review_comments`](RemoteHost::review_comments) would answer from the same
    /// marker.
    ///
    /// Defaulted to the refusal for the reason every other added method is.
    fn review_standings(
        &self,
        _root: &str,
        _changes: &[(ChangeId, Option<ReadMarker>)],
    ) -> Result<ReviewStandings> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::review_standings",
        })
    }

    /// Move a change request onto `base`, writing `body` as its description in the
    /// same request where one is given, and answer what the write cost. Never changes
    /// whether it is a draft.
    ///
    /// Defaulted to the refusal for the reason every other added method is.
    fn retarget_change(
        &self,
        _change: &ChangeId,
        _base: &str,
        _body: Option<&str>,
    ) -> Result<ReadCost> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::retarget_change",
        })
    }

    /// Reopen a closed change request, as the draft it was where it was one, and answer
    /// what the write cost. Its base branch is already back on the origin.
    ///
    /// Defaulted to the refusal for the reason every other added method is.
    fn reopen_change(&self, _change: &ChangeId) -> Result<ReadCost> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::reopen_change",
        })
    }

    /// Whether work the host runs on the change request's head commit is still in
    /// progress: a workflow run, or a check suite that has at least one check run,
    /// not yet completed. Asked by a draft's watch only when its reported checks
    /// show nothing incomplete at an early-lift decision or at the after-lift
    /// "did not re-run" ending. Defaulted to the refusal, as `mergeability`
    /// is, and a refusal is read as no answer, never as "idle".
    ///
    /// The watch asks it about the change request at the commit it pushed, so
    /// `cr.head_sha` is that commit; an answer whose [`HeadActivity::head`] names
    /// another commit is read as no answer too.
    fn head_activity(&self, _cr: &ChangeRequest) -> Result<HeadActivity> {
        Err(Error::NotImplemented {
            operation: "RemoteHost::head_activity",
        })
    }
}

/// What a host says is still running on one commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeadActivity {
    /// The commit the host answered about, read off the host's own records.
    pub head: Sha,
    /// The host's name for each piece of work still in progress on it (a workflow
    /// run's name, an app's check suite); empty when nothing is.
    // llmlint: ignore[invalid_states_unrepresentable] the contract fixes this field as
    // the host's own names, carried for a reader and decided on only by emptiness.
    pub in_progress: Vec<String>,
    /// Whether every source of such work was consulted. `false` means only GitHub
    /// Actions' workflow runs were (a credential that cannot read check suites), so an
    /// external app's work is invisible to this answer.
    // llmlint: ignore[invalid_states_unrepresentable] the approved contract fixes this
    // field as `complete: bool` for the three consumers that restate it; it has exactly
    // two states, both meaningful, and no third a named type could exclude.
    pub complete: bool,
}

/// Whether a change request can merge into its base, as
/// [`RemoteHost::mergeability`] answers it.
///
/// `#[non_exhaustive]` so that a later state a host reports — a change that merges
/// cleanly and is blocked for another reason, say — is not a breaking change. A caller
/// matching on it reads anything it does not name as "not a conflict".
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Mergeability {
    /// The host computed it, and the change merges into its base as it stands.
    Mergeable,
    /// The host confirms the change conflicts with its base, so it cannot merge until
    /// the branch is reconciled with it.
    Conflicting {
        /// What the host reported, in its own words — on GitHub `mergeable` and
        /// `mergeStateStatus` — which is what a refusal about it quotes.
        reported: String,
    },
    /// The host has not computed it yet, which is never a conflict.
    Unknown,
}

/// A change request the host reports merged, as
/// [`RemoteHost::merged_head`] answers it: the commit it reached its base at, and the
/// head commit the host merged it from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MergedChange {
    /// The commit the base reached — the squash or merge commit the host made.
    pub commit: Sha,
    /// The head the host reports the change request carried when it merged.
    pub head: Sha,
}

/// A change request's description as the host holds it.
///
/// What [`RemoteHost::change_description`] answers, and the other half of
/// [`ChangeDescription`](crate::ChangeDescription): a caller writes a body and
/// optionally a title, and reads back both. Both are plain strings, because both are
/// prose a host places no shape on — a title *this crate lands* is a
/// [`Subject`](crate::Subject), but a title a host already holds was composed by
/// whoever opened the change request, and is reported as it is rather than refused.
// llmlint: ignore[invalid_states_unrepresentable] the doc above: what a host answers,
// reported rather than judged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Description {
    /// The title, which under squash-merge becomes the commit subject.
    pub title: String,
    /// The body, verbatim. Empty where the change request carries none.
    pub body: String,
}

/// One of the ways a host protects a branch, each of which may name required checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProtectionSource {
    /// The repository's rulesets, which every credential that can read the
    /// repository can read.
    Rulesets,
    /// Classic branch protection, which only a credential with administration
    /// rights can read — so it is the source an audit is most often refused.
    BranchProtection,
}

impl ProtectionSource {
    /// Every source, in the order a report names them.
    pub fn every() -> impl Iterator<Item = ProtectionSource> {
        [
            ProtectionSource::Rulesets,
            ProtectionSource::BranchProtection,
        ]
        .into_iter()
    }

    /// How a report names it.
    pub fn describe(self) -> &'static str {
        match self {
            ProtectionSource::Rulesets => "the repository's rulesets",
            ProtectionSource::BranchProtection => "classic branch protection",
        }
    }
}

/// What a host requires before a merge into a branch, and how much of the host
/// that answer covers.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequiredChecks {
    /// The names, from every source that answered.
    pub checks: BTreeSet<String>,
    /// Each protection source the host holds that could not be read, with the
    /// host's reason. Empty means every source answered and `checks` is the whole
    /// list; otherwise `checks` is what the sources that did answer require, and an
    /// empty `checks` is not "nothing is required".
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub unconsulted: BTreeMap<ProtectionSource, String>,
}

impl RequiredChecks {
    /// Whether every protection source answered, so `checks` is the whole list.
    pub fn complete(&self) -> bool {
        self.unconsulted.is_empty()
    }
}

/// Where a [`RemoteHost`] for one repository comes from.
///
/// A host is addressed at a repository rather than at an installation — every
/// call `gh` makes carries a slug — so the seam a caller supplies is the factory
/// rather than one host object. This is what makes the interface reachable: a
/// publication asks the factory it was handed for the repository it is publishing
/// to, and never names an implementation.
pub trait Hosting {
    /// The host that answers for the repository named `owner/name`.
    // llmlint: ignore[invalid_states_unrepresentable] a validated slug newtype would be a
    // public item beyond the one this seam is specified as, and it would have exactly one
    // constructor — the check below. That check is where the value is decided: `GitHub::new`
    // refuses anything that does not name one repository as `owner/name`, before the slug is
    // interpolated into a single `gh --repo`. A caller cannot reach a host any other way.
    fn for_repo(&self, slug: &str) -> Result<Box<dyn RemoteHost>>;
}

/// The factory that produces [`GitHub`] hosts, which is what a real run uses.
///
/// Private: the way to hold one is [`crate::Providers::real`], because a caller
/// mixing a real GitHub into a run whose repository side is not git is asking for
/// a combination neither half was written for.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct GitHubHosting;

impl Hosting for GitHubHosting {
    fn for_repo(&self, slug: &str) -> Result<Box<dyn RemoteHost>> {
        Ok(Box::new(GitHub::new(slug)?))
    }
}

/// What to open a change request for.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChangeSpec {
    /// The branch carrying the change.
    // llmlint: ignore[invalid_states_unrepresentable] a validated branch-ref newtype is
    // exactly what the publication path carries internally, and it cannot surface here:
    // the contract fixes the matching `ChangeRequest.base` as `String` and names no ref
    // type, so spelling one on this side of the same trait would add a public item the
    // contract does not name and disagree with the type it does. Both names are handed to
    // git before they reach a host, which is where the parser that decides them lives.
    pub head: String,
    /// The branch it targets, which for a stacked change is the branch below it.
    pub base: String,
    /// The title, which under squash-merge becomes the commit subject.
    pub title: String,
    /// The body. Absent means the host's default from the repository template.
    pub body: Option<String>,
    /// Open it as a **draft**, and why it is not ready. Absent opens an ordinary
    /// change request, which is every publication that came before this field.
    ///
    /// The host is handed the whole reason and asked for one thing with it: open the
    /// change as a draft. Nothing here renders the reason into the change request —
    /// see [`DraftReason`] for the ruling that keeps it out of the body — so a host
    /// implementation that reads past this field's presence is reading further than
    /// the contract asks it to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub draft: Option<DraftReason>,
    /// Open it as a draft **while its required checks run**, with no
    /// [`DraftReason`]: what a lifecycle publication asks for when its caller asked
    /// for no draft. A host lifts or keeps it once the checks settle, by the rules
    /// the publication states; nothing here is a reason a caller gave.
    ///
    /// Beside `draft` rather than a third kind of it, because [`DraftReason`] is what
    /// a *caller* asks for and this is what the lifecycle asks for when the caller
    /// asked for none. Defaulted and omitted when false, so a spec written before it
    /// reads and writes as it did. Where both are set the reason is what the host
    /// records: either way the change opens as a draft.
    // llmlint: ignore[invalid_states_unrepresentable] one sum type over both would
    // change `draft`, which the approved contract declares verbatim as
    // `Option<DraftReason>`, and the manager's ruling for this amendment forbids widening
    // `DraftReason` itself. So the lifecycle's draft is an additive, defaulted field beside
    // it, and the one combination both allow is given a meaning above rather than refused.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub draft_awaiting_checks: bool,
}

/// An open change request on the host.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChangeRequest {
    /// The host's identifier for it.
    pub id: ChangeId,
    /// Where a human reads it.
    pub url: Url,
    /// The commit its checks are reported against.
    pub head_sha: Sha,
    /// The branch it targets.
    // llmlint: ignore[invalid_states_unrepresentable] the contract declares this field
    // verbatim as `pub base: String` and names no ref type to narrow it to; changing it
    // is changing the interface, which is reported rather than done. Every one this crate
    // constructs is read out of a host response naming a branch the host already has.
    pub base: String,
}

/// A host's identifier for a change request.
// llmlint: ignore[invalid_states_unrepresentable] the contract declares this as
// `id: ChangeId` and fixes nothing about its content — GitHub numbers its pull
// requests, and another host may not. Every one this crate constructs is read out of
// a host response that is required to carry it: `find_changes` rejects an entry with
// no number, and `open_change` rejects output that printed no URL to take one from.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ChangeId(pub String);

/// A commit hash.
// llmlint: ignore[invalid_states_unrepresentable] the contract declares this field as
// `head_sha: Sha` and fixes nothing about its content, and a hash's shape is the host's
// to state — a SHA-1 hex string today, something else on a repository that has moved.
// Every one this crate constructs is validated where it enters: `head_sha` and
// `merged_sha` below both reject a response that names no commit rather than
// constructing an empty one, so no code path here can produce a blank `Sha`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Sha(pub String);

/// One check the host reports on a change request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Check {
    /// The check's name, as branch protection lists it.
    pub name: String,
    /// Where the check is: the host's own status vocabulary, passed through.
    // llmlint: ignore[invalid_states_unrepresentable] the contract fixes this field name
    // and enumerates no value set for it, and the vocabulary differs per host — which is
    // the thing this crate exists to abstract. Inventing an enum here would add a public
    // item the contract does not name. The one word this build reads out of it —
    // `completed` — is read in `settled` below and nowhere else, so a host that spells
    // its states differently is understood by a second implementation of that predicate
    // rather than by a new variant here. Recorded as open question 1 in
    // docs/inferred-surface.md for the planner to settle across the three repositories.
    pub status: String,
    /// How it ended, once it has. Absent while it is still running.
    // llmlint: ignore[invalid_states_unrepresentable] `conclusion` is the other half of the
    // same open question as `status` above, for the same reason: the contract names the
    // field and enumerates no conclusion vocabulary, and each host spells its own. The
    // three this build treats as not blocking a merge are read in `green` below, which is
    // the one place a second host's vocabulary would be taught.
    pub conclusion: Option<String>,
    /// Whether it blocks the merge.
    pub required: bool,
    /// The commit the host attached this check to, or `None` where the host did not
    /// say which one it is about.
    ///
    /// What makes a check's verdict addressable to a commit rather than to a change
    /// request. A change request is a moving target — every push gives it a new head,
    /// and the host attaches the new head's checks seconds to minutes later — so a
    /// caller reading "the checks on this change request" moments after a push reads
    /// the *previous* head's answer and cannot tell. `None` is the host declining to
    /// say and never a commit inferred from the change request: a caller that must
    /// distinguish them has to be able to, and one that cannot is told nothing rather
    /// than told wrongly.
    ///
    /// Defaulted, so a check some earlier build serialized still reads — as one whose
    /// commit that build never recorded, which is what it is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head: Option<Sha>,
    /// Where this check is on the host, so whoever is handed its refusal can go and
    /// look at it. `None` where the host reported no address for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<Url>,
    /// When the host says this run of the check started, spelled as the host spelled
    /// it, or `None` where it did not say.
    ///
    /// The run's own identity: a check re-run under the same name — the run a
    /// workflow starts when a draft is lifted — is a new run with a new start, even
    /// where it concludes exactly as the one before it did. That is what a
    /// publication tells a run the host attached after an early lift from the
    /// draft's by, so it is compared for equality and never parsed or ordered: two
    /// clocks never meet in it.
    ///
    /// Defaulted and omitted when empty, as `head` and `url` are, so a check an
    /// earlier build serialized still reads and one without a start serializes as
    /// it always did.
    // llmlint: ignore[invalid_states_unrepresentable] the host's own timestamp, carried
    // as an opaque token: this crate only ever asks whether two runs report the same
    // one, so parsing it would add a failure mode and decide nothing. `reported_time`
    // is the one place it enters, and it drops GitHub's zero time for a run that has
    // not started rather than letting every queued run share one identity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at: Option<String>,
    /// When the host says this run of the check completed, spelled as the host
    /// spelled it, or `None` where it did not say — which is every run still going.
    ///
    /// Carried for the record of a gate run and nothing else: a `required-checks`
    /// run lists each required check with the times the host reported, so a reader
    /// can tell a long check from a long wait for one. Never compared or ordered
    /// here. Defaulted and omitted when empty, as `started_at` is, so a check an
    /// earlier build serialized still reads.
    // llmlint: ignore[invalid_states_unrepresentable] the host's own timestamp, carried
    // through to the record verbatim for the reason `started_at` is: this crate decides
    // nothing by it, and parsing it would add a failure mode to a field nothing reads.
    // `reported_time` is where it enters, and drops GitHub's zero time as it does there.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<String>,
}

impl Check {
    /// Whether this check has reached a terminal state.
    pub fn settled(&self) -> bool {
        self.status.eq_ignore_ascii_case("completed")
    }

    /// Which of the five states this check is in — the one classifier every reading
    /// and every rendering of a check follows.
    ///
    /// A skipped check is its own state and never a passed one: a job a workflow
    /// gated on the change not being a draft reports `skipped` without having run,
    /// so reading it as green would call a change verified that nothing verified.
    /// What the publication watch does with a skipped *required* check is its own
    /// rule, stated where the watch is.
    pub fn state(&self) -> CheckState {
        if !self.settled() {
            return CheckState::Pending;
        }
        match self
            .conclusion
            .as_deref()
            .map(str::to_ascii_lowercase)
            .as_deref()
        {
            Some("success" | "neutral") => CheckState::Passed,
            Some("skipped") => CheckState::Skipped,
            Some("cancelled" | "stale") => CheckState::NoVerdict,
            _ => CheckState::Failed,
        }
    }

    /// Whether a settled check passed. A skipped one did not: see [`Check::state`].
    pub fn green(&self) -> bool {
        self.state() == CheckState::Passed
    }

    /// Whether a settled check ended in a way that blocks a merge.
    pub fn red(&self) -> bool {
        self.state() == CheckState::Failed
    }
}

/// Which of five states one check is in, as [`Check::state`] classifies it.
///
/// Exported so a consumer holds its own copy of "what reads as green" to this
/// declaration rather than to a list it keeps beside it. Serialized kebab-case, which
/// is how the `change-check` event's `state`, the `checks-settled` event and `onevcs
/// status` spell it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CheckState {
    /// Concluded `success` or `neutral`.
    Passed,
    /// Concluded in a way that blocks a merge: every settled conclusion not named by
    /// another state.
    Failed,
    /// Concluded `skipped`: it did not run, and it is never read as passed.
    Skipped,
    /// Not settled yet.
    Pending,
    /// Concluded `cancelled` or `stale`: the host ended the run with no verdict.
    NoVerdict,
}

/// One place a host's answer about a change request's checks was read from.
///
/// A credential decides which of these can be reached, so which were consulted is
/// part of the answer rather than a property of the build: a fine-grained personal
/// access token cannot read check runs *at all* — GitHub offers no `Checks`
/// permission for one, and the permission it briefly had was withdrawn — so for
/// such a token the rollup is unreadable and Actions is everything it can see.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CheckSource {
    /// The host's own rollup of every check on the change request: workflow jobs,
    /// check runs a third-party integration posted, and commit statuses alike,
    /// each carrying whether it blocks the merge. Complete, and the one source a
    /// fine-grained token cannot read.
    StatusChecks,
    /// GitHub Actions' own view of the head commit: the jobs of the workflow runs
    /// on it and nothing else. A check that ran no workflow — anything a
    /// third-party integration posted as a check run or a commit status — is not
    /// in it and cannot be seen from it.
    Actions,
    /// The repository's rulesets, for which checks block a merge into the base.
    /// Narrower than the rollup's own answer: it reports rulesets and not classic
    /// branch protection, so a repository protected the classic way reports
    /// nothing blocking here — which the publication path fails closed on, waiting
    /// for a required check that never arrives rather than merging without one.
    BranchRules,
}

/// What a host reports about a change request's checks, and where it looked.
///
/// The sources travel with the checks because a caller deciding whether a change
/// may merge has to be able to tell "these are all the checks" from "these are the
/// workflow checks, and anything a third-party integration posted is invisible to
/// this credential". Reporting the second as the first is how a merge gets waved
/// through by a check nobody could see.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChangeChecks {
    /// The checks themselves.
    pub checks: Vec<Check>,
    /// Every source consulted to produce them. Never empty: a host that could read
    /// none of its sources is a refusal rather than an answer.
    // llmlint: ignore[invalid_states_unrepresentable] the approved contract fixes
    // this as a public BTreeSet; implementations refuse an empty answer.
    pub sources: BTreeSet<CheckSource>,
}

impl ChangeChecks {
    /// Whether this answer covers every check the host reports.
    ///
    /// False means the checks above are GitHub Actions' and only those.
    pub fn complete(&self) -> bool {
        self.sources.contains(&CheckSource::StatusChecks)
    }
}

/// What merging a change request did.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum MergeOutcome {
    /// It merged, at this commit.
    Merged(Sha),
    /// The host queued it and will merge it once its checks pass.
    Queued,
    /// It was left open for review, which the policy asked for.
    Open,
}

/// The GitHub implementation of [`RemoteHost`], driven through `gh`.
///
/// Every method is one `gh` invocation, and the program that answers as `gh` is the
/// seam a journey substitutes: GitHub's decisioning is what a test replaces, never
/// the git underneath it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitHub {
    /// The `owner/name` slug every call is addressed to. Private, so the only way
    /// to hold one is to have had it accepted by [`GitHub::new`] — every `gh`
    /// invocation below trusts it as the repository it addresses.
    repo: String,
}

impl GitHub {
    /// Address this host at one repository, named `owner/name`.
    ///
    /// Checked here rather than at each call: the slug is interpolated into every
    /// `gh --repo` invocation, and a value that is not one repository is a value
    /// that addresses something nobody asked for.
    pub fn new(repo: impl Into<String>) -> Result<Self> {
        let repo = repo.into();
        let mut parts = repo.split('/');
        let named = matches!(
            (parts.next(), parts.next(), parts.next()),
            (Some(owner), Some(name), None)
                if !owner.is_empty()
                    && !name.is_empty()
                    && !repo.starts_with('-')
                    && !repo.contains(char::is_whitespace)
        );
        if !named {
            return Err(invalid(format!(
                "{repo:?} does not name one repository as owner/name"
            )));
        }
        Ok(Self { repo })
    }

    /// The names of the checks the host says block the merge.
    ///
    /// A second call, and it has to be one: `gh pr view`'s `statusCheckRollup`
    /// carries a check's name, status, and conclusion and *nothing* about whether it
    /// blocks anything. This build asked it for `isRequired` anyway and read the
    /// field's absence as a host answering partially, so every `change_checks`
    /// against real GitHub failed — a field `gh pr view` has never returned, checked
    /// only ever against a stand-in that returned it. `gh pr checks --required` is
    /// where `gh` reports it.
    fn required_checks(&self, cr: &ChangeRequest) -> Result<BTreeSet<String>> {
        addressable(&cr.id.0, "change request id")?;
        let answer = gh::attempt(&[
            "pr",
            "checks",
            &cr.id.0,
            "--repo",
            &self.repo,
            "--required",
            "--json",
            "name",
        ])?;
        if !usable(&answer) {
            // A repository that declares no required check at all is answering, not
            // failing: refusing here would make every unprotected repository
            // unreadable, and "nothing blocks the merge" is what the publication
            // path already knows how to act on.
            if no_required_checks(&answer) {
                return Ok(BTreeSet::new());
            }
            if no_checks_yet(&answer) {
                return Err(unregistered(&cr.url, answer.stderr.trim()));
            }
            return Err(unsaid(&cr.url, &answer.detail()));
        }
        let value = gh::json(&answer.stdout)?;
        let entries = value
            .as_array()
            .ok_or_else(|| unsaid(&cr.url, &value.to_string()))?;
        let mut names = BTreeSet::new();
        for entry in entries {
            let name = entry
                .get("name")
                .and_then(|value| value.as_str())
                .filter(|value| !value.is_empty())
                .ok_or_else(|| unsaid(&cr.url, &entry.to_string()))?;
            names.insert(name.to_owned());
        }
        Ok(names)
    }

    /// The log of the job one check ran in.
    ///
    /// Two calls, because `gh` addresses a job's log by the job's *id* and a check's
    /// name is not one. This build passed the name to `gh run view --job`, which has
    /// never accepted anything but a number — so the artifact every settled check
    /// carried held a refusal to produce a log rather than the log, and no offline
    /// journey could tell, because the program standing in for `gh` answered to the
    /// name. The id is the last segment of the details URL `gh pr checks` reports.
    fn job_log(&self, cr: &ChangeRequest, name: &str) -> Result<String> {
        addressable(&cr.id.0, "change request id")?;
        let answer = gh::attempt(&[
            "pr",
            "checks",
            &cr.id.0,
            "--repo",
            &self.repo,
            "--json",
            "name,link",
        ])?;
        if !usable(&answer) {
            return Err(invalid(format!(
                "gh pr checks would not say where check {name:?} on {} ran: {}",
                cr.url,
                answer.detail()
            )));
        }
        let value = gh::json(&answer.stdout)?;
        // Rejected here rather than searched through: a host that answered with
        // something other than a list of checks has not said this check has no job,
        // and reporting it as though it had would put the wrong reason in the
        // artifact an operator reads to find out why there is no log.
        let entries = value.as_array().ok_or_else(|| {
            invalid(format!(
                "gh pr checks returned a non-list of checks on {}, so where check {name:?} ran \
                 cannot be read from it: {value}",
                cr.url
            ))
        })?;
        let link = entries
            .iter()
            .find(|entry| entry.get("name").and_then(|value| value.as_str()) == Some(name))
            .and_then(|entry| entry.get("link"))
            .and_then(|value| value.as_str())
            .ok_or_else(|| {
                invalid(format!(
                    "the host reports no job for check {name:?} on {}",
                    cr.url
                ))
            })?;
        let job = link
            .rsplit_once("/job/")
            .map(|(_, id)| id)
            .filter(|id| !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()))
            .ok_or_else(|| {
                invalid(format!(
                    "the host says check {name:?} ran at {link:?}, which names no job this build \
                     can ask for a log"
                ))
            })?;
        gh::invoke_content(&["run", "view", "--repo", &self.repo, "--log", "--job", job])
    }

    /// One check's log, from whichever source this credential can read.
    ///
    /// The same order [`RemoteHost::change_checks`] consults them in, for the same
    /// reason: `gh pr checks` reports where *every* check ran, including one no
    /// workflow produced, and the Actions API answers for the ones it owns when the
    /// credential may not read the rollup at all.
    fn log_of(&self, cr: &ChangeRequest, name: &str) -> Result<String> {
        match consult()? {
            Consult::StatusChecks => self.job_log(cr, name),
            Consult::Actions => self.actions_log(cr, name),
            // As above, and for the same reason: where a check ran is a question
            // `gh pr checks` can answer about every check, and only a credential
            // that may not ask it at all has cause to ask a narrower source.
            Consult::Either => self.job_log(cr, name).or_else(|reported| {
                if !check_rollup_refused_for_pat(&reported) {
                    return Err(reported);
                }
                self.actions_log(cr, name).map_err(|actions| {
                    invalid(format!(
                        "neither of GitHub's check sources would produce the log of check \
                         {name:?} on {}: gh pr checks answered {reported}, and the Actions API \
                         answered {actions}",
                        cr.url
                    ))
                })
            }),
        }
    }

    /// Every check the host's own rollup reports on a change request.
    ///
    /// Complete — a workflow job, a check run some integration posted, and a commit
    /// status all appear here — and readable only by a credential the repository
    /// allows to read its check runs. A fine-grained personal access token is not
    /// one and cannot become one, which is what [`GitHub::actions_checks`] answers
    /// instead.
    fn rollup_checks(&self, cr: &ChangeRequest) -> Result<Vec<Check>> {
        // `headRefOid` in the same call, because the rollup GitHub renders is the
        // rollup of the change request's *last commit* as that one response saw it —
        // and which commit that was is the whole of what makes the answer
        // addressable. Asked together rather than in a second call for the same
        // reason a second call could not answer it: the head moves, so a commit read
        // afterwards is not necessarily the one those checks were about. It costs
        // this call nothing, because the field needs no more than the read access
        // that found the change request while `statusCheckRollup` needs far more —
        // a credential refused for one of them was already refused for the call.
        let value = self.view(&cr.id.0, "headRefOid,statusCheckRollup")?;
        let head = reported_sha(&value, "headRefOid")?;
        let reported = value.get("statusCheckRollup").ok_or_else(|| {
            invalid(format!(
                "gh pr view reported no checks at all on {}",
                cr.url
            ))
        })?;
        if reported.is_null() {
            return Ok(Vec::new());
        }
        let rollup = reported
            .as_array()
            .ok_or_else(|| invalid(format!("gh pr view returned a non-list rollup: {reported}")))?;
        if rollup.is_empty() {
            return Ok(Vec::new());
        }
        let required = self.required_checks(cr)?;
        rollup
            .iter()
            .map(|entry| check(entry, cr, &required, head.as_ref()))
            .collect()
    }

    /// The checks GitHub Actions reports for the change request's head commit.
    ///
    /// One workflow job is one check, which is the same unit the rollup reports
    /// them in — GitHub posts a check run per job — so what a caller waits for is
    /// unchanged. What it cannot see is anything that ran no workflow, which is why
    /// the answer says which sources it came from rather than passing itself off as
    /// the whole picture.
    fn actions_checks(&self, cr: &ChangeRequest) -> Result<ChangeChecks> {
        let jobs = self.actions_jobs(cr)?;
        if jobs.is_empty() {
            // Nothing has run yet, which is the first seconds of every change
            // request. There is no check to ask the rulesets about, so they are not
            // asked and the answer does not claim they were.
            return Ok(ChangeChecks {
                checks: Vec::new(),
                sources: [CheckSource::Actions].into_iter().collect(),
            });
        }
        let required = self.ruled_checks(cr)?;
        Ok(ChangeChecks {
            checks: jobs
                .into_iter()
                .map(|job| Check {
                    required: required.contains(&job.name),
                    name: job.name,
                    status: job.status,
                    conclusion: job.conclusion,
                    head: job.head,
                    url: job.url,
                    started_at: job.started_at,
                    completed_at: job.completed_at,
                })
                .collect(),
            sources: [CheckSource::Actions, CheckSource::BranchRules]
                .into_iter()
                .collect(),
        })
    }

    /// Every job of every workflow run on the change request's head commit.
    ///
    /// Two calls per run, because the Actions API reports a *run*'s status at the
    /// run and a job's at the job, and a run that is still going says nothing about
    /// which of its jobs have finished — and one before them, for which commit that
    /// head is *now*. Asked rather than taken off the [`ChangeRequest`] the caller
    /// holds, because that one was read when the change request was found: a
    /// publication finds it moments after pushing, when the host may not have
    /// processed the push, and a build that kept asking about the head it first saw
    /// would go on asking about a commit this run replaced for as long as it
    /// watched. The rollup source re-reads the same field on every call for the same
    /// reason; this is that, on the source a fine-grained token is left with.
    fn actions_jobs(&self, cr: &ChangeRequest) -> Result<Vec<Job>> {
        let current = head_sha(&self.view(&cr.id.0, "headRefOid")?)?;
        let sha = commit(&current)?;
        let runs = self.api(&format!(
            "repos/{}/actions/runs?head_sha={sha}&per_page={PAGE}",
            self.repo
        ))?;
        let mut jobs = Vec::new();
        for run in listed(&runs, "workflow_runs", &format!("the commit {sha}"))? {
            let id = run
                .get("id")
                .and_then(serde_json::Value::as_u64)
                .ok_or_else(|| {
                    invalid(format!(
                        "the Actions API reported a workflow run on {} with no id: {run}",
                        cr.url
                    ))
                })?;
            // The commit off the run's own record rather than the one this query
            // filtered on: what the host says it ran against is the host's answer,
            // and a build that stamped the question onto the answer could not tell a
            // host that disagreed.
            let head = reported_sha(run, "head_sha")?;
            let listing = self.api(&format!(
                "repos/{}/actions/runs/{id}/jobs?per_page={PAGE}",
                self.repo
            ))?;
            for entry in listed(&listing, "jobs", &format!("workflow run {id}"))? {
                jobs.push(job(entry, cr, head.as_ref())?);
            }
        }
        Ok(jobs)
    }

    /// The names of the checks the repository's rulesets say block a merge into the
    /// change request's base.
    ///
    /// The second question `gh pr checks --required` answers and a credential that
    /// cannot read check runs cannot ask, because that command reads the same
    /// rollup. This is what such a credential *can* read — and it is narrower, in a
    /// direction that is safe rather than quiet: it reports rulesets and not classic
    /// branch protection, so a repository protected the classic way answers "nothing
    /// blocks" and the publication path then waits for a required check that never
    /// arrives and stops. Under-reporting what blocks holds a merge; over-reporting
    /// what has passed lets one through, and only one of those is recoverable.
    fn ruled_checks(&self, cr: &ChangeRequest) -> Result<BTreeSet<String>> {
        self.required_on(&cr.base, cr.url.as_ref())
    }

    /// The names of the checks the repository's rulesets require before a merge into
    /// `base` — the same read as [`GitHub::ruled_checks`], addressed to a branch
    /// rather than to a change request targeting one, and what
    /// [`RemoteHost::required_checks_on`] answers with. It is the rulesets' answer
    /// and carries the rulesets' limit: a repository protected the classic way names
    /// nothing here.
    ///
    fn required_on(&self, base: &str, about: &str) -> Result<BTreeSet<String>> {
        addressable_branch(base, "the base branch")?;
        let value = self.api(&format!(
            "repos/{}/rules/branches/{}",
            self.repo,
            path_segment(base)
        ))?;
        let rules = value.as_array().ok_or_else(|| {
            invalid(format!(
                "the rules on {about}'s base branch {base:?} came back as something that is \
                 not a list of them, so which of its checks block the merge cannot be read \
                 from it: {value}"
            ))
        })?;
        let mut names = BTreeSet::new();
        for rule in rules {
            if rule.get("type").and_then(|value| value.as_str()) != Some("required_status_checks") {
                continue;
            }
            // A rule that says it requires status checks and then will not say
            // which is the one shape that must not be read as "none": that is the
            // difference between a merge that was gated and one that only looked
            // like it.
            let required = rule
                .get("parameters")
                .and_then(|parameters| parameters.get("required_status_checks"))
                .and_then(|value| value.as_array())
                .ok_or_else(|| unsaid_about(about, &rule.to_string()))?;
            for entry in required {
                let name = entry
                    .get("context")
                    .and_then(|value| value.as_str())
                    .filter(|value| !value.is_empty())
                    .ok_or_else(|| unsaid_about(about, &entry.to_string()))?;
                names.insert(name.to_owned());
            }
        }
        Ok(names)
    }

    /// The contexts classic branch protection requires on `base`, or why the host
    /// would not say.
    ///
    /// Three answers, told apart by what `gh` wrote. A protected branch answers with
    /// its contexts; a branch with no classic protection answers `Branch not
    /// protected`, a 404 that *is* an answer — the source was consulted and names
    /// nothing; and anything else is the source not consulted, which the inner `Err`
    /// carries so the caller records it beside what the rulesets did say rather than
    /// losing that too. The outer `Err` is `gh` itself failing to run.
    fn classic_protection(
        &self,
        base: &str,
    ) -> Result<std::result::Result<BTreeSet<String>, String>> {
        addressable_branch(base, "the base branch")?;
        let path = format!(
            "repos/{}/branches/{}/protection/required_status_checks",
            self.repo,
            path_segment(base)
        );
        let answer = gh::attempt(&["api", &path])?;
        if answer.code != Some(0) {
            if answer.stderr.contains(NOT_PROTECTED) {
                return Ok(Ok(BTreeSet::new()));
            }
            return Ok(Err(answer.detail()));
        }
        let value = gh::json(&answer.stdout)?;
        let contexts = value
            .get("contexts")
            .and_then(|value| value.as_array())
            .ok_or_else(|| {
                invalid(format!(
                    "the classic branch protection on {}'s {base:?} came back without its \
                     contexts, so which checks it requires cannot be read from it: {value}",
                    self.repo
                ))
            })?;
        let mut names = BTreeSet::new();
        for context in contexts {
            let name = context
                .as_str()
                .filter(|value| !value.is_empty())
                .ok_or_else(|| unsaid_about(&self.repo, &context.to_string()))?;
            names.insert(name.to_owned());
        }
        Ok(Ok(names))
    }

    /// Whether the repository's rulesets require a branch to be up to date with `base`
    /// before a merge into it: any `required_status_checks` rule on it whose
    /// `strict_required_status_checks_policy` is set.
    ///
    /// A rule that does not say is refused rather than read as `false`, for the reason
    /// a rule that will not name its checks is: it is the difference between a merge
    /// the host would take and one it would refuse.
    fn ruled_up_to_date(&self, base: &str) -> Result<bool> {
        addressable_branch(base, "the base branch")?;
        let value = self.api(&format!(
            "repos/{}/rules/branches/{}",
            self.repo,
            path_segment(base)
        ))?;
        let rules = value.as_array().ok_or_else(|| {
            invalid(format!(
                "the rules on {}'s base branch {base:?} came back as something that is not a \
                 list of them, so whether it requires an up-to-date branch cannot be read from \
                 it: {value}",
                self.repo
            ))
        })?;
        let mut strict = false;
        for rule in rules {
            if rule.get("type").and_then(|value| value.as_str()) != Some("required_status_checks") {
                continue;
            }
            strict |= rule
                .get("parameters")
                .and_then(|parameters| parameters.get("strict_required_status_checks_policy"))
                .and_then(serde_json::Value::as_bool)
                .ok_or_else(|| {
                    invalid(format!(
                        "a required-status-checks rule on {}'s base branch {base:?} does not say \
                         whether it requires an up-to-date branch: {rule}",
                        self.repo
                    ))
                })?;
        }
        Ok(strict)
    }

    /// Whether classic branch protection on `base` requires an up-to-date branch, or
    /// why the host would not say — the same three answers
    /// [`classic_protection`](GitHub::classic_protection) tells apart.
    fn classic_up_to_date(&self, base: &str) -> Result<std::result::Result<bool, String>> {
        addressable_branch(base, "the base branch")?;
        let path = format!(
            "repos/{}/branches/{}/protection/required_status_checks",
            self.repo,
            path_segment(base)
        );
        let answer = gh::attempt(&["api", &path])?;
        if answer.code != Some(0) {
            if answer.stderr.contains(NOT_PROTECTED) {
                return Ok(Ok(false));
            }
            return Ok(Err(answer.detail()));
        }
        let value = gh::json(&answer.stdout)?;
        value
            .get("strict")
            .and_then(serde_json::Value::as_bool)
            .map(Ok)
            .ok_or_else(|| {
                invalid(format!(
                    "the classic branch protection on {}'s {base:?} came back without saying \
                     whether it requires an up-to-date branch: {value}",
                    self.repo
                ))
            })
    }

    /// The log of the Actions job one check ran in, addressed by the job's id.
    ///
    /// The id comes from the same listing the checks did, so the name matched here
    /// is the name reported there — the two cannot drift apart the way a check's
    /// name and a details URL parsed out of a second command can.
    fn actions_log(&self, cr: &ChangeRequest, name: &str) -> Result<String> {
        let job = self
            .actions_jobs(cr)?
            .into_iter()
            .find(|job| job.name == name)
            .ok_or_else(|| {
                invalid(format!(
                    "GitHub Actions reports no job named {name:?} on the head commit of {}",
                    cr.url
                ))
            })?;
        gh::invoke_content(&[
            "api",
            &format!("repos/{}/actions/jobs/{}/logs", self.repo, job.id),
        ])
    }

    fn api(&self, path: &str) -> Result<serde_json::Value> {
        gh::json(&gh::invoke(&["api", path])?)
    }

    /// One change request as `gh` describes it, in the fields the caller reads and
    /// no others.
    ///
    /// The field list is the caller's, not a constant, because `gh pr view` fails
    /// *whole* when GitHub refuses one field of the several it was asked for — and
    /// the fields differ in what a credential has to be allowed to see.
    /// `statusCheckRollup` resolves the change request's check runs, which a
    /// fine-grained token may not read without the repository's Checks permission,
    /// while `state`, `headRefOid`, and `mergeCommit` need no more than the read
    /// access that found the change request at all. This build asked for all of them
    /// at every call, so a token that could open and merge a change request was
    /// refused at both over a field neither reads — and only from the moment a check
    /// first appeared on it, so the same credential merged a young change request and
    /// failed on an older one. Ask for what you read.
    fn view(&self, id: &str, fields: &str) -> Result<serde_json::Value> {
        addressable(id, "change request id")?;
        let raw = gh::invoke(&["pr", "view", id, "--repo", &self.repo, "--json", fields])?;
        gh::json(&raw)
    }
}

/// One value bound for `gh`'s argument vector, checked before it gets there.
///
/// Every string in these methods arrives from outside — off a caller embedding this
/// crate, or out of the host's own answer — and each becomes a positional or an
/// option's value. `gh` reads a leading `-` as an option of its own and an empty
/// string as a present-but-blank value, so a name shaped like either is refused
/// here rather than silently addressing something other than what it names.
///
/// Those two and no others: the vector is handed to `gh` as a vector, so no shell
/// splits an argument this build wrote as one. Whitespace was refused here too, and
/// [`matchable`] records what that cost — a value with a space in it reaches `gh`
/// exactly as it was written, so it is nothing this boundary has to guard against.
fn addressable(value: &str, what: &str) -> Result<()> {
    if value.is_empty() || value.starts_with('-') {
        return Err(invalid(format!(
            "{what} {value:?} cannot address anything on the host: it must be non-empty and must \
             not begin with '-'"
        )));
    }
    Ok(())
}

/// A check's name, checked before it is matched against the ones the host reports.
///
/// Deliberately not [`addressable`], because a check's name never becomes an
/// argument to `gh`: [`GitHub::job_log`] matches it against the `name` field of the
/// JSON `gh pr checks` returns, and [`GitHub::actions_log`] against the job names
/// the Actions API lists — the job's *id* is what either one then asks for a log by.
/// So `gh`'s argument grammar has no say over this value, and the shapes that
/// grammar refuses are ordinary job names here. Every GitHub matrix job is named
/// with whitespace — `check (macos-latest)`, `test-os (windows-latest)` — and
/// refusing it left every matrix check on every change request this crate published
/// recorded with no log at all.
///
/// What is refused is a name that can match nothing the host reports: the host names
/// every check it answers about, so an empty name is a value a caller made up rather
/// than a check anything has.
fn matchable(name: &str, cr: &ChangeRequest) -> Result<()> {
    if name.is_empty() {
        return Err(invalid(format!(
            "onevcs will not ask for the log of a check with no name on {}: every check the host \
             reports is named, so an empty name matches none of them. This build refused the \
             request; the host was not asked.",
            cr.url
        )));
    }
    Ok(())
}

/// One value bound for a URL path segment, percent-encoded.
///
/// A branch name is the only one of these, and git allows characters in one that a
/// path does not — a `/` above all, which every stacked branch carries and which
/// would otherwise address a resource nobody asked for. Encoded rather than
/// refused: `feature/thing` is a branch a repository really has.
fn path_segment(value: &str) -> String {
    let mut encoded = String::with_capacity(value.len());
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
            encoded.push(char::from(byte));
        } else {
            encoded.push_str(&format!("%{byte:02X}"));
        }
    }
    encoded
}

/// A commit hash bound for a query string, checked before it gets there.
///
/// It arrives off a host response and goes on to be one parameter of several, so a
/// value carrying anything but hex digits could address a query nobody wrote.
fn commit(sha: &Sha) -> Result<&str> {
    if !is_commit_hash(&sha.0) {
        return Err(invalid(format!(
            "{:?} is not a commit hash, so the checks reported against it cannot be asked for",
            sha.0
        )));
    }
    Ok(&sha.0)
}

/// Whether text the host handed over is the shape of a commit hash.
///
/// The one shape rule, so the two boundaries that read a commit off this host agree
/// about what one is: the commit an Actions query is built from ([`commit`]) and the
/// commit a host says it attached a check to ([`reported_sha`]). Shared as the rule
/// rather than as the refusal because each of those refusals costs something
/// different and says so.
fn is_commit_hash(sha: &str) -> bool {
    !sha.is_empty() && sha.chars().all(|c| c.is_ascii_hexdigit())
}

/// One workflow job, as the Actions API reports it.
struct Job {
    /// What `gh api .../actions/jobs/<id>/logs` addresses its log by.
    id: u64,
    /// The job's name, which is the name GitHub posts its check run under.
    name: String,
    /// Where it is, in the host's own vocabulary.
    status: String,
    /// How it ended, once it has.
    conclusion: Option<String>,
    /// The commit its workflow run was reported against, off that run's own record.
    head: Option<Sha>,
    /// Where a human reads this job on the host.
    url: Option<Url>,
    /// When the host says this job started.
    started_at: Option<String>,
    /// When the host says this job completed.
    completed_at: Option<String>,
}

/// One job of an Actions listing, required to say what it is.
///
/// Defaulting a missing field is what would let a job that is still running be read
/// as a green check, which is the shape that must never be inferred — the same rule
/// [`check`] below is held to, for the same reason.
fn job(entry: &serde_json::Value, cr: &ChangeRequest, head: Option<&Sha>) -> Result<Job> {
    let field = |name: &str| -> Result<&str> {
        entry
            .get(name)
            .and_then(|value| value.as_str())
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                invalid(format!(
                    "the Actions API returned a job on {} with no {name}: {entry}",
                    cr.url
                ))
            })
    };
    Ok(Job {
        id: entry
            .get("id")
            .and_then(serde_json::Value::as_u64)
            .ok_or_else(|| {
                invalid(format!(
                    "the Actions API returned a job on {} with no id, so its log cannot be asked \
                     for: {entry}",
                    cr.url
                ))
            })?,
        name: field("name")?.to_owned(),
        status: field("status")?.to_ascii_lowercase(),
        // Genuinely absent while a job is still running.
        conclusion: entry
            .get("conclusion")
            .and_then(|value| value.as_str())
            .filter(|value| !value.is_empty())
            .map(str::to_ascii_lowercase),
        head: head.cloned(),
        url: reported_url(entry, "html_url"),
        started_at: reported_time(entry, "started_at"),
        completed_at: reported_time(entry, "completed_at"),
    })
}

/// The commit a host response names, off whichever field that response spells it
/// in, or `None` where it named none.
///
/// Lenient about *absence* where [`head_sha`] refuses, and the difference is what
/// each answer is for: a change request with no head is one this build cannot go on
/// to ask the Actions API about at all, while a check whose source would not say
/// which commit it is about is still a check, and reading it is still the answer.
/// Inventing one is the thing that must not happen — which is why an absent field
/// reads `None` rather than falling back to the head the caller already holds.
///
/// Strict about *shape* exactly where it is lenient about absence, and for the same
/// reason. This is host-supplied text arriving at a trust boundary, and it is held
/// to [`is_commit_hash`] like every other commit read off this host. Passed through
/// unchecked it would be worse than a refusal rather than more forgiving than one:
/// what a publication does with this value is compare it to the commit it pushed,
/// so anything that is not a commit hash matches nothing and reads as "the host has
/// said nothing about your commit yet" — silence — for as long as the watch runs,
/// and then times out naming a commit the host never had trouble with. A malformed
/// answer must not be able to wear the one shape this path exists to keep distinct
/// from an answer.
fn reported_sha(value: &serde_json::Value, field: &str) -> Result<Option<Sha>> {
    let Some(reported) = value
        .get(field)
        .and_then(|value| value.as_str())
        .filter(|value| !value.is_empty())
    else {
        return Ok(None);
    };
    if !is_commit_hash(reported) {
        return Err(invalid(format!(
            "gh reported {reported:?} as the {field} of a check, and that is not a commit hash, \
             so which commit the check is attached to cannot be decided"
        )));
    }
    Ok(Some(Sha(reported.to_owned())))
}

/// Where the host says something is, off whichever field that response spells it
/// in, or `None` where it named nowhere this build can point a person at.
///
/// A URL that will not parse is `None` rather than a refusal: this is the address a
/// refusal hands over so somebody can go and look, and failing a publication over a
/// link would put the check's verdict behind a formatting complaint.
pub(crate) fn reported_url(entry: &serde_json::Value, field: &str) -> Option<Url> {
    entry
        .get(field)
        .and_then(|value| value.as_str())
        .filter(|value| !value.is_empty())
        .and_then(|value| Url::parse(value).ok())
}

/// The entries of one Actions listing, refused unless the page carried them all.
///
/// These endpoints page, and a page that held entries back is a partial answer
/// about what ran — read as the whole of it, a check nobody saw is a check nobody
/// waited for. `total_count` is how the answer says how many there are, so the two
/// are compared rather than the list being trusted to be complete.
fn listed<'a>(
    value: &'a serde_json::Value,
    field: &str,
    what: &str,
) -> Result<&'a Vec<serde_json::Value>> {
    let entries = value
        .get(field)
        .and_then(|value| value.as_array())
        .ok_or_else(|| {
            invalid(format!(
                "the Actions API answered about {what} with something that lists no {field}: \
                 {value}"
            ))
        })?;
    let total = value
        .get("total_count")
        .and_then(serde_json::Value::as_u64)
        .ok_or_else(|| {
            invalid(format!(
                "the Actions API did not say how many {field} there are on {what}: {value}"
            ))
        })?;
    if total > entries.len() as u64 {
        return Err(invalid(format!(
            "the Actions API reports {total} {field} on {what} and returned {}, so this build has \
             not been shown all of them",
            entries.len()
        )));
    }
    Ok(entries)
}

/// Whether a workflow run or a check suite GitHub reported has completed: its
/// `status` is `completed`. Anything else — `queued`, `in_progress`, `waiting`,
/// `requested`, `pending`, or no status at all — is work still going.
fn is_completed(record: &serde_json::Value) -> bool {
    record
        .get("status")
        .and_then(serde_json::Value::as_str)
        .is_some_and(|status| status.eq_ignore_ascii_case("completed"))
}

/// What GitHub calls one workflow run or check suite, off the field `path` names, or
/// `what` with its id where it names nothing — the name is for a reader, and a record
/// without one is still work in progress.
fn named(record: &serde_json::Value, path: &[&str], what: &str) -> String {
    path.iter()
        .try_fold(record, |value, field| value.get(field))
        .and_then(serde_json::Value::as_str)
        .filter(|name| !name.is_empty())
        .map_or_else(
            || {
                let id = record
                    .get("id")
                    .map_or_else(String::new, |id| format!(" {id}"));
                format!("{what}{id}")
            },
            str::to_owned,
        )
}

/// Whether a REST call failed because GitHub will not let this credential make it —
/// the 403 it answers a fine-grained token the endpoint's permission was not granted
/// to — rather than because the call went wrong.
fn refused_to_this_credential(error: &Error) -> bool {
    let Error::Invalid { reason } = error else {
        return false;
    };
    reason.contains("(HTTP 403)") || reason.contains("Resource not accessible")
}

/// The refusal for a credential that can read none of the host's check sources.
///
/// Both refusals, verbatim, and the permission that answers them — because the
/// thing an operator cannot tell from GitHub's own words is that one of these is
/// not a scope to widen: a fine-grained personal access token has no `Checks`
/// permission to grant, so the rollup is out of reach for that credential class
/// however it is scoped, and `Actions: Read` is what makes the other source work.
fn unreadable(repo: &str, cr: &ChangeRequest, rollup: &Error, actions: &Error) -> Error {
    invalid(format!(
        "neither of GitHub's check sources could be read for {}, so what its checks say is \
         unknown rather than empty. Its check rollup answered: {rollup}. Its Actions API \
         answered: {actions}. Grant this credential `Actions: Read` on {repo} to read the \
         repository's workflow checks — a fine-grained personal access token cannot read the \
         rollup at all, whatever it is scoped to, because GitHub offers no Checks permission for \
         one.",
        cr.url
    ))
}

/// A branch name a caller supplied, checked by the parser that decides branch names.
fn addressable_branch(value: &str, what: &str) -> Result<()> {
    if !git::is_valid_branch_name(value) {
        return Err(invalid(format!(
            "{what} {value:?} is a name git would not accept"
        )));
    }
    Ok(())
}

impl RemoteHost for GitHub {
    fn authenticated_user(&self) -> Result<String> {
        let login = gh::invoke(&["api", "user", "--jq", ".login"])?
            .trim()
            .to_owned();
        if login.is_empty() {
            return Err(Error::Invalid {
                reason: "gh reported no authenticated user".to_owned(),
            });
        }
        Ok(login)
    }

    fn open_change(&self, req: ChangeSpec) -> Result<ChangeRequest> {
        addressable_branch(&req.head, "the head branch")?;
        addressable_branch(&req.base, "the base branch")?;
        // The publication rule the crate states, applied rather than restated —
        // and applied here as well as where a publication takes a request in, because
        // [`ChangeSpec`] is public and this trait is reachable directly. A reason no
        // publication could have carried must not open a change request the record
        // then cannot say anything readable about.
        if let Some(reason) = &req.draft {
            reason.checked()?;
        }
        let body = req.body.unwrap_or_default();
        let mut args = vec![
            "pr", "create", "--repo", &self.repo, "--head", &req.head, "--base", &req.base,
            "--title", &req.title, "--body", &body,
        ];
        // The whole of what the reason does at the host: it opens as a draft. Nothing
        // of the reason itself is written there — see `DraftReason`.
        if req.draft.is_some() || req.draft_awaiting_checks {
            args.push("--draft");
        }
        let raw = gh::invoke(&args)?;
        let url = raw
            .lines()
            .map(str::trim)
            .rfind(|line| line.starts_with("http"))
            .ok_or_else(|| invalid(format!("gh pr create printed no URL: {raw:?}")))?;
        let parsed = Url::parse(url)
            .map_err(|e| invalid(format!("gh pr create printed {url:?}, not a URL: {e}")))?;
        // The host numbers its change requests, and the number is the last segment
        // of the URL it printed. Anything else in that position is `gh` having
        // printed something other than a change request's URL, which is not an
        // identifier to go on addressing it by.
        let id = parsed
            .path_segments()
            .and_then(|mut segments| segments.next_back())
            .filter(|segment| !segment.is_empty() && segment.chars().all(|c| c.is_ascii_digit()))
            .ok_or_else(|| {
                invalid(format!(
                    "gh pr create printed {url:?}, which names no change"
                ))
            })?
            .to_owned();
        Ok(ChangeRequest {
            // The commit the new change request's checks will be reported against,
            // which `gh pr create` does not print.
            head_sha: head_sha(&self.view(&id, "headRefOid")?)?,
            id: ChangeId(id),
            url: parsed,
            base: req.base,
        })
    }

    fn find_changes(&self, head: &str, base: &str) -> Result<Vec<ChangeRequest>> {
        addressable_branch(head, "the head branch")?;
        addressable_branch(base, "the base branch")?;
        let raw = gh::invoke(&[
            "pr",
            "list",
            "--repo",
            &self.repo,
            "--head",
            head,
            "--base",
            base,
            "--state",
            "open",
            "--json",
            "number,url,state,headRefOid",
        ])?;
        let value = gh::json(&raw)?;
        let items = value
            .as_array()
            .ok_or_else(|| invalid(format!("gh pr list returned {raw:?}, not a list")))?;
        let mut changes = Vec::new();
        for item in items {
            let url = item.get("url").and_then(|v| v.as_str()).unwrap_or_default();
            let parsed = Url::parse(url)
                .map_err(|e| invalid(format!("gh pr list returned {url:?}, not a URL: {e}")))?;
            let number = item
                .get("number")
                .and_then(|value| value.as_u64())
                .ok_or_else(|| invalid(format!("gh pr list returned no number: {raw:?}")))?
                .to_string();
            changes.push(ChangeRequest {
                id: ChangeId(number),
                url: parsed,
                head_sha: head_sha(item)?,
                base: base.to_owned(),
            });
        }
        Ok(changes)
    }

    fn change_checks(&self, cr: &ChangeRequest) -> Result<ChangeChecks> {
        let rollup = |checks| ChangeChecks {
            checks,
            sources: [CheckSource::StatusChecks].into_iter().collect(),
        };
        match consult()? {
            Consult::StatusChecks => self.rollup_checks(cr).map(rollup),
            Consult::Actions => self.actions_checks(cr),
            // The rollup first, because it is the complete answer and this build
            // cannot know what the credential is until it is refused. A refusal is
            // never read as "no checks": the fallback either produces an answer of
            // its own or both refusals are reported together.
            Consult::Either => match self.rollup_checks(cr) {
                Ok(checks) => Ok(rollup(checks)),
                Err(refused) if check_rollup_refused_for_pat(&refused) => self
                    .actions_checks(cr)
                    .map_err(|actions| unreadable(&self.repo, cr, &refused, &actions)),
                Err(refused) => Err(refused),
            },
        }
    }

    /// Store one check's log as an artifact, or refuse.
    ///
    /// A fetch that did not produce the log is an error and no artifact: an
    /// artifact reads as what the check printed, so one holding the reason there is
    /// none is a lie in the only record a consumer has. A caller that must not fail
    /// over a missing log declines to fail over this error, as [`crate::publish`]
    /// does.
    fn check_log(&self, cr: &ChangeRequest, check: &Check) -> Result<ArtifactId> {
        // The two are told apart, because they are two different things to whoever
        // reads the refusal: a name this build would not ask about is this build's
        // own doing and says so, while a host that would not produce the log is the
        // host's and quotes what it said. They used to arrive as one message
        // attributing both to the host, which is how a refusal this crate made read
        // as GitHub keeping its logs — and why it went unnoticed for as long as it
        // did. The kind stays `Invalid` for both, because the failure vocabulary is
        // fixed across the libraries that route on it; the message is where the
        // actor is named.
        matchable(&check.name, cr)?;
        let log = self.log_of(cr, &check.name).map_err(|error| {
            invalid(format!(
                "the host could not produce a log for check {:?} on {}: {error}",
                check.name, cr.url
            ))
        })?;
        Ok(ArtifactId(stream::store_artifact("log", &log)?.id))
    }

    fn merge(&self, cr: &ChangeRequest, policy: MergePolicy) -> Result<MergeOutcome> {
        match policy {
            MergePolicy::LocalDirect | MergePolicy::ChangeOpen => Ok(MergeOutcome::Open),
            MergePolicy::ChangeAuto => {
                addressable(&cr.id.0, "change request id")?;
                gh::invoke(&[
                    "pr", "merge", &cr.id.0, "--repo", &self.repo, "--squash", "--auto",
                ])?;
                let view = self.view(&cr.id.0, MERGE_FIELDS)?;
                Ok(match merged_sha(&view, cr)? {
                    Some(sha) => MergeOutcome::Merged(sha),
                    None => MergeOutcome::Queued,
                })
            }
            MergePolicy::ChangeDirect => {
                addressable(&cr.id.0, "change request id")?;
                gh::invoke(&["pr", "merge", &cr.id.0, "--repo", &self.repo, "--squash"])?;
                let view = self.view(&cr.id.0, MERGE_FIELDS)?;
                match merged_sha(&view, cr)? {
                    Some(sha) => Ok(MergeOutcome::Merged(sha)),
                    None => Err(Error::GateFailed {
                        reason: format!(
                            "the host accepted the merge of {} but reports it unmerged",
                            cr.url
                        ),
                    }),
                }
            }
        }
    }

    fn ready_for_review(&self, cr: &ChangeRequest) -> Result<()> {
        addressable(&cr.id.0, "change request id")?;
        gh::invoke(&["pr", "ready", &cr.id.0, "--repo", &self.repo]).map(|_| ())
    }

    /// One `gh pr edit`, handing the body over as a file.
    ///
    /// A file rather than `--body`, because a body is prose of unbounded size and an
    /// argument vector is not where multi-line Markdown belongs: the same reason
    /// `onevcs publish` takes `--body-file`. The file is written under a scratch
    /// directory that goes when this returns, and `gh` reads it before then.
    fn describe_change(&self, cr: &ChangeRequest, title: Option<&str>, body: &str) -> Result<()> {
        addressable(&cr.id.0, "change request id")?;
        let scratch = tempfile::tempdir().map_err(|failure| {
            invalid(format!(
                "could not create a scratch directory to hand the body of {} to gh: {failure}",
                cr.url
            ))
        })?;
        let file = scratch.path().join("body.md");
        std::fs::write(&file, body).map_err(crate::error::at(
            "write the change request's body to",
            &file,
        ))?;
        let file = file.to_string_lossy().into_owned();
        let mut args = vec![
            "pr",
            "edit",
            &cr.id.0,
            "--repo",
            &self.repo,
            "--body-file",
            &file,
        ];
        if let Some(title) = title {
            args.extend(["--title", title]);
        }
        gh::invoke(&args).map(|_| ())
    }

    /// One `gh pr view`, reading exactly the two fields a description is.
    ///
    /// A response missing either is refused rather than read as empty: "the change
    /// request has no body" and "the host would not say what the body is" are
    /// different facts, and a caller finishing a description off what it reads here
    /// would otherwise start from a blank the host never answered.
    fn change_description(&self, cr: &ChangeRequest) -> Result<Description> {
        addressable(&cr.id.0, "change request id")?;
        let view = self.view(&cr.id.0, "title,body")?;
        let read = |name: &str| {
            view.get(name)
                .and_then(serde_json::Value::as_str)
                .map(str::to_owned)
                .ok_or_else(|| {
                    invalid(format!(
                        "gh pr view answered about {} without its {name}, so what the change \
                         request says cannot be read",
                        cr.url
                    ))
                })
        };
        Ok(Description {
            title: read("title")?,
            body: read("body")?,
        })
    }

    /// One `gh api repos/{owner}/{name}`, reading the two fields GitHub states a
    /// repository's visibility in. `visibility` is `public`, `private` or `internal`,
    /// and an internal repository is private to everybody outside its organisation;
    /// an answer carrying neither field is refused rather than read as either.
    fn visibility(&self) -> Result<Visibility> {
        let answer = gh::json(&gh::invoke(&["api", &format!("repos/{}", self.repo)])?)?;
        match answer.get("visibility").and_then(serde_json::Value::as_str) {
            Some("public") => return Ok(Visibility::Public),
            Some("private" | "internal") => return Ok(Visibility::Private),
            _ => {}
        }
        match answer.get("private").and_then(serde_json::Value::as_bool) {
            Some(true) => Ok(Visibility::Private),
            Some(false) => Ok(Visibility::Public),
            None => Err(invalid(format!(
                "gh api answered about {} without its visibility",
                self.repo
            ))),
        }
    }

    /// One `gh pr view`, reading the one field the host decides a draft by.
    ///
    /// A response that does not carry it is refused rather than read as "not a
    /// draft": what this decides is whether a change may be asked to merge, and
    /// "could not look" reported as "nothing is holding it" is the one answer that
    /// lands work somebody held back.
    fn is_draft(&self, cr: &ChangeRequest) -> Result<bool> {
        addressable(&cr.id.0, "change request id")?;
        let view = self.view(&cr.id.0, "isDraft")?;
        view.get("isDraft")
            .and_then(serde_json::Value::as_bool)
            .ok_or_else(|| {
                invalid(format!(
                    "gh pr view answered about {} without saying whether it is a draft, so \
                     whether the host is holding it cannot be read",
                    cr.url
                ))
            })
    }

    /// One `gh pr view`, reading exactly the two fields a merge is decided from —
    /// the same read `merge` makes, through the same parser, so watching a change
    /// request and merging one cannot come to disagree about what merged means.
    fn merged_at(&self, cr: &ChangeRequest) -> Result<Option<Sha>> {
        addressable(&cr.id.0, "change request id")?;
        merged_sha(&self.view(&cr.id.0, MERGE_FIELDS)?, cr)
    }

    /// One `gh pr view`, reading the two fields a merge is decided from and the head
    /// it was of — the read [`merged_at`](RemoteHost::merged_at) makes, through the same
    /// parser, with `headRefOid` beside it rather than in a second request.
    fn merged_head(&self, cr: &ChangeRequest) -> Result<Option<MergedChange>> {
        addressable(&cr.id.0, "change request id")?;
        let view = self.view(&cr.id.0, MERGED_HEAD_FIELDS)?;
        let Some(commit) = merged_sha(&view, cr)? else {
            return Ok(None);
        };
        Ok(Some(MergedChange {
            commit,
            head: head_sha(&view)?,
        }))
    }

    /// One `gh pr view`, reading exactly the field GitHub records a merge's time in.
    ///
    /// `mergedAt` is null — or GitHub's zero time — on a change request that has not
    /// merged, and both read as `None`.
    fn merge_time(&self, cr: &ChangeRequest) -> Result<Option<String>> {
        addressable(&cr.id.0, "change request id")?;
        Ok(reported_time(
            &self.view(&cr.id.0, MERGE_TIME_FIELDS)?,
            "mergedAt",
        ))
    }

    /// One `gh pr view`, reading exactly the two fields GitHub decides a merge's
    /// mergeability by.
    ///
    /// `mergeable` is the answer — `MERGEABLE`, `CONFLICTING`, or `UNKNOWN` while
    /// GitHub has not computed it — and `mergeStateStatus` is quoted beside it, since
    /// `DIRTY` is how GitHub spells the same conflict there. A response that carries
    /// no `mergeable`, or a value GitHub has never answered, is refused rather than
    /// read as either: a conflict nobody reported ends a publication, and a mergeable
    /// change nobody reported hides one.
    fn mergeability(&self, cr: &ChangeRequest) -> Result<Mergeability> {
        addressable(&cr.id.0, "change request id")?;
        let view = self.view(&cr.id.0, MERGEABILITY_FIELDS)?;
        let mergeable = view
            .get("mergeable")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| {
                invalid(format!(
                    "gh pr view answered about {} without saying whether it can merge: {view}",
                    cr.url
                ))
            })?;
        let status = view
            .get("mergeStateStatus")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("unreported");
        match mergeable.to_ascii_uppercase().as_str() {
            "MERGEABLE" => Ok(Mergeability::Mergeable),
            "CONFLICTING" => Ok(Mergeability::Conflicting {
                reported: format!("mergeable: {mergeable}, mergeStateStatus: {status}"),
            }),
            "UNKNOWN" => Ok(Mergeability::Unknown),
            _ => Err(invalid(format!(
                "gh pr view reports {} as mergeable {mergeable:?}, which is none of \
                 MERGEABLE, CONFLICTING or UNKNOWN, so whether it can merge cannot be read",
                cr.url
            ))),
        }
    }

    /// Two REST reads about the commit the caller names: the workflow runs on it, and
    /// its check suites.
    ///
    /// A run counts while its `status` is anything but `completed`; a suite counts
    /// while it is not `completed` **and** has at least one check run, because GitHub
    /// leaves an installed app's empty `queued` suite on every commit for ever. A
    /// credential refused the suites answers from the runs alone, saying so with
    /// `complete: false`; one refused both reads is the runs' refusal.
    ///
    /// The commit asked about is the caller's — a watch names the one it pushed — and
    /// the commit answered about is read off the records GitHub returned, so a host
    /// whose records name another commit says so rather than having this build's
    /// question stamped onto its answer. Reading the change request's head first
    /// would cost a third request on every read and decide nothing these two do not.
    fn head_activity(&self, cr: &ChangeRequest) -> Result<HeadActivity> {
        let sha = commit(&cr.head_sha)?;
        let runs = self.api(&format!(
            "repos/{}/actions/runs?head_sha={sha}&per_page={PAGE}",
            self.repo
        ))?;
        let mut answered: Option<Sha> = None;
        let mut in_progress = Vec::new();
        let mut about = |record: &serde_json::Value| -> Result<()> {
            if let Some(head) = reported_sha(record, "head_sha")? {
                if answered.as_ref().is_some_and(|seen| *seen != head) {
                    return Err(invalid(format!(
                        "GitHub answered about the work on {sha} with records naming two \
                         commits, {} and {}, so which one is running cannot be told",
                        answered.as_ref().map_or("", |seen| seen.0.as_str()),
                        head.0
                    )));
                }
                answered = Some(head);
            }
            Ok(())
        };
        for run in listed(&runs, "workflow_runs", &format!("the commit {sha}"))? {
            about(run)?;
            if !is_completed(run) {
                in_progress.push(named(run, &["name"], "workflow run"));
            }
        }
        let suites = gh::invoke(&[
            "api",
            &format!(
                "repos/{}/commits/{sha}/check-suites?per_page={PAGE}",
                self.repo
            ),
        ]);
        let complete = match suites {
            Ok(raw) => {
                let suites = gh::json(&raw)?;
                for suite in listed(&suites, "check_suites", &format!("the commit {sha}"))? {
                    about(suite)?;
                    let runs = suite
                        .get("latest_check_runs_count")
                        .and_then(serde_json::Value::as_u64)
                        .ok_or_else(|| {
                            invalid(format!(
                                "GitHub reported a check suite on {sha} without saying how many \
                                 check runs it has: {suite}"
                            ))
                        })?;
                    if runs > 0 && !is_completed(suite) {
                        in_progress.push(named(suite, &["app", "name"], "check suite"));
                    }
                }
                true
            }
            Err(refused) if refused_to_this_credential(&refused) => false,
            Err(other) => return Err(other),
        };
        Ok(HeadActivity {
            head: answered.unwrap_or_else(|| Sha(sha.to_owned())),
            in_progress,
            complete,
        })
    }

    /// One GraphQL query document, paged — see `review::github`.
    fn review_comments(&self, change: &ChangeId, since: Option<&ReadMarker>) -> Result<ReviewRead> {
        review::github::read(&self.repo, change, since)
    }

    /// One REST request — see `review::github`.
    fn reply_to_comment(
        &self,
        change: &ChangeId,
        comment: &CommentId,
        body: &str,
        _key: &str,
    ) -> Result<PostedReply> {
        review::github::reply(&self.repo, change, comment, body)
    }

    /// One aliased GraphQL query per 50 change requests — see `standings::github`.
    fn change_standings(&self, root: &str, changes: &[ChangeId]) -> Result<ChangeStandings> {
        standings::github::read(&self.repo, root, changes)
    }

    /// One aliased GraphQL query per 150 change requests — see `standings::github`.
    fn review_standings(
        &self,
        root: &str,
        changes: &[(ChangeId, Option<ReadMarker>)],
    ) -> Result<ReviewStandings> {
        standings::github::read_with_reviews(&self.repo, root, changes)
    }

    /// One REST request — see `standings::github`.
    fn retarget_change(
        &self,
        change: &ChangeId,
        base: &str,
        body: Option<&str>,
    ) -> Result<ReadCost> {
        standings::github::retarget(&self.repo, change, base, body)
    }

    /// One REST request — see `standings::github`.
    fn reopen_change(&self, change: &ChangeId) -> Result<ReadCost> {
        standings::github::reopen(&self.repo, change)
    }

    fn required_checks_on(&self, base: &str) -> Result<RequiredChecks> {
        // The rulesets first, and their refusal is the whole read's: every
        // credential that can see the repository can read them, so one that cannot
        // has not answered about anything. Classic protection is asked second and
        // its refusal is recorded rather than raised, because the credential GitHub
        // steers people toward is refused it on every repository, and the rulesets'
        // answer is still worth having — marked as the part it is.
        let checks = self.required_on(base, &self.repo)?;
        let mut answer = RequiredChecks {
            checks,
            unconsulted: BTreeMap::new(),
        };
        match self.classic_protection(base)? {
            Ok(contexts) => answer.checks.extend(contexts),
            Err(refusal) => {
                answer
                    .unconsulted
                    .insert(ProtectionSource::BranchProtection, refusal);
            }
        }
        Ok(answer)
    }

    fn requires_up_to_date(&self, base: &str) -> Result<bool> {
        // The two sources `required_checks_on` reads, in the same order and with the
        // same weight: either one requiring it is the answer, and "neither does" is an
        // answer only once both were read.
        if self.ruled_up_to_date(base)? {
            return Ok(true);
        }
        match self.classic_up_to_date(base)? {
            Ok(strict) => Ok(strict),
            Err(refusal) => Err(invalid(format!(
                "whether {}'s {base:?} requires an up-to-date branch could not be read from \
                 classic branch protection: {refusal}",
                self.repo
            ))),
        }
    }

    /// One `gh repo view`, reading the one field GitHub decides it by.
    fn allows_auto_merge(&self) -> Result<bool> {
        let answer = gh::json(&gh::invoke(&[
            "repo",
            "view",
            &self.repo,
            "--json",
            "autoMergeAllowed",
        ])?)?;
        answer
            .get("autoMergeAllowed")
            .and_then(serde_json::Value::as_bool)
            .ok_or_else(|| {
                invalid(format!(
                    "gh repo view answered about {} without saying whether it allows auto-merge: \
                     {answer}",
                    self.repo
                ))
            })
    }
}

/// The refusal for a host that will not say which of its checks block the merge.
///
/// Inferring it is the one shape that must never be guessed: it is the difference
/// between a merge that was gated and one that only looked like it. What changed
/// with the real backend is *where* the question is asked, not that it may be
/// skipped — a host that answers `gh pr checks --required` with something other
/// than the checks it requires is refused here rather than read as requiring none.
fn unsaid(url: &Url, detail: &str) -> Error {
    invalid(format!(
        "gh pr checks --required answered about {url} with {detail}, so a check it reported does \
         not say whether it blocks the merge"
    ))
}

/// The same refusal from the rulesets read, which is addressed to a base branch and
/// names whatever asked about it — a change request's URL, or an identity.
fn unsaid_about(about: &str, detail: &str) -> Error {
    invalid(format!(
        "the repository's rulesets answered about {about} with {detail}, so a check they \
         reported does not say whether it blocks the merge"
    ))
}

/// The refusal for a host that has no check on the head to report yet.
///
/// Separate from [`unsaid`] because the next move differs: this one is a clock, and
/// whoever reads it waits rather than re-runs.
fn unregistered(url: &Url, said: &str) -> Error {
    invalid(format!(
        "the host reports no check at all yet on the head of {url} ({said}), which is not the \
         same as a repository that declares none required — it is what a head pushed moments ago \
         looks like — so whether anything blocks the merge cannot be read from it"
    ))
}

/// One entry of the host's check rollup, required to say what it is.
///
/// Defaulting a missing field here is what would let a host that answered
/// partially be read as a green check — the one shape that must never be inferred.
/// Whether the check *blocks* is not in this entry at all and never was: it comes
/// from [`GitHub::required_checks`], which refuses a host that will not say.
///
/// Two shapes, told apart by the `__typename` GitHub writes on each: a check run
/// (`CheckRun` — every Actions job, and any app's run), and a commit status an
/// integration posted (`StatusContext`), which [`status_context`] reads.
fn check(
    entry: &serde_json::Value,
    cr: &ChangeRequest,
    required: &BTreeSet<String>,
    head: Option<&Sha>,
) -> Result<Check> {
    let field = |name: &str| -> Result<&str> {
        entry
            .get(name)
            .and_then(|value| value.as_str())
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                invalid(format!(
                    "gh pr view returned a check on {} with no {name}: {entry}",
                    cr.url
                ))
            })
    };
    if entry.get("__typename").and_then(|value| value.as_str()) == Some("StatusContext") {
        return status_context(entry, cr, required, head);
    }
    let name = field("name").or_else(|_| field("context"))?.to_owned();
    let blocks = required.contains(&name);
    Ok(Check {
        name,
        status: field("status")?.to_ascii_lowercase(),
        // Genuinely absent while a check is still running, which is the one thing
        // the host cannot yet know.
        conclusion: entry
            .get("conclusion")
            .and_then(|value| value.as_str())
            .filter(|value| !value.is_empty())
            .map(str::to_ascii_lowercase),
        required: blocks,
        head: head.cloned(),
        // A check run's own address; a commit status spells its own `targetUrl`, and
        // is read by `status_context`.
        url: reported_url(entry, "detailsUrl"),
        started_at: reported_time(entry, "startedAt"),
        completed_at: reported_time(entry, "completedAt"),
    })
}

/// One commit status in the host's rollup, read as the check it stands for.
///
/// A commit status has one `state` where a check run has a status and a conclusion:
/// `PENDING` (and `EXPECTED`, a required context nothing has posted yet) is a check
/// still running, and `SUCCESS`, `FAILURE` and `ERROR` are a completed one concluding
/// that way — so an `ERROR` is red, as every conclusion `Check::state` does not name
/// is. A state none of those five is refused rather than guessed at: reading an
/// unknown one as either would wave a merge through or hold one for ever. It is named
/// by its `context`, which is what branch protection requires it by, and its start is
/// when the integration posted it — a status posted again after a lift is a new one.
fn status_context(
    entry: &serde_json::Value,
    cr: &ChangeRequest,
    required: &BTreeSet<String>,
    head: Option<&Sha>,
) -> Result<Check> {
    let named = |name: &str| {
        entry
            .get(name)
            .and_then(|value| value.as_str())
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                invalid(format!(
                    "gh pr view returned a commit status on {} with no {name}: {entry}",
                    cr.url
                ))
            })
    };
    let name = named("context")?.to_owned();
    let state = named("state")?;
    let (status, conclusion) = match state.to_ascii_uppercase().as_str() {
        "PENDING" | "EXPECTED" => ("pending", None),
        "SUCCESS" => ("completed", Some("success")),
        "FAILURE" => ("completed", Some("failure")),
        "ERROR" => ("completed", Some("error")),
        _ => {
            return Err(invalid(format!(
                "gh pr view reports commit status {name:?} on {} as {state:?}, which is none of \
                 PENDING, EXPECTED, SUCCESS, FAILURE or ERROR, so where it stands cannot be read",
                cr.url
            )))
        }
    };
    Ok(Check {
        required: required.contains(&name),
        name,
        status: status.to_owned(),
        conclusion: conclusion.map(str::to_owned),
        head: head.cloned(),
        url: reported_url(entry, "targetUrl"),
        started_at: reported_time(entry, "startedAt"),
        completed_at: None,
    })
}

/// When a host response says a run started — or completed, or a change merged — or
/// `None` where it did not say.
///
/// GitHub answers a run that is queued and has not started with the zero time rather
/// than with nothing, and that is read as nothing: a start every queued run shares is
/// no run's identity, and a time every unfinished thing shares is no time at all.
pub(crate) fn reported_time(entry: &serde_json::Value, field: &str) -> Option<String> {
    entry
        .get(field)
        .and_then(|value| value.as_str())
        .filter(|value| !value.is_empty() && !value.starts_with("0001-01-01"))
        .map(str::to_owned)
}

/// What [`merged_sha`] reads, which is what a merge asks `gh pr view` for.
const MERGE_FIELDS: &str = "state,mergeCommit";

/// What [`GitHub`]'s `merged_head` reads: [`MERGE_FIELDS`] and the head it merged.
const MERGED_HEAD_FIELDS: &str = "state,mergeCommit,headRefOid";

/// What [`GitHub`]'s `merge_time` reads.
const MERGE_TIME_FIELDS: &str = "mergedAt";

/// What [`GitHub`]'s `mergeability` reads.
const MERGEABILITY_FIELDS: &str = "mergeable,mergeStateStatus";

/// The commit a merged change request landed as, or `None` while it is still open.
///
/// A host reporting `MERGED` without naming the commit is answering wrongly rather
/// than answering "not yet": the commit is the whole evidence that the change
/// reached its base, and reporting a merge with no SHA is the one thing that must
/// not be passed through.
fn merged_sha(view: &serde_json::Value, cr: &ChangeRequest) -> Result<Option<Sha>> {
    let state = view
        .get("state")
        .and_then(|value| value.as_str())
        .ok_or_else(|| invalid(format!("gh pr view returned no state for {}", cr.url)))?;
    if !state.eq_ignore_ascii_case("merged") {
        return Ok(None);
    }
    view.get("mergeCommit")
        .and_then(|commit| commit.get("oid"))
        .and_then(|value| value.as_str())
        .filter(|value| !value.is_empty())
        .map(|sha| Some(Sha(sha.to_owned())))
        .ok_or_else(|| {
            invalid(format!(
                "gh pr view reports {} merged without naming the commit it merged as",
                cr.url
            ))
        })
}

/// The commit a change request's checks are reported against.
fn head_sha(view: &serde_json::Value) -> Result<Sha> {
    view.get("headRefOid")
        .and_then(|value| value.as_str())
        .filter(|value| !value.is_empty())
        .map(|sha| Sha(sha.to_owned()))
        .ok_or_else(|| invalid(format!("gh returned a change request with no head: {view}")))
}