onetaskgraph-github-projects 0.14.9

A onetaskgraph source over GitHub Projects.
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
//! Deterministic drift check for the exact GitHub GraphQL production documents.
//!
//! The pinned subset defines no `updateProjectV2`, no `ProjectV2.shortDescription` and no
//! `ProjectV2.readme`, so a document that reached for one would fail here rather than
//! rename a user's board. It deliberately defines `updateProjectV2Field` for the one
//! guarded status-options document, and validates the exact document production sends.

use graphql_parser::{query, schema};
use std::collections::{HashMap, HashSet};

// Shared with the two GitHub doubles, which call the halves of it this file does not.
#[allow(dead_code)]
mod github_schema;

#[test]
fn status_option_colors_match_the_pinned_graphql_vocabulary() {
    use onetaskgraph_github_projects::StatusOptionColor;

    let rust_schema = schemars::schema_for!(StatusOptionColor);
    let rust_value = rust_schema.as_value();
    let rust_variants = rust_value
        .get("enum")
        .or_else(|| rust_value.get("oneOf"))
        .and_then(serde_json::Value::as_array)
        .expect("StatusOptionColor is a closed enum");
    let rust_colors = rust_variants
        .iter()
        .map(|color| {
            color
                .as_str()
                .or_else(|| color.get("const").and_then(serde_json::Value::as_str))
                .expect("a color token")
                .to_owned()
        })
        .collect::<HashSet<_>>();
    let graphql_schema =
        schema::parse_schema::<String>(include_str!("fixtures/schema.graphql")).unwrap();
    let graphql_colors = graphql_schema
        .definitions
        .iter()
        .find_map(|definition| match definition {
            schema::Definition::TypeDefinition(schema::TypeDefinition::Enum(value))
                if value.name == "ProjectV2SingleSelectFieldOptionColor" =>
            {
                Some(
                    value
                        .values
                        .iter()
                        .map(|color| color.name.clone())
                        .collect::<HashSet<_>>(),
                )
            }
            _ => None,
        })
        .expect("the pinned schema defines GitHub's option colors");
    assert_eq!(rust_colors, graphql_colors);
}

/// Every enum member a value names, inside lists and objects alike.
fn enum_values<'a>(value: &'a query::Value<'a, String>) -> Vec<&'a str> {
    match value {
        query::Value::Enum(member) => vec![member.as_str()],
        query::Value::List(values) => values.iter().flat_map(enum_values).collect(),
        query::Value::Object(fields) => fields.values().flat_map(enum_values).collect(),
        _ => Vec::new(),
    }
}

fn named_type<'a>(kind: &'a schema::Type<'a, String>) -> &'a str {
    match kind {
        schema::Type::NamedType(name) => name,
        schema::Type::ListType(inner) | schema::Type::NonNullType(inner) => named_type(inner),
    }
}

fn selected_keys(selection: &query::SelectionSet<'_, String>, keys: &mut HashSet<String>) {
    for selected in &selection.items {
        match selected {
            query::Selection::Field(value) => {
                keys.insert(value.alias.as_ref().unwrap_or(&value.name).clone());
                selected_keys(&value.selection_set, keys);
            }
            query::Selection::InlineFragment(value) => selected_keys(&value.selection_set, keys),
            query::Selection::FragmentSpread(_) => {}
        }
    }
}

fn assert_fixture_keys(value: &serde_json::Value, selected: &HashSet<String>) {
    match value {
        serde_json::Value::Object(object) => {
            for (key, value) in object {
                assert!(
                    key == "__typename" || selected.contains(key),
                    "fixture key {key} is absent from its production operation"
                );
                assert_fixture_keys(value, selected);
            }
        }
        serde_json::Value::Array(values) => {
            for value in values {
                assert_fixture_keys(value, selected);
            }
        }
        _ => {}
    }
}

#[test]
fn pinned_schema_checks_selected_fields_arguments_types_fragments_and_fixture_keys() {
    use onetaskgraph_github_projects::graphql;

    let schema = schema::parse_schema::<String>(include_str!("fixtures/schema.graphql")).unwrap();
    let fields = schema
        .definitions
        .iter()
        .filter_map(|definition| match definition {
            schema::Definition::TypeDefinition(schema::TypeDefinition::Object(value)) => {
                Some((value.name.as_str(), value.fields.as_slice()))
            }
            schema::Definition::TypeDefinition(schema::TypeDefinition::Interface(value)) => {
                Some((value.name.as_str(), value.fields.as_slice()))
            }
            _ => None,
        })
        .collect::<HashMap<_, _>>();
    let known_types = schema
        .definitions
        .iter()
        .filter_map(|definition| match definition {
            schema::Definition::TypeDefinition(value) => Some(match value {
                schema::TypeDefinition::Scalar(value) => value.name.as_str(),
                schema::TypeDefinition::Object(value) => value.name.as_str(),
                schema::TypeDefinition::Interface(value) => value.name.as_str(),
                schema::TypeDefinition::Union(value) => value.name.as_str(),
                schema::TypeDefinition::Enum(value) => value.name.as_str(),
                schema::TypeDefinition::InputObject(value) => value.name.as_str(),
            }),
            _ => None,
        })
        .collect::<HashSet<_>>();
    // Every enum's members, so a variable's default naming one can be held to the pin.
    let enum_members = schema
        .definitions
        .iter()
        .filter_map(|definition| match definition {
            schema::Definition::TypeDefinition(schema::TypeDefinition::Enum(value)) => Some((
                value.name.as_str(),
                value
                    .values
                    .iter()
                    .map(|member| member.name.as_str())
                    .collect::<HashSet<_>>(),
            )),
            _ => None,
        })
        .collect::<HashMap<_, _>>();
    let possible_types = |name: &str| {
        let mut possible = HashSet::new();
        for definition in &schema.definitions {
            match definition {
                schema::Definition::TypeDefinition(schema::TypeDefinition::Object(value)) => {
                    if value.name == name
                        || value
                            .implements_interfaces
                            .iter()
                            .any(|interface| interface == name)
                    {
                        possible.insert(value.name.as_str());
                    }
                }
                schema::Definition::TypeDefinition(schema::TypeDefinition::Union(value))
                    if value.name == name =>
                {
                    possible.extend(value.types.iter().map(String::as_str));
                }
                _ => {}
            }
        }
        possible
    };

    fn validate<'query, 'schema>(
        type_name: &str,
        selection: &'query query::SelectionSet<'query, String>,
        fragments: &HashMap<&str, &'query query::FragmentDefinition<'query, String>>,
        fields: &HashMap<&str, &'schema [schema::Field<'schema, String>]>,
        known_types: &HashSet<&str>,
        possible_types: &impl Fn(&str) -> HashSet<&'schema str>,
        variables: &HashMap<&str, &query::Type<'query, String>>,
    ) {
        for selected in &selection.items {
            match selected {
                query::Selection::Field(selected) => {
                    if selected.name == "__typename" {
                        continue;
                    }
                    let field = fields
                        .get(type_name)
                        .and_then(|fields| fields.iter().find(|field| field.name == selected.name))
                        .unwrap_or_else(|| {
                            panic!(
                                "pinned schema {type_name} lacks selected field {}",
                                selected.name
                            )
                        });
                    for (argument, _) in &selected.arguments {
                        let schema_argument = field
                            .arguments
                            .iter()
                            .find(|value| value.name == *argument)
                            .unwrap_or_else(|| {
                                panic!(
                                    "pinned schema {type_name}.{} lacks argument {argument}",
                                    selected.name
                                )
                            });
                        let query::Value::Variable(variable) = &selected
                            .arguments
                            .iter()
                            .find(|(name, _)| name == argument)
                            .unwrap()
                            .1
                        else {
                            panic!("production arguments must use declared variables")
                        };
                        let variable_type = format!("{:?}", variables[variable.as_str()]);
                        let argument_type = format!("{:?}", schema_argument.value_type);
                        let compatible = variable_type == argument_type
                            || variable_type
                                .strip_prefix("NonNullType(")
                                .and_then(|value| value.strip_suffix(')'))
                                == Some(argument_type.as_str());
                        assert!(
                            compatible,
                            "variable ${variable} no longer matches {type_name}.{}({argument}:): {variable_type:?} versus {:?}",
                            selected.name, schema_argument.value_type
                        );
                    }
                    for required in field.arguments.iter().filter(|argument| {
                        matches!(argument.value_type, schema::Type::NonNullType(_))
                            && argument.default_value.is_none()
                    }) {
                        assert!(
                            selected
                                .arguments
                                .iter()
                                .any(|(name, _)| name == &required.name),
                            "production operation omits required {type_name}.{}({}:)",
                            selected.name,
                            required.name
                        );
                    }
                    if !selected.selection_set.items.is_empty() {
                        validate(
                            named_type(&field.field_type),
                            &selected.selection_set,
                            fragments,
                            fields,
                            known_types,
                            possible_types,
                            variables,
                        );
                    }
                }
                query::Selection::InlineFragment(fragment) => {
                    let condition = fragment.type_condition.as_ref().map_or(type_name, |value| {
                        let query::TypeCondition::On(name) = value;
                        name.as_str()
                    });
                    assert!(
                        known_types.contains(condition),
                        "pinned schema lacks {condition}"
                    );
                    assert!(
                        !possible_types(type_name).is_disjoint(&possible_types(condition)),
                        "fragment on {condition} cannot apply to {type_name}"
                    );
                    validate(
                        condition,
                        &fragment.selection_set,
                        fragments,
                        fields,
                        known_types,
                        possible_types,
                        variables,
                    );
                }
                query::Selection::FragmentSpread(spread) => {
                    let fragment = fragments[spread.fragment_name.as_str()];
                    let query::TypeCondition::On(condition) = &fragment.type_condition;
                    assert!(
                        known_types.contains(condition.as_str()),
                        "pinned schema lacks {condition}"
                    );
                    assert!(
                        !possible_types(type_name).is_disjoint(&possible_types(condition)),
                        "fragment {condition} cannot apply to {type_name}"
                    );
                    validate(
                        condition,
                        &fragment.selection_set,
                        fragments,
                        fields,
                        known_types,
                        possible_types,
                        variables,
                    );
                }
            }
        }
    }

    for (operation, fixture_pointer, fixture) in [
        (
            graphql::BOARD,
            Some("/data/owner"),
            Some(include_str!("fixtures/project.json")),
        ),
        (
            graphql::SEARCH_ISSUES,
            Some("/data/search"),
            Some(include_str!("fixtures/issues.json")),
        ),
        (graphql::BOARD_WITH_COMMENTS, None, None),
        (graphql::ISSUE, None, None),
        (graphql::DOCUMENT_IN_PROJECT, None, None),
        (graphql::BOARD_FIELDS, None, None),
        (
            graphql::ORIGIN_LOOKUP,
            Some("/data"),
            Some(include_str!("fixtures/origin-lookup.json")),
        ),
        (graphql::DRAFT, None, None),
        (
            graphql::ISSUE_BOARD_ITEMS,
            Some("/data/node"),
            Some(include_str!("fixtures/issue-board-items.json")),
        ),
        (
            graphql::SUB_ISSUES,
            Some("/data/node"),
            Some(include_str!("fixtures/sub-issues.json")),
        ),
        (graphql::REPOSITORY, None, None),
        (graphql::CREATION_CONTEXT, None, None),
        (graphql::ORIGIN_LOOKUPS, None, None),
        (graphql::ORIGIN_LOOKUPS_WITH_MEMBERS, None, None),
        (graphql::CREATED_BOARD_ITEMS, None, None),
        (graphql::CREATE_ISSUES, None, None),
        (graphql::WRITE_FIELD_VALUES, None, None),
        (graphql::CLOSE_ISSUES, None, None),
        (graphql::UPDATE_ISSUES, None, None),
        (graphql::ADD_BLOCKED_BYS, None, None),
        (graphql::WRITE_FIELDS_AND_EDGES, None, None),
        (graphql::DELETE_ISSUES, None, None),
        (
            graphql::ISSUE_DEPENDENCIES,
            Some("/data/node"),
            Some(include_str!("fixtures/dependencies.json")),
        ),
        (
            graphql::ISSUE_DEPENDS_ON,
            Some("/data"),
            Some(include_str!("fixtures/dependencies-depends-on.json")),
        ),
        (
            graphql::ISSUE_DEPENDED_ON_BY,
            Some("/data"),
            Some(include_str!("fixtures/dependencies-depended-on-by.json")),
        ),
        (graphql::CREATE_ISSUE, None, None),
        (graphql::ADD_TO_BOARD, None, None),
        (graphql::UPDATE_ISSUE, None, None),
        (graphql::UPDATE_DRAFT, None, None),
        (graphql::UPDATE_FIELD, None, None),
        (graphql::UPDATE_FIELDS, None, None),
        (graphql::CLEAR_FIELD, None, None),
        (graphql::CREATE_FIELD, None, None),
        (graphql::STATUS_OPTIONS_UPDATE, None, None),
        (graphql::STATUS_OPTIONS_SNAPSHOT, None, None),
        (graphql::ADD_SUB_ISSUE, None, None),
        (graphql::REMOVE_SUB_ISSUE, None, None),
        (graphql::ADD_BLOCKED_BY, None, None),
        (graphql::REMOVE_BLOCKED_BY, None, None),
        (graphql::DELETE_ISSUE, None, None),
        (
            graphql::ISSUE_COMMENTS,
            Some("/data/node"),
            Some(include_str!("fixtures/comments.json")),
        ),
        (graphql::ISSUE_DETAIL, None, None),
        (graphql::ISSUE_DETAILS, None, None),
        (graphql::COMMENT_ISSUE, None, None),
        (graphql::ADD_COMMENT, None, None),
        (graphql::UPDATE_COMMENT, None, None),
        (graphql::DELETE_COMMENT, None, None),
    ] {
        let document = query::parse_query::<String>(operation).unwrap();
        let fragments = document
            .definitions
            .iter()
            .filter_map(|definition| match definition {
                query::Definition::Fragment(fragment) => Some((fragment.name.as_str(), fragment)),
                _ => None,
            })
            .collect::<HashMap<_, _>>();
        let (root, variable_definitions, selection_set) = match &document.definitions[0] {
            query::Definition::Operation(query::OperationDefinition::Query(operation)) => (
                "Query",
                &operation.variable_definitions,
                &operation.selection_set,
            ),
            query::Definition::Operation(query::OperationDefinition::Mutation(operation)) => (
                "Mutation",
                &operation.variable_definitions,
                &operation.selection_set,
            ),
            _ => panic!("production document must begin with a named query or mutation"),
        };
        for variable in variable_definitions {
            assert!(
                known_types.contains(named_type(&variable.var_type)),
                "pinned schema lacks variable type {}",
                named_type(&variable.var_type)
            );
            // A default is part of what the document sends, so every enum member it names is
            // one the pinned enum declares — and the credentialed lane holds GitHub to the pin.
            if let Some(default) = &variable.default_value {
                let enum_name = named_type(&variable.var_type);
                for member in enum_values(default) {
                    let members = enum_members.get(enum_name).unwrap_or_else(|| {
                        panic!("${} defaults to enum members of {enum_name}, which the pinned schema declares no enum of", variable.name)
                    });
                    assert!(
                        members.contains(member),
                        "${} defaults to {member}, which the pinned {enum_name} does not declare",
                        variable.name
                    );
                }
            }
        }
        let variables = variable_definitions
            .iter()
            .map(|variable| (variable.name.as_str(), &variable.var_type))
            .collect::<HashMap<_, _>>();
        validate(
            root,
            selection_set,
            &fragments,
            &fields,
            &known_types,
            &possible_types,
            &variables,
        );

        if let (Some(pointer), Some(fixture)) = (fixture_pointer, fixture) {
            let fixture: serde_json::Value = serde_json::from_str(fixture).unwrap();
            let mut keys = HashSet::new();
            selected_keys(selection_set, &mut keys);
            for fragment in fragments.values() {
                selected_keys(&fragment.selection_set, &mut keys);
            }
            assert_fixture_keys(fixture.pointer(pointer).unwrap(), &keys);
        }
    }
}

/// Nothing except the named guarded document can rewrite a Status field's options.
///
/// The pinned schema already refuses a *document* naming either, and this reads the whole
/// crate rather than the documents alone: the criterion is that no code path invokes
/// `updateProjectV2Field` with `singleSelectOptions`, and a source file is where a path
/// would have to be spelled. GitHub documents that input as overwriting a field's existing
/// options, so no addition is additive and a mistake destroys every item's status; a
/// status this board cannot represent is a refusal instead.
#[test]
fn only_the_guarded_source_path_writes_a_status_fields_option_set() {
    /// Everything the file says that is not a comment about what it does not do.
    fn code(text: &str, comment: &str) -> String {
        text.lines()
            .filter(|line| !line.trim_start().starts_with(comment))
            .collect::<Vec<_>>()
            .join("\n")
    }
    const FORBIDDEN: [&str; 3] = ["updateProjectV2(", "shortDescription", "readme"];
    for forbidden in FORBIDDEN {
        assert!(
            !code(include_str!("../src/lib.rs"), "//").contains(forbidden),
            "the source names {forbidden}, which this board is never written through"
        );
        assert!(
            !code(include_str!("fixtures/schema.graphql"), "#").contains(forbidden),
            "the pinned schema defines {forbidden}, which would let a document reach it"
        );
    }
    assert_eq!(
        code(include_str!("../src/lib.rs"), "//")
            .matches("updateProjectV2Field(input:$input)")
            .count(),
        1,
        "exactly the guarded mutation document may call updateProjectV2Field"
    );
}

/// The category list this source maps cannot silently lose a variant of the vocabulary.
///
/// `CATEGORIES` mirrors `StatusCategory`, and `category_position` is a wildcard-free
/// match over it — so a variant added to the shared vocabulary fails to compile there
/// until it is named, and this reconciliation fails until the list holds it too.
#[test]
fn every_status_category_this_source_can_be_handed_has_a_place_in_its_mapping() {
    use onetaskgraph_github_projects::{CATEGORIES, category_position};

    let mut filled = [false; CATEGORIES.len()];
    for category in CATEGORIES {
        let at = category_position(category);
        assert!(at < CATEGORIES.len(), "{category:?} sits past the list");
        assert!(
            !filled[at],
            "{category:?} shares a place with another category"
        );
        assert_eq!(CATEGORIES[at], category, "{category:?} is filed elsewhere");
        filled[at] = true;
    }
    assert!(
        filled.iter().all(|filled| *filled),
        "a place in the list is unfilled, so a category the vocabulary declares is missing"
    );
}

#[test]
fn the_category_list_is_reconciled_against_the_vocabulary_it_mirrors() {
    use onetaskgraph_github_projects::CATEGORIES;
    use onetaskgraph_plugin_api::StatusCategory;

    // The list checking itself proves nothing about the enum it restates: a variant added
    // to the shared vocabulary and given a place by `category_position` compiles with the
    // list one short, and every mapping indexed by that place then panics. `StatusCategory`'s
    // own derived schema is the second source — generated from the variants rather than
    // written beside them — so it grows the moment the vocabulary does, in its order.
    let schema = serde_json::to_value(schemars::schema_for!(StatusCategory))
        .expect("the derived schema serializes");
    let declared = schema["oneOf"]
        .as_array()
        .expect("a unit-variant enum schema lists its variants")
        .iter()
        .map(|variant| {
            variant["const"]
                .as_str()
                .expect("each variant is a string constant")
                .to_owned()
        })
        .collect::<Vec<_>>();
    let mirrored = CATEGORIES
        .iter()
        .map(|category| {
            serde_json::to_value(category)
                .expect("a category serializes")
                .as_str()
                .expect("a category serializes as a string")
                .to_owned()
        })
        .collect::<Vec<_>>();
    assert_eq!(
        declared, mirrored,
        "CATEGORIES must name every category the vocabulary declares, in the order it \
         declares them"
    );
}

#[test]
fn documents_are_all_inventoried_with_what_the_source_is_doing_when_it_sends_one() {
    // `graphql::DOCUMENTS` is what a rate-limit diagnostic reads to name the call that was
    // refused, and a document missing from it would be reported as "talking to GitHub"
    // with nothing saying so. Nothing about a set of `&str` constants makes that a
    // compile error, so this reads the module back and is the gate instead.
    let source = include_str!("../src/lib.rs");
    let module = source
        .split_once("pub mod graphql {")
        .expect("the production documents live in one module")
        .1
        .split_once("\n}\n")
        .expect("that module ends")
        .0;
    let declared: Vec<&str> = module
        .lines()
        .filter_map(|line| line.trim().strip_prefix("pub const "))
        .filter_map(|rest| rest.split_once(':'))
        .map(|(name, _)| name.trim())
        .filter(|name| *name != "DOCUMENTS")
        .collect();
    let inventory = onetaskgraph_github_projects::graphql::DOCUMENTS;
    // Counting alone would let a duplicated entry stand in for an omitted document, so
    // distinctness is asserted too. Every entry is a compiler-checked reference to one of
    // the constants declared above it, so `as many entries as constants` and `no two
    // entries alike` together mean each constant is inventoried exactly once.
    let documents: HashSet<&str> = inventory.iter().map(|(document, _)| *document).collect();
    assert_eq!(
        documents.len(),
        inventory.len(),
        "graphql::DOCUMENTS holds the same document twice, which hides one it omits"
    );
    assert_eq!(
        declared.len(),
        inventory.len(),
        "graphql::DOCUMENTS names {} documents and the module declares {declared:?}; add the \
         missing one to that list with what this source is doing when it sends it",
        inventory.len()
    );
    let described: HashSet<&str> = inventory.iter().map(|(_, doing)| *doing).collect();
    assert_eq!(
        described.len(),
        inventory.len(),
        "two documents are inventoried as the same activity, so a diagnostic naming it \
         cannot say which call was refused"
    );
    for (document, doing) in inventory {
        assert!(
            !doing.trim().is_empty(),
            "every document is inventoried with what sending it is doing"
        );
        query::parse_query::<String>(document).expect("every inventoried document parses");
    }
}

#[test]
fn the_rate_limit_vocabulary_and_published_limits_match_their_pinned_artifact() {
    // GitHub's refusal wordings and its published secondary limits are GitHub's contract,
    // not this source's, and this source restates both: the wordings are what
    // `Limiter::classify` matches a refusal on, and the limits are the windows this source
    // paces under, the per-minute one also what `MIN_MUTATION_INTERVAL_MS` is derived from. Restating an external contract
    // without a gate is how the restatement quietly stops being true, so
    // `fixtures/rate-limits.json` is the pin — recorded with its provenance in the README
    // beside it — and this reconciles the two **both ways**: a wording the source matches
    // on that nothing pinned it, and a pinned wording the source no longer matches on,
    // each fail here naming the entry.
    let pinned: serde_json::Value =
        serde_json::from_str(include_str!("fixtures/rate-limits.json")).expect("the pin parses");

    for (side, shipped) in [
        (
            "secondary",
            onetaskgraph_github_projects::SECONDARY_WORDINGS.as_slice(),
        ),
        (
            "primary",
            onetaskgraph_github_projects::PRIMARY_WORDINGS.as_slice(),
        ),
        (
            "conflict",
            onetaskgraph_github_projects::CONFLICT_WORDINGS.as_slice(),
        ),
    ] {
        let pinned_wordings: HashSet<&str> = pinned[side]["wordings"]
            .as_array()
            .unwrap_or_else(|| panic!("the pin records the {side} wordings"))
            .iter()
            .map(|wording| wording.as_str().expect("each pinned wording is a string"))
            .collect();
        let shipped_wordings: HashSet<&str> = shipped.iter().copied().collect();
        assert_eq!(
            shipped_wordings.len(),
            shipped.len(),
            "the {side} wordings list the same phrase twice, which hides one it omits"
        );
        for wording in &shipped_wordings {
            assert!(
                pinned_wordings.contains(wording),
                "this source matches a {side} refusal on {wording:?}, which is not in \
                 fixtures/rate-limits.json; pin it there with where it was read, or stop \
                 matching on it"
            );
        }
        for wording in &pinned_wordings {
            assert!(
                shipped_wordings.contains(wording),
                "fixtures/rate-limits.json pins the {side} wording {wording:?} and this \
                 source no longer matches on it; a refusal GitHub still sends that way \
                 would be reported as something it is not"
            );
        }
        for wording in &shipped_wordings {
            assert_eq!(
                *wording,
                wording.to_ascii_lowercase(),
                "`classify` lower-cases the response before matching, so an upper-case \
                 character in {wording:?} could never match"
            );
        }
    }

    assert_eq!(
        pinned["content_creation"]["per_minute"].as_u64(),
        Some(onetaskgraph_github_projects::CONTENT_CREATION_PER_MINUTE),
        "the shipped per-minute ceiling is not the one pinned from GitHub's documentation"
    );
    assert_eq!(
        pinned["content_creation"]["per_hour"].as_u64(),
        Some(onetaskgraph_github_projects::CONTENT_CREATION_PER_HOUR),
        "the shipped per-hour ceiling is not the one pinned from GitHub's documentation"
    );
    for (key, shipped) in [
        (
            "per_minute",
            onetaskgraph_github_projects::SECONDARY_POINTS_PER_MINUTE,
        ),
        (
            "per_mutation_request",
            onetaskgraph_github_projects::SECONDARY_POINTS_PER_MUTATION,
        ),
        (
            "per_query_request",
            onetaskgraph_github_projects::SECONDARY_POINTS_PER_QUERY,
        ),
    ] {
        assert_eq!(
            pinned["secondary_points"][key].as_u64(),
            Some(shipped),
            "the shipped secondary points {key} is not the one pinned from GitHub's \
             documentation"
        );
    }
    let pinned_points: HashSet<&str> = pinned["secondary_points"]
        .as_object()
        .expect("the pin records the secondary points")
        .keys()
        .map(String::as_str)
        .filter(|key| *key != "read")
        .collect();
    assert_eq!(
        pinned_points,
        HashSet::from(["per_minute", "per_mutation_request", "per_query_request"]),
        "fixtures/rate-limits.json pins a secondary points figure this source does not pace by"
    );
    // And the derivation itself, because the pin is only worth having if the value this
    // source actually paces at moves with it.
    assert_eq!(
        onetaskgraph_github_projects::MIN_MUTATION_INTERVAL_MS,
        60_000 / onetaskgraph_github_projects::CONTENT_CREATION_PER_MINUTE,
        "the shipped interval stopped being the fastest rate the pinned per-minute \
         ceiling allows"
    );
}

/// The priority levels this source maps, and the configuration naming them, cannot silently
/// lose a priority the vocabulary gains.
///
/// `PRIORITY_LEVELS` and `PriorityMappingConfig`'s members both restate `Priority` less its
/// `none`, which is no option of a board field; `level_position` is a wildcard-free match, so a
/// new priority fails to compile there, and this reconciles both lists against the enum's own
/// derived schema — generated from the variants rather than written beside them.
#[test]
fn the_priority_levels_and_their_configuration_are_reconciled_against_the_vocabulary() {
    use onetaskgraph_github_projects::{
        GitHubProjectsConfig, PRIORITY_LEVELS, PriorityMappingConfig, level_position,
    };
    use onetaskgraph_plugin_api::Priority;

    let spelled = |value: serde_json::Value| {
        value
            .as_str()
            .expect("a priority serializes as a string")
            .to_owned()
    };
    let schema = serde_json::to_value(schemars::schema_for!(Priority))
        .expect("the derived schema serializes");
    let declared = schema["oneOf"]
        .as_array()
        .expect("a unit-variant enum schema lists its variants")
        .iter()
        .map(|variant| spelled(variant["const"].clone()))
        .filter(|name| name != "none")
        .collect::<Vec<_>>();
    let mirrored = PRIORITY_LEVELS
        .iter()
        .map(|level| spelled(serde_json::to_value(level).expect("serializes")))
        .collect::<Vec<_>>();
    assert_eq!(
        declared, mirrored,
        "PRIORITY_LEVELS must name every priority but none, in the order the vocabulary does"
    );
    for (index, level) in PRIORITY_LEVELS.iter().enumerate() {
        assert_eq!(level_position(*level), Some(index), "{level}");
    }
    assert_eq!(level_position(Priority::None), None);

    let config = serde_json::to_value(schemars::schema_for!(PriorityMappingConfig))
        .expect("the configuration schema serializes");
    let mut members = config["properties"]
        .as_object()
        .expect("the mapping is an object of levels")
        .keys()
        .cloned()
        .collect::<Vec<_>>();
    members.sort();
    let mut levels = mirrored.clone();
    levels.sort();
    assert_eq!(
        members, levels,
        "priority_mapping must take exactly one member per level"
    );
    // And the whole configuration schema reaches it under the name a document writes.
    let whole = serde_json::to_value(schemars::schema_for!(GitHubProjectsConfig))
        .expect("the configuration schema serializes");
    assert!(whole["properties"]["priority_mapping"].is_object());
}

/// Each aliased field of `UPDATE_FIELDS`, in the order GitHub runs them: the key its answer
/// comes back under, the mutation it is, the variable carrying its input and the boolean that
/// includes it.
fn update_fields_slots(document: &str) -> Vec<(String, String, String, String)> {
    let document = query::parse_query::<String>(document).expect("a valid document");
    let query::Definition::Operation(query::OperationDefinition::Mutation(mutation)) =
        &document.definitions[0]
    else {
        panic!("UPDATE_FIELDS is a mutation");
    };
    let variable = |value: &query::Value<String>| match value {
        query::Value::Variable(name) => name.clone(),
        other => panic!("a slot is bound to a variable, not {other:?}"),
    };
    mutation
        .selection_set
        .items
        .iter()
        .map(|selection| {
            let query::Selection::Field(field) = selection else {
                panic!("UPDATE_FIELDS selects fields alone");
            };
            let input = field
                .arguments
                .iter()
                .find(|(name, _)| name == "input")
                .map(|(_, value)| variable(value))
                .expect("an input");
            let include = field
                .directives
                .iter()
                .find(|directive| directive.name == "include")
                .and_then(|directive| directive.arguments.first())
                .map(|(_, value)| variable(value))
                .expect("every slot is included by its own boolean");
            (
                field.alias.clone().unwrap_or_else(|| field.name.clone()),
                field.name.clone(),
                input,
                include,
            )
        })
        .collect()
}

/// `FIELD_WRITE_SLOTS` and `FIELD_CLEAR_SLOTS` are what the source and every loopback board
/// read `UPDATE_FIELDS`' aliases off, so they are held to the document itself, both ways and in
/// order: a slot added to one and not the other fails here rather than as a write whose answer
/// is read under the wrong key.
#[test]
fn the_field_slots_are_exactly_the_aliased_fields_of_update_fields() {
    use onetaskgraph_github_projects::{FIELD_CLEAR_SLOTS, FIELD_WRITE_SLOTS, graphql};
    let declared = FIELD_WRITE_SLOTS
        .iter()
        .map(|slot| (slot, "updateProjectV2ItemFieldValue"))
        .chain(
            FIELD_CLEAR_SLOTS
                .iter()
                .map(|slot| (slot, "clearProjectV2ItemFieldValue")),
        )
        .map(|(slot, mutation)| {
            (
                slot.alias.to_owned(),
                mutation.to_owned(),
                slot.variable.to_owned(),
                slot.include.to_owned(),
            )
        })
        .collect::<Vec<_>>();
    assert_eq!(update_fields_slots(graphql::UPDATE_FIELDS), declared);
    // And the comparison is one that can fail: the same document with two slots' includes
    // swapped is refused.
    let swapped = graphql::UPDATE_FIELDS
        .replacen("@include(if:$writeSecond)", "@include(if:$PLACEHOLDER)", 1)
        .replacen("@include(if:$writeThird)", "@include(if:$writeSecond)", 1)
        .replacen("@include(if:$PLACEHOLDER)", "@include(if:$writeThird)", 1);
    assert_ne!(update_fields_slots(&swapped), declared);
}

/// A `github-projects` configuration serializes to a document it reads back as itself, with an
/// empty `metadata_fields`, and an entry's empty `path`, left out — so a configuration written
/// before either existed and one written with them empty are the same document.
#[test]
fn a_configuration_round_trips_and_leaves_its_empty_lists_out() {
    use onetaskgraph_github_projects::GitHubProjectsConfig;
    use serde_json::{Value, json};
    let base = json!({"owner": "octo-org", "project_number": 7, "repository": "acme/work"});
    let read = |document: &Value| -> GitHubProjectsConfig {
        serde_json::from_value(document.clone())
            .unwrap_or_else(|error| panic!("{document} does not read: {error}"))
    };
    let written = |config: &GitHubProjectsConfig| serde_json::to_value(config).unwrap();
    let with = |entries: Value| {
        let mut document = base.clone();
        document["metadata_fields"] = entries;
        document
    };

    // Absent and empty read alike, and both write no key at all.
    for document in [base.clone(), with(json!([]))] {
        let config = read(&document);
        assert!(config.metadata_fields.is_empty(), "{document}");
        let serialized = written(&config);
        assert_eq!(serialized.get("metadata_fields"), None, "{serialized}");
        assert_eq!(read(&serialized), config, "{serialized}");
    }
    assert_eq!(read(&base), read(&with(json!([]))));

    // Populated: every entry kept in order; a path is written only when it has a step.
    let populated = read(&with(json!([
        {"field": "Host", "key": "orchestrator.follow-up", "path": ["host"]},
        {"field": "Team", "key": "team.name", "path": []},
        {"field": "Owner", "key": "team.owner"},
    ])));
    let serialized = written(&populated);
    assert_eq!(
        serialized["metadata_fields"],
        json!([
            {"field": "Host", "key": "orchestrator.follow-up", "path": ["host"]},
            {"field": "Team", "key": "team.name"},
            {"field": "Owner", "key": "team.owner"},
        ])
    );
    let again = read(&serialized);
    assert_eq!(again, populated);
    assert_eq!(
        written(&again),
        serialized,
        "a second round trip writes the same bytes"
    );
    assert_eq!(populated.metadata_fields[1].path, Vec::<String>::new());

    // Every other member survives the trip too, defaults included.
    let full = read(&json!({
        "owner": "octo-org", "project_number": 7, "repository": "acme/work",
        "token_env": "BOARD_TOKEN", "endpoint": "https://github.example/api/graphql",
        "status_mapping": {"todo": "Ready", "draft": null},
        "priority_mapping": {"urgent": "P0"},
        "pacing": {"min_mutation_interval_ms": 0, "retry_budget_ms": 0},
        "metadata_fields": [{"field": "Host", "key": "orchestrator.follow-up", "path": ["host"]}],
    }));
    assert_eq!(read(&written(&full)), full);
}

#[test]
fn every_batch_document_declares_and_sends_exactly_the_slots_its_constant_counts() {
    // The batch documents spell their slots out one by one, and the source fills and reads them
    // by the constants: each prefix's input variable, its include variable and its alias are
    // declared exactly that many times, numbered from nought, and no more.
    use onetaskgraph_github_projects::{DELETE_BATCH, MUTATION_BATCH, WRITE_BATCH, graphql};
    // Each document by name, the document, each kind's slot prefix and include prefix, and how
    // many slots its constant counts.
    type Batch<'a> = (&'a str, &'a str, &'a [(&'a str, &'a str)], usize);
    let batches: [Batch<'_>; 7] = [
        (
            "CREATE_ISSUES",
            graphql::CREATE_ISSUES,
            &[("create", "send")],
            MUTATION_BATCH,
        ),
        (
            "CLOSE_ISSUES",
            graphql::CLOSE_ISSUES,
            &[("close", "send")],
            MUTATION_BATCH,
        ),
        (
            "UPDATE_ISSUES",
            graphql::UPDATE_ISSUES,
            &[("update", "send")],
            MUTATION_BATCH,
        ),
        (
            "WRITE_FIELD_VALUES",
            graphql::WRITE_FIELD_VALUES,
            &[("field", "send")],
            WRITE_BATCH,
        ),
        (
            "ADD_BLOCKED_BYS",
            graphql::ADD_BLOCKED_BYS,
            &[("block", "send")],
            WRITE_BATCH,
        ),
        (
            "WRITE_FIELDS_AND_EDGES",
            graphql::WRITE_FIELDS_AND_EDGES,
            &[("field", "sendField"), ("block", "sendBlock")],
            WRITE_BATCH,
        ),
        (
            "DELETE_ISSUES",
            graphql::DELETE_ISSUES,
            &[("delete", "send")],
            DELETE_BATCH,
        ),
    ];
    for (name, document, kinds, slots) in batches {
        for (prefix, send) in kinds {
            let numbered = |pattern: &str| -> Vec<usize> {
                let mut found = Vec::new();
                let mut rest = document;
                while let Some(at) = rest.find(pattern) {
                    rest = &rest[at + pattern.len()..];
                    let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
                    if !digits.is_empty() && rest[digits.len()..].starts_with([':', ')']) {
                        found.push(digits.parse().unwrap());
                    }
                }
                found.sort_unstable();
                found
            };
            let expected: Vec<usize> = (0..slots).collect();
            assert_eq!(
                numbered(&format!("${prefix}")),
                expected
                    .iter()
                    .flat_map(|slot| [*slot, *slot])
                    .collect::<Vec<_>>(),
                "{name} declares and passes `${prefix}<n>` other than once each for {slots} slots"
            );
            assert_eq!(
                numbered(&format!("${send}")),
                expected
                    .iter()
                    .flat_map(|slot| [*slot, *slot])
                    .collect::<Vec<_>>(),
                "{name} declares and reads `${send}<n>` other than once each for {slots} slots"
            );
            assert_eq!(
                numbered(&format!(" {prefix}")),
                expected,
                "{name} aliases `{prefix}<n>` other than once each for {slots} slots"
            );
        }
    }
}

/// Every document this source sends holds to GitHub's complete published schema, not only to
/// the reduced subset above: the subset is written by the same hand as the documents, which is
/// how a field-setup input GitHub does not define passed the check above in 0.12.13.
#[test]
fn every_production_document_validates_against_githubs_complete_published_schema() {
    let refused = onetaskgraph_github_projects::graphql::DOCUMENTS
        .iter()
        .filter_map(|(document, doing)| {
            github_schema::validate_document(document)
                .err()
                .map(|errors| format!("{doing}: {errors:?}"))
        })
        .collect::<Vec<_>>();
    assert!(
        refused.is_empty(),
        "GitHub would refuse:\n{}",
        refused.join("\n")
    );
}

/// The field setup's two writes, with the variables it sends, are what GitHub accepts — and
/// the input 0.12.13 sent is refused with the message GitHub answered it with.
#[test]
fn the_field_setup_requests_validate_and_the_input_0_12_13_sent_is_refused() {
    use onetaskgraph_github_projects::graphql::{CREATE_FIELD, STATUS_OPTIONS_UPDATE};
    use serde_json::json;

    let options = json!([
        {"id": "opt-todo", "name": "Todo", "color": "GRAY", "description": ""},
        {"name": "Cancelled", "color": "GRAY", "description": ""},
    ]);
    github_schema::validate(
        STATUS_OPTIONS_UPDATE,
        &json!({"input": {"fieldId": "PVTSSF-status", "singleSelectOptions": options}}),
    )
    .expect("adding a Status option is a request GitHub runs");
    github_schema::validate(
        CREATE_FIELD,
        &json!({"input": {"projectId": "PVT-board", "dataType": "SINGLE_SELECT",
            "name": "Priority", "singleSelectOptions": [
                {"name": "Critical", "color": "GRAY", "description": ""},
                {"name": "Low", "color": "GRAY", "description": ""}]}}),
    )
    .expect("creating the Priority field is a request GitHub runs");
    github_schema::validate(
        CREATE_FIELD,
        &json!({"input": {"projectId": "PVT-board", "dataType": "TEXT", "name": "Origin"}}),
    )
    .expect("creating a metadata field is a request GitHub runs");

    assert_eq!(
        github_schema::validate(
            STATUS_OPTIONS_UPDATE,
            &json!({"input": {"projectId": "PVT-board", "fieldId": "PVTSSF-status",
                "singleSelectOptions": options}}),
        ),
        Err(vec![
            "Variable \"$input\" has invalid value: Expected value of type \
             \"UpdateProjectV2FieldInput\" not to include unknown field \"projectId\", found: { \
             fieldId: \"PVTSSF-status\", projectId: \"PVT-board\", singleSelectOptions: \
             [[Object], [Object]] }."
                .to_owned()
        ])
    );
}

/// Every validation rule of the GraphQL specification's §5, and the coercion of variables in
/// §6.1.2, each broken by one request that the doubles refuse, as GitHub refuses it: a body of
/// `errors` alone — no `data` — each error a `message` and, where the document has one, the
/// `locations` it stands at.
#[test]
fn the_schema_check_refuses_a_request_breaking_each_validation_rule() {
    use serde_json::{Value, json};

    // (the rule, the specification's section, the document, its variables, what is answered)
    let cases: &[(&str, &str, &str, Value, &[&str])] = &[
        (
            "document parses",
            "2",
            "query{viewer{login}",
            json!({}),
            &["Syntax Error: Expected Name, found <EOF>."],
        ),
        (
            "executable definitions",
            "5.1.1",
            "query{viewer{login}} type Extra{id:ID}",
            json!({}),
            &["The \"Extra\" definition is not executable."],
        ),
        (
            "operation name uniqueness",
            "5.2.1.1",
            "query a{viewer{login}} query a{viewer{name}}",
            json!({}),
            &["There can be only one operation named \"a\"."],
        ),
        (
            "lone anonymous operation",
            "5.2.2.1",
            "{viewer{login}} query b{viewer{name}}",
            json!({}),
            &["This anonymous operation must be the only defined operation."],
        ),
        // GitHub's schema defines no subscription root, so §5.2.3.1's single root field is
        // reached only as the operation type it cannot answer.
        (
            "operation type is defined",
            "5.2.3.1",
            "subscription{a:__typename b:__typename}",
            json!({}),
            &["The subscription operation is not supported by the schema."],
        ),
        (
            "field selections",
            "5.3.1",
            "query{viewer{loginName}}",
            json!({}),
            &["Cannot query field \"loginName\" on type \"User\". Did you mean \"login\"?"],
        ),
        (
            "field selections, introspection",
            "5.3.1",
            "query{__schema{queryType{nom}}}",
            json!({}),
            &["Cannot query field \"nom\" on type \"__Type\". Did you mean \"name\"?"],
        ),
        (
            "field selection merging, aliases",
            "5.3.2",
            "query{viewer{x:login x:name}}",
            json!({}),
            &[
                "Fields \"x\" conflict because \"login\" and \"name\" are different fields. Use different aliases on the fields to fetch both if this was intentional.",
            ],
        ),
        (
            "field selection merging, arguments",
            "5.3.2",
            "query{viewer{repositories(first:1){totalCount} repositories(first:2){totalCount}}}",
            json!({}),
            &[
                "Fields \"repositories\" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.",
            ],
        ),
        (
            "field selection merging, nested",
            "5.3.2",
            "query{viewer{r:repositories(first:1){nodes{a:name}} r:repositories(first:1){nodes{a:id}}}}",
            json!({}),
            &[
                "Fields \"r\" conflict because subfields \"nodes\" conflict because subfields \"a\" conflict because \"name\" and \"id\" are different fields. Use different aliases on the fields to fetch both if this was intentional.",
            ],
        ),
        (
            "field selection merging, exclusive fragments",
            "5.3.2",
            "query($id:ID!){node(id:$id){... on Issue{x:title} ... on PullRequest{x:number}}}",
            json!({"id": "I_1"}),
            &[
                "Fields \"x\" conflict because they return conflicting types \"String!\" and \"Int!\". Use different aliases on the fields to fetch both if this was intentional.",
            ],
        ),
        (
            "leaf field selections, scalar",
            "5.3.3",
            "query{viewer{login{name}}}",
            json!({}),
            &["Field \"login\" must not have a selection since type \"String!\" has no subfields."],
        ),
        (
            "leaf field selections, composite",
            "5.3.3",
            "query{viewer}",
            json!({}),
            &[
                "Field \"viewer\" of type \"User!\" must have a selection of subfields. Did you mean \"viewer { ... }\"?",
            ],
        ),
        (
            "argument names",
            "5.4.1",
            "query{viewer{login(first:1)}}",
            json!({}),
            &["Unknown argument \"first\" on field \"User.login\"."],
        ),
        (
            "argument uniqueness",
            "5.4.2",
            "query{node(id:\"A\",id:\"B\"){id}}",
            json!({}),
            &["There can be only one argument named \"id\"."],
        ),
        (
            "required arguments",
            "5.4.2.1",
            "query{node{id}}",
            json!({}),
            &["Argument \"Query.node(id:)\" of type \"ID!\" is required, but it was not provided."],
        ),
        (
            "fragment name uniqueness",
            "5.5.1.1",
            "query{viewer{...f}} fragment f on User{name} fragment f on User{login}",
            json!({}),
            &["There can be only one fragment named \"f\"."],
        ),
        (
            "fragment spread type existence",
            "5.5.1.2",
            "query($id:ID!){node(id:$id){... on Labelled{id}}}",
            json!({"id": "I_1"}),
            &[
                "Unknown type \"Labelled\". Did you mean \"Label\", \"LabelEdge\", \"Labelable\", or \"LabelOrder\"?",
            ],
        ),
        (
            "fragments on composite types",
            "5.5.1.3",
            "query{viewer{...f}} fragment f on String{__typename}",
            json!({}),
            &["Fragment \"f\" cannot condition on non composite type \"String\"."],
        ),
        (
            "fragments must be used",
            "5.5.1.4",
            "query{viewer{login}} fragment f on User{name}",
            json!({}),
            &["Fragment \"f\" is never used."],
        ),
        (
            "fragment spread target defined",
            "5.5.2.1",
            "query{viewer{...g}}",
            json!({}),
            &["Unknown fragment \"g\"."],
        ),
        (
            "fragment spreads must not form cycles",
            "5.5.2.2",
            "query{viewer{...a}} fragment a on User{login ...b} fragment b on User{...a}",
            json!({}),
            &["Cannot spread fragment \"a\" within itself via \"b\"."],
        ),
        (
            "fragment spread is possible",
            "5.5.2.3",
            "query{viewer{... on Issue{title}}}",
            json!({}),
            &[
                "Fragment cannot be spread here as objects of type \"User\" can never be of type \"Issue\".",
            ],
        ),
        (
            "values of correct type",
            "5.6.1",
            "query{viewer{repositories(first:3000000000){totalCount}}}",
            json!({}),
            &["Int cannot represent non 32-bit signed integer value: 3000000000"],
        ),
        (
            "input object field names",
            "5.6.2",
            "mutation{updateProjectV2Field(input:{fieldId:\"F\",projectId:\"P\"}){clientMutationId}}",
            json!({}),
            &[
                "Expected value of type \"UpdateProjectV2FieldInput\" not to include unknown field \"projectId\", found: { fieldId: \"F\", projectId: \"P\" }.",
            ],
        ),
        (
            "input object field uniqueness",
            "5.6.3",
            "mutation{updateProjectV2Field(input:{fieldId:\"F\",fieldId:\"G\"}){clientMutationId}}",
            json!({}),
            &["There can be only one input field named \"fieldId\"."],
        ),
        (
            "input object required fields",
            "5.6.4",
            "mutation{updateProjectV2Field(input:{}){clientMutationId}}",
            json!({}),
            &[
                "Expected value of type \"UpdateProjectV2FieldInput\" to include required field \"fieldId\", found: {  }.",
            ],
        ),
        (
            "directives are defined",
            "5.7.1",
            "query{viewer{login @nowhere}}",
            json!({}),
            &["Unknown directive \"@nowhere\"."],
        ),
        (
            "directives are in valid locations",
            "5.7.2",
            "query @include(if:true){viewer{login}}",
            json!({}),
            &["Directive \"@include\" may not be used on QUERY."],
        ),
        (
            "directives are unique per location",
            "5.7.3",
            "query{viewer{login @skip(if:false) @skip(if:false)}}",
            json!({}),
            &["The directive \"@skip\" can only be used once at this location."],
        ),
        (
            "directive required arguments",
            "5.4.2.1",
            "query{viewer{login @skip}}",
            json!({}),
            &["Argument \"@skip(if:)\" of type \"Boolean!\" is required, but it was not provided."],
        ),
        (
            "variable uniqueness",
            "5.8.1",
            "query($id:ID!,$id:ID!){node(id:$id){id}}",
            json!({"id": "I_1"}),
            &["There can be only one variable named \"$id\"."],
        ),
        (
            "variables are input types",
            "5.8.2",
            "query($u:User){viewer{login}}",
            json!({}),
            &[
                "Variable \"$u\" is never used.",
                "Variable \"$u\" cannot be non-input type \"User\".",
            ],
        ),
        (
            "all variable uses defined",
            "5.8.3",
            "query{node(id:$id){id}}",
            json!({}),
            &["Variable \"$id\" is not defined."],
        ),
        (
            "all variable uses defined, through a fragment",
            "5.8.3",
            "query{viewer{...f}} fragment f on User{repositories(first:$n){totalCount}}",
            json!({}),
            &["Variable \"$n\" is not defined."],
        ),
        (
            "all variables used",
            "5.8.4",
            "query($id:ID!,$unused:Int){node(id:$id){id}}",
            json!({"id": "I_1"}),
            &["Variable \"$unused\" is never used."],
        ),
        (
            "all variable usages are allowed, nullability",
            "5.8.5",
            "query($id:ID){node(id:$id){id}}",
            json!({"id": "I_1"}),
            &["Variable \"$id\" of type \"ID\" used in position expecting type \"ID!\"."],
        ),
        (
            "all variable usages are allowed, a null default is no licence",
            "5.8.5",
            "query($id:ID = null){node(id:$id){id}}",
            json!({}),
            &["Variable \"$id\" of type \"ID\" used in position expecting type \"ID!\"."],
        ),
        (
            "all variable usages are allowed, list",
            "5.8.5",
            "query($ids:[ID!]!){node(id:$ids){id}}",
            json!({"ids": ["I_1"]}),
            &["Variable \"$ids\" of type \"[ID!]!\" used in position expecting type \"ID!\"."],
        ),
        (
            "a default is a value of its type",
            "5.6.1",
            "query($first:Int = \"ten\"){viewer{repositories(first:$first){totalCount}}}",
            json!({}),
            &["Int cannot represent non-integer value: \"ten\""],
        ),
        (
            "a default is a constant",
            "2.10",
            "query($a:Int,$b:Int=$a){viewer{repositories(first:$b){totalCount}}}",
            json!({}),
            &["Syntax Error: Unexpected variable \"$a\" in constant value."],
        ),
        // §6.1.2, CoerceVariableValues, over each variable's JSON value.
        (
            "variables are an object",
            "7.1.1",
            "query{viewer{login}}",
            json!(["not", "an", "object"]),
            &["Variables must be provided as an Object where each property is a variable value."],
        ),
        (
            "a required variable is given",
            "6.1.2",
            "mutation($input:UpdateProjectV2FieldInput!){updateProjectV2Field(input:$input){clientMutationId}}",
            json!({}),
            &[
                "Variable \"$input\" has invalid value: Expected a value of non-null type \"UpdateProjectV2FieldInput!\" to be provided.",
            ],
        ),
        (
            "a variable coerces to its scalar",
            "6.1.2",
            "query($first:Int){viewer{repositories(first:$first){totalCount}}}",
            json!({"first": "ten"}),
            &[
                "Variable \"$first\" has invalid value: Int cannot represent non-integer value: \"ten\"",
            ],
        ),
        (
            "a variable coerces to its enum",
            "6.1.2",
            "mutation($input:CreateProjectV2FieldInput!){createProjectV2Field(input:$input){clientMutationId}}",
            json!({"input": {"projectId": "PVT_1", "dataType": "PRIORITY", "name": "Priority"}}),
            &[
                "Variable \"$input\" has invalid value at .dataType: Value \"PRIORITY\" does not exist in \"ProjectV2CustomFieldType\" enum.",
            ],
        ),
        (
            "a variable names no input field its type lacks",
            "6.1.2",
            "mutation($input:DeleteIssueInput!){deleteIssue(input:$input){clientMutationId}}",
            json!({"input": {"issueId": "I_1", "projectId": "PVT_1"}}),
            &[
                "Variable \"$input\" has invalid value: Expected value of type \"DeleteIssueInput\" not to include unknown field \"projectId\", found: { issueId: \"I_1\", projectId: \"PVT_1\" }.",
            ],
        ),
        (
            "a variable gives every required input field",
            "6.1.2",
            "mutation($input:CreateProjectV2FieldInput!){createProjectV2Field(input:$input){clientMutationId}}",
            json!({"input": {"projectId": "PVT_1", "dataType": "SINGLE_SELECT",
                "name": "Priority", "singleSelectOptions": [{"name": "High", "color": "GRAY"}]}}),
            &[
                "Variable \"$input\" has invalid value at .singleSelectOptions[0]: Expected value of type \"ProjectV2SingleSelectFieldOptionInput\" to include required field \"description\", found: { color: \"GRAY\", name: \"High\" }.",
            ],
        ),
    ];
    let mut wrong = Vec::new();
    for (rule, section, document, variables, expected) in cases {
        let answered = github_schema::refuse(&json!({"query": document, "variables": variables}));
        let Some(answered) = answered else {
            wrong.push(format!("§{section} {rule}: {document} was not refused"));
            continue;
        };
        let errors = answered["errors"].as_array().cloned().unwrap_or_default();
        let messages = errors
            .iter()
            .map(|error| error["message"].as_str().unwrap_or_default())
            .collect::<Vec<_>>();
        if messages != *expected {
            wrong.push(format!(
                "§{section} {rule}: {document} answered {messages:?}"
            ));
        }
        let shaped = answered.as_object().is_some_and(|body| body.len() == 1)
            && errors.iter().all(|error| {
                error["message"].is_string()
                    && error.as_object().is_some_and(|fields| {
                        fields
                            .keys()
                            .all(|key| key == "message" || key == "locations")
                    })
                    && error.get("locations").is_none_or(|locations| {
                        locations.as_array().is_some_and(|all| {
                            all.iter()
                                .all(|at| at["line"].is_u64() && at["column"].is_u64())
                        })
                    })
            });
        if !shaped {
            wrong.push(format!(
                "§{section} {rule}: {answered} is not GraphQL's error shape"
            ));
        }
    }
    assert!(wrong.is_empty(), "{}", wrong.join("\n"));

    // A refusal of a rule broken at a place in the document says where.
    assert_eq!(
        github_schema::refuse(&json!({"query": "query{\n  viewer{loginName}}"})),
        Some(
            json!({"errors": [{"message": "Cannot query field \"loginName\" on type \"User\". \
                Did you mean \"login\"?",
            "locations": [{"line": 2, "column": 10}]}]})
        )
    );
    // And what breaks none of them runs: a nullable variable with a non-null default is allowed
    // where a non-null one is expected, a list position takes a single value, and a named
    // operation is chosen by `operationName`.
    for (document, variables, operation) in [
        ("query($id:ID = \"I_1\"){node(id:$id){id}}", json!({}), None),
        (
            "query($ids:[ID!]!){nodes(ids:$ids){id}}",
            json!({"ids": "I_1"}),
            None,
        ),
        (
            "query a{viewer{login}} query b{viewer{name}}",
            json!({}),
            Some("b"),
        ),
    ] {
        assert_eq!(
            github_schema::refuse(
                &json!({"query": document, "variables": variables, "operationName": operation})
            ),
            None,
            "{document}"
        );
    }
    // A document of several operations names the one to run, or GitHub runs none of them.
    assert_eq!(
        github_schema::refuse(&json!({"query": "query a{viewer{login}} query b{viewer{id}}"})),
        Some(json!({"errors": [{
            "message": "Must provide operation name if query contains multiple operations."
        }]}))
    );
    assert_eq!(
        github_schema::refuse(&json!({"query": "query a{viewer{login}}", "operationName": "c"})),
        Some(json!({"errors": [{"message": "Unknown operation named \"c\"."}]}))
    );
    assert_eq!(
        github_schema::refuse(&json!({"query": "query a{viewer{login}}", "operationName": 1})),
        Some(json!({"errors": [{"message": "operationName must be a string, not 1"}]}))
    );
}

/// A malformed or adversarial request is refused, never answered by a crash or an exhausted
/// stack: bytes that are not GraphQL, nesting far past any real document's, a fragment cycle
/// two thousand spreads long, a wide selection, more tokens than it parses and deeply nested
/// variables.
#[test]
fn a_malformed_or_adversarial_request_is_refused_rather_than_crashing() {
    use serde_json::json;

    // Each of these takes the server seconds, which would be every other test's wait too.
    let server = github_schema::serve_privately();

    let refused = |document: &str, variables: serde_json::Value| {
        server
            .refuse(&json!({"query": document, "variables": variables}))
            .unwrap_or_else(|| panic!("{} was not refused", &document[..document.len().min(80)]))
    };
    refused("", json!({}));
    refused("\u{0}\u{1}garbage{{{", json!({}));
    refused("query{viewer{login}} }}}}", json!({}));
    let deep = |open: &str, close: &str, depth: usize| (open.repeat(depth), close.repeat(depth));
    let (open, close) = deep("viewer{", "}", 50_000);
    assert_eq!(
        refused(&format!("query{{{open}login{close}}}"), json!({})),
        json!({"errors": [{"message": "The request nests too deeply to validate."}]})
    );
    // A deep document that breaks no rule is validated, not refused for its depth.
    let (open, close) = deep("ofType{", "}", 190);
    assert_eq!(
        server
            .refuse(&json!({"query": format!("query{{__schema{{types{{{open}name{close}}}}}}}")})),
        None
    );
    let (open, close) = deep("[", "]", 50_000);
    assert_eq!(
        refused(
            &format!("query{{node(id:{open}1{close}){{id}}}}"),
            json!({}),
        ),
        json!({"errors": [{"message": "The request nests too deeply to validate."}]})
    );
    let (open, close) = deep("{a:", "}", 50_000);
    assert_eq!(
        refused(
            &format!("mutation{{updateProjectV2Field(input:{open}1{close}){{clientMutationId}}}}"),
            json!({}),
        ),
        json!({"errors": [{"message": "The request nests too deeply to validate."}]})
    );
    let chain = (0..2_000)
        .map(|at| format!("fragment f{at} on User{{...f{}}} ", at + 1))
        .collect::<String>();
    let cycle = refused(
        &format!("query{{viewer{{...f0}}}} {chain} fragment f2000 on User{{...f0}}"),
        json!({}),
    );
    assert!(
        cycle["errors"][0]["message"].as_str().is_some_and(
            |message| message.starts_with("Cannot spread fragment \"f0\" within itself via")
        ),
        "{cycle}"
    );
    let mut nested = json!("I_1");
    for _ in 0..300 {
        nested = json!([nested]);
    }
    let answered = refused("query($id:ID!){node(id:$id){id}}", json!({"id": nested}));
    assert_eq!(
        answered,
        json!({"errors": [{"message": "Variables nest deeper than 200 levels"}]})
    );
    // A wide document that breaks nothing is not refused for its width.
    let wide = (0..3_000)
        .map(|at| format!("a{at}:login "))
        .collect::<String>();
    assert_eq!(
        server.refuse(&json!({"query": format!("query{{viewer{{{wide}}}}}")})),
        None
    );
    // A document that breaks no rule but holds more tokens than the check parses is refused
    // unparsed, before any rule runs over it.
    let oversized = "login ".repeat(200_000);
    let answered = refused(&format!("query{{viewer{{{oversized}}}}}"), json!({}));
    assert!(
        answered["errors"][0]["message"]
            .as_str()
            .is_some_and(|message| message
                .starts_with("Syntax Error: Document contains more than 200000 tokens.")),
        "{answered}"
    );
}

/// The check's server stops when a client greets it with another protocol — as it does when its
/// files change or it has been idle — and the next request after it stops is still answered, by
/// a server started in its place, over connections this process held open to the one that
/// stopped. A protocol it does not speak is answered `stale`, never served. Driven against a
/// server of this test's own, through the same rendezvous every test process shares one by, so
/// stopping it holds up no other test.
///
/// Bounded: two server starts and a stop take about a second, so a replacement that hangs fails
/// this test within a minute rather than holding the run until its runner's timeout.
#[test]
fn a_stopped_schema_check_server_is_replaced_by_the_next_request() {
    within(
        std::time::Duration::from_secs(60),
        "replacing a stopped schema check server",
        a_stopped_server_is_replaced,
    );
}

/// Runs `body` on a thread of its own and fails, naming `what`, when it has not finished within
/// `limit`; a panic inside it fails the test as itself.
fn within(limit: std::time::Duration, what: &str, body: impl FnOnce() + Send + 'static) {
    use std::sync::mpsc::RecvTimeoutError;

    let (done, finished) = std::sync::mpsc::channel();
    let worker = std::thread::spawn(move || {
        body();
        let _ = done.send(());
    });
    match finished.recv_timeout(limit) {
        Ok(()) => worker.join().expect("the body finished"),
        Err(RecvTimeoutError::Disconnected) => {
            std::panic::resume_unwind(worker.join().expect_err("the body panicked"));
        }
        Err(RecvTimeoutError::Timeout) => panic!("{what} did not finish within {limit:?}"),
    }
}

fn a_stopped_server_is_replaced() {
    use serde_json::{Value, json};
    use std::io::{BufRead, BufReader, Write};

    let server = github_schema::serve_privately();
    let (port, pid) = server.server();
    let mut stream =
        std::net::TcpStream::connect(("127.0.0.1", port)).expect("the server accepts a client");
    stream
        .write_all(b"{\"hello\":0}\n")
        .expect("the hello is sent");
    let mut answer = String::new();
    BufReader::new(&stream)
        .read_line(&mut answer)
        .expect("the server answers the hello");
    let answer: Value = serde_json::from_str(&answer).expect("the answer is JSON");
    assert!(
        answer["stale"]
            .as_str()
            .is_some_and(|why| why.contains("protocol 1 was sent 0")),
        "{answer}"
    );
    let stopped = std::time::Instant::now();
    while std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
        assert!(
            stopped.elapsed() < std::time::Duration::from_secs(30),
            "the stale server stopped listening"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }

    // A document no other test sends, so this process has no answer to it kept.
    let answered = server.refuse(&json!({
        "query": "query StoppedServer{viewer{loginName}}",
    }));
    assert_eq!(
        answered,
        Some(json!({"errors": [{
            "message": "Cannot query field \"loginName\" on type \"User\". Did you mean \"login\"?",
            "locations": [{"line": 1, "column": 28}],
        }]}))
    );
    let (_, replaced_by) = server.server();
    assert_ne!(replaced_by, pid, "a new server answered");
}

/// The check's server stops by itself once no client has held a connection to it for its idle
/// period, and not while one does: a connection open across several such periods keeps it
/// serving, a connection opened inside one cancels the stop it was counting down to, and once
/// the last connection closes it stops and removes its rendezvous endpoint. The next request is
/// answered by a server started in its place. Driven against a server of this test's own, idling
/// for half a second rather than the shared server's ten.
#[test]
fn a_schema_check_server_stops_once_idle_and_never_while_a_client_is_connected() {
    within(
        std::time::Duration::from_secs(60),
        "watching a schema check server stop once idle",
        an_idle_server_stops,
    );
}

/// The check's server answers a client greeting it `stale`, naming what changed, once a file it
/// was built from has changed since it started — here the schema, a copy in the test's own
/// directory — and stops; the next request is answered, over the connection this process held
/// to the one that stopped, by a server built from the file as it now stands.
#[test]
fn a_schema_check_server_whose_schema_changed_is_replaced_by_the_next_request() {
    within(
        std::time::Duration::from_secs(60),
        "replacing a schema check server whose schema changed",
        a_changed_server_is_replaced,
    );
}

/// Connects to the server at `port` and greets it with the protocol it speaks, answering the
/// connection and the server's first line.
fn greeted(port: u16) -> (std::net::TcpStream, serde_json::Value) {
    use std::io::{BufRead, BufReader, Write};

    let mut stream =
        std::net::TcpStream::connect(("127.0.0.1", port)).expect("the server accepts a client");
    stream
        .write_all(b"{\"hello\":1}\n")
        .expect("the hello is sent");
    let mut answer = String::new();
    BufReader::new(&stream)
        .read_line(&mut answer)
        .expect("the server answers the hello");
    (
        stream,
        serde_json::from_str(&answer).expect("the answer is JSON"),
    )
}

/// Waits, without connecting, until the server that wrote `endpoint` has removed it — which it
/// does as it stops — and then that nothing listens on `port`. Connecting to poll would itself
/// be the connection that keeps an idle server running.
fn wait_until_stopped(endpoint: &std::path::Path, port: u16) {
    let asked = std::time::Instant::now();
    while endpoint.exists() {
        assert!(
            asked.elapsed() < std::time::Duration::from_secs(30),
            "the server stopped and removed {}",
            endpoint.display()
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    while std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
        assert!(
            asked.elapsed() < std::time::Duration::from_secs(30),
            "the stopped server stopped listening"
        );
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

/// The answer to a field `User` does not have, named `field`, so each request is one no other
/// test sends and no process has an answer to kept.
fn unknown_user_field(server: &github_schema::PrivateServer, field: &str) {
    use serde_json::json;

    let query = format!("query{{viewer{{{field}}}}}");
    let answered = server.refuse(&json!({ "query": query }));
    let message = answered
        .as_ref()
        .and_then(|answered| answered["errors"][0]["message"].as_str());
    assert_eq!(
        message,
        Some(format!("Cannot query field \"{field}\" on type \"User\".").as_str()),
        "{answered:?}"
    );
}

fn an_idle_server_stops() {
    use std::io::{BufRead, BufReader, Write};

    // Half of this is what a connection has to arrive in to cancel the stop below, across a
    // process boundary, so it is what a loaded host has to manage.
    let idle = std::time::Duration::from_secs(2);
    let server = github_schema::serve_privately_from_a_copy(idle);
    let endpoint = server
        .schema()
        .parent()
        .expect("the copy sits in the rendezvous directory")
        .join("endpoint.json");
    // `server()` holds this process's connection open, across four idle periods.
    let (port, pid) = server.server();
    std::thread::sleep(idle * 4);
    unknown_user_field(&server, "heldAcrossIdlePeriods");
    assert_eq!(
        server.server(),
        (port, pid),
        "a connection held open keeps it serving"
    );

    // Every connection closed starts the count; one opened inside it cancels it.
    server.disconnect();
    std::thread::sleep(idle / 2);
    let (mut stream, ready) = greeted(port);
    assert_eq!(ready["ready"], true, "{ready}");
    std::thread::sleep(idle * 4);
    stream
        .write_all(b"{\"query\":\"query{viewer{openedInsideTheCount}}\",\"operationName\":null,\"variables\":null,\"coerce\":false}\n")
        .expect("the request is sent");
    let mut answer = String::new();
    BufReader::new(&stream)
        .read_line(&mut answer)
        .expect("a server whose stop was cancelled answers");
    assert!(answer.contains("openedInsideTheCount"), "{answer}");
    assert!(
        endpoint.exists(),
        "a server serving a client keeps its endpoint"
    );

    // The last connection closed, it stops by itself.
    drop(stream);
    wait_until_stopped(&endpoint, port);

    unknown_user_field(&server, "askedAfterTheIdleStop");
    let (_, replaced_by) = server.server();
    assert_ne!(replaced_by, pid, "a new server answered");
}

fn a_changed_server_is_replaced() {
    let server = github_schema::serve_privately_from_a_copy(std::time::Duration::from_secs(30));
    let endpoint = server
        .schema()
        .parent()
        .expect("the copy sits in the rendezvous directory")
        .join("endpoint.json");
    let (port, pid) = server.server();
    unknown_user_field(&server, "beforeTheSchemaChanged");

    // A comment changes the file and not the schema it describes.
    let mut schema = std::fs::read(server.schema()).expect("the copy is read");
    schema.extend_from_slice(b"\n# changed after the server started\n");
    std::fs::write(server.schema(), schema).expect("the copy is changed");

    let (_, stale) = greeted(port);
    assert!(
        stale["stale"]
            .as_str()
            .is_some_and(|why| why.contains(&server.schema().display().to_string())
                && why.ends_with("changed since it started")),
        "{stale}"
    );
    wait_until_stopped(&endpoint, port);

    unknown_user_field(&server, "afterTheSchemaChanged");
    let (_, replaced_by) = server.server();
    assert_ne!(replaced_by, pid, "a new server answered");
}

/// A request line that is not the protocol's shape — not an object, a query that is not a
/// string, an `operationName` that is neither a string nor null, a `coerce` missing or not a
/// boolean — is answered `internal`, naming what is wrong, rather than read with defaults: a
/// missing `coerce` read as false would skip the variables' coercion silently. The server goes on
/// answering a well-formed request on the same connection.
#[test]
fn a_request_line_not_in_the_protocols_shape_is_answered_internal() {
    use serde_json::{Value, json};
    use std::io::{BufRead, BufReader, Write};

    let server = github_schema::serve_privately();
    let (port, _) = server.server();
    let mut stream =
        std::net::TcpStream::connect(("127.0.0.1", port)).expect("the server accepts a client");
    stream
        .set_read_timeout(Some(std::time::Duration::from_secs(60)))
        .expect("a read timeout");
    let mut reader = BufReader::new(stream.try_clone().expect("a second handle"));
    let mut exchange = |line: &str| -> Value {
        stream
            .write_all(format!("{line}\n").as_bytes())
            .expect("the line is sent");
        let mut answer = String::new();
        reader.read_line(&mut answer).expect("the server answers");
        serde_json::from_str(&answer).expect("the answer is JSON")
    };
    assert_eq!(exchange(r#"{"hello":1}"#)["ready"], json!(true));

    let valid =
        r#""query":"query($id:ID!){node(id:$id){id}}","operationName":null,"variables":{"id":5.5}"#;
    for (line, named) in [
        ("null".to_owned(), "a request is a JSON object"),
        ("[1]".to_owned(), "a request is a JSON object"),
        (
            r#"{"query":5,"operationName":null,"variables":{},"coerce":true}"#.to_owned(),
            "a request's query is a string",
        ),
        (
            r#"{"query":"query{viewer{login}}","operationName":3,"variables":{},"coerce":true}"#
                .to_owned(),
            "a request's operationName is a string or null",
        ),
        (
            format!("{{{valid}}}"),
            "a request's coerce is true or false",
        ),
        (
            format!(r#"{{{valid},"coerce":"yes"}}"#),
            "a request's coerce is true or false",
        ),
    ] {
        let answer = exchange(&line);
        assert!(
            answer["internal"]
                .as_str()
                .is_some_and(|internal| internal.contains(named)),
            "{line} was answered {answer}"
        );
        assert!(
            answer.get("errors").is_none(),
            "{line} was answered {answer}"
        );
    }

    // The same request, whole, has its variables coerced: an `ID` is a string or an integer.
    let answer = exchange(&format!(r#"{{{valid},"coerce":true}}"#));
    assert!(
        answer["errors"][0]["message"]
            .as_str()
            .is_some_and(|message| message.contains("$id")),
        "{answer}"
    );
}

/// The schema check stops, rather than answering requests, against a schema breaking any
/// type-system rule but the one GitHub's published file breaks — so a copy that is not the
/// schema GitHub serves cannot pass for it — and starts against one breaking that rule alone.
#[test]
fn the_schema_check_refuses_a_schema_breaking_any_rule_but_the_tolerated_one() {
    use serde_json::{Value, json};

    let first_answer = |sdl: &str| -> Value {
        let file = tempfile::NamedTempFile::new().expect("a scratch schema file");
        std::fs::write(file.path(), sdl).expect("the scratch schema is written");
        let output = std::process::Command::new("bun")
            .arg(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/tests/github_schema/validate.mjs"
            ))
            .arg(file.path())
            .env("BUN_RUNTIME_TRANSPILER_CACHE_PATH", "0")
            // Where the doubles' own check unpacks graphql-js, so this run writes nothing
            // inside the crate either.
            .env(
                "GITHUB_SCHEMA_MODULES",
                concat!(
                    env!("CARGO_MANIFEST_DIR"),
                    "/../../target/github-schema/node_modules"
                ),
            )
            .stdin(std::process::Stdio::null())
            .output()
            .expect("bun runs the schema check");
        let stdout = String::from_utf8_lossy(&output.stdout);
        serde_json::from_str(stdout.lines().next().unwrap_or_default())
            .unwrap_or_else(|_| panic!("the schema check answered {stdout:?}"))
    };
    let tolerated = "interface Node { id: ID! } \
                     type Card implements Node { id: ID! @deprecated(reason: \"gone\") } \
                     type Query { node: Node card: Card }";
    assert_eq!(first_answer(tolerated)["ready"], json!(true));

    let invalid = first_answer("type Empty type Query { empty: Empty }");
    assert!(
        invalid["internal"]
            .as_str()
            .is_some_and(|message| message.contains("is invalid")
                && message.contains("Type Empty must define one or more fields.")),
        "{invalid}"
    );
}

/// The check refuses a command line in neither shape its usage names, and an idle period that
/// is not a whole number of milliseconds a timer holds, answering `internal` and exiting
/// non-zero before it builds anything or serves — never read as the standard-input mode, nor an
/// idle period silently replaced by its default.
#[test]
fn the_schema_check_refuses_a_malformed_command_line_or_idle_period() {
    use serde_json::Value;

    let schema = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/fixtures/github-schema.docs.graphql"
    );
    let scratch = tempfile::tempdir().expect("a scratch directory");
    let directory = scratch.path().to_str().expect("a UTF-8 scratch path");
    let run = |args: &[&str], idle: Option<&str>| -> (bool, Value) {
        let mut command = std::process::Command::new("bun");
        command
            .arg(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/tests/github_schema/validate.mjs"
            ))
            .args(args)
            .env("BUN_RUNTIME_TRANSPILER_CACHE_PATH", "0")
            .env(
                "GITHUB_SCHEMA_MODULES",
                concat!(
                    env!("CARGO_MANIFEST_DIR"),
                    "/../../target/github-schema/node_modules"
                ),
            )
            .env_remove("GITHUB_SCHEMA_IDLE_MS")
            .stdin(std::process::Stdio::null());
        if let Some(idle) = idle {
            command.env("GITHUB_SCHEMA_IDLE_MS", idle);
        }
        let output = command.output().expect("bun runs the schema check");
        let stdout = String::from_utf8_lossy(&output.stdout);
        (
            output.status.success(),
            serde_json::from_str(stdout.lines().next().unwrap_or_default())
                .unwrap_or_else(|_| panic!("the schema check answered {stdout:?}")),
        )
    };
    let refused = |args: &[&str], idle: Option<&str>, naming: &str| {
        let (succeeded, answer) = run(args, idle);
        assert!(
            !succeeded,
            "{args:?} with idle {idle:?} exited zero: {answer}"
        );
        assert!(
            answer["internal"]
                .as_str()
                .is_some_and(|message| message.contains(naming)),
            "{args:?} with idle {idle:?} answered {answer}, not naming {naming:?}"
        );
    };

    for args in [
        &[][..],
        &[schema, "--server", directory],
        &[schema, "--serve"],
        &[schema, "--serve", ""],
        &[schema, "--serve", directory, "extra"],
        &["", "--serve", directory],
    ] {
        refused(
            args,
            None,
            "usage: bun validate.mjs <schema.graphql> [--serve <directory>]",
        );
    }
    for idle in ["", "0", "-5", "1.5", "Infinity", "2147483648", "ten"] {
        refused(
            &[schema, "--serve", directory],
            Some(idle),
            "GITHUB_SCHEMA_IDLE_MS is",
        );
    }
    // Both shapes, with an idle period in range, still start.
    let (succeeded, ready) = run(&[schema], Some("2147483647"));
    assert!(succeeded && ready["ready"] == true, "{ready}");
}

/// The check writes nothing inside the crate it tests: graphql-js is unpacked, and the shared
/// server records where it listens, under the workspace's `target`. A release records the digest
/// of each crate's directory when it builds and refuses to publish one that has moved since, and
/// the release journeys run beside these tests in one checkout, so a file written into this
/// crate's directory by a test run refused the release journeys' publication of this crate.
#[test]
fn the_schema_check_writes_nothing_inside_the_crate_it_tests() {
    assert_eq!(
        github_schema::validate("query { viewer { login } }", &serde_json::json!({})),
        Ok(())
    );
    let (here, modules, rendezvous) = github_schema::locations();
    let target = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../target")
        .canonicalize()
        .expect("the workspace's target exists once a test has been built");
    for written in [&modules, &rendezvous] {
        let written = written
            .canonicalize()
            .unwrap_or_else(|error| panic!("the check wrote {} ({error})", written.display()));
        assert!(
            written.starts_with(&target),
            "{} is not under {}",
            written.display(),
            target.display()
        );
    }
    assert!(
        modules
            .join("graphql")
            .join(".onetaskgraph-integrity")
            .is_file(),
        "graphql-js is unpacked under {}",
        modules.display()
    );
    assert!(
        rendezvous.join("endpoint.json").is_file(),
        "the shared server records its endpoint"
    );
    let mut entries: Vec<String> = std::fs::read_dir(&here)
        .expect("the check's directory is readable")
        .map(|entry| {
            entry
                .expect("a directory entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .collect();
    entries.sort();
    assert_eq!(
        entries,
        ["graphql-17.0.2.tgz", "mod.rs", "validate.mjs"],
        "{} holds only its committed files; a `node_modules` left there by an earlier \
         version of this check can be deleted",
        here.display()
    );
}

/// graphql-js is npm's own published tarball, and a copy of it that does not hash to the
/// integrity npm records is refused before anything is unpacked or imported from it — so the
/// validation every GitHub double runs cannot quietly become some other code. The check is run
/// from a scratch directory holding `validate.mjs` beside a tarball one byte off npm's.
#[test]
fn the_schema_check_refuses_a_graphql_tarball_npm_did_not_publish() {
    let tests = concat!(env!("CARGO_MANIFEST_DIR"), "/tests");
    let scratch = tempfile::tempdir().expect("a scratch directory");
    std::fs::copy(
        format!("{tests}/github_schema/validate.mjs"),
        scratch.path().join("validate.mjs"),
    )
    .expect("the schema check is copied");
    let mut tarball = std::fs::read(format!("{tests}/github_schema/graphql-17.0.2.tgz"))
        .expect("the pinned graphql-js tarball is readable");
    let last = tarball.len() - 1;
    tarball[last] ^= 0xff;
    std::fs::write(scratch.path().join("graphql-17.0.2.tgz"), tarball)
        .expect("the altered tarball is written");

    let output = std::process::Command::new("bun")
        .arg(scratch.path().join("validate.mjs"))
        .arg(format!("{tests}/fixtures/github-schema.docs.graphql"))
        .env("BUN_RUNTIME_TRANSPILER_CACHE_PATH", "0")
        .stdin(std::process::Stdio::null())
        .output()
        .expect("bun runs the schema check");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let answer: serde_json::Value = serde_json::from_str(stdout.lines().next().unwrap_or_default())
        .unwrap_or_else(|_| panic!("the schema check answered {stdout:?}"));
    assert!(!output.status.success(), "{answer}");
    assert!(
        answer["internal"].as_str().is_some_and(|message| {
            message.contains("graphql-17.0.2.tgz has integrity sha512-")
                && message.contains("not the sha512-FRWbddMx")
        }),
        "{answer}"
    );
    assert!(
        !scratch.path().join("node_modules").exists(),
        "nothing is unpacked from a tarball npm did not publish"
    );
}

/// A copy of graphql-js already unpacked beside the check that is not the pinned tarball's —
/// one from another pin, its marker naming another integrity, and one whose marker names the
/// pin but whose code was changed after it was unpacked — is replaced by the pinned tarball's
/// before anything is imported, so the validation runs only the code npm published.
#[test]
fn the_schema_check_replaces_a_graphql_copy_that_is_not_the_pinned_tarballs() {
    let tests = concat!(env!("CARGO_MANIFEST_DIR"), "/tests");
    for marker in [
        "sha512-another",
        "sha512-FRWbddMxfkjiB7z+aQDWIR+E34xo9I8c9mtK2RPv8PmMzKRvrdsreHL/Ui/TmwHJfhHChEtsFPyMHKI+xuarQQ==",
    ] {
        let scratch = tempfile::tempdir().expect("a scratch directory");
        for file in ["validate.mjs", "graphql-17.0.2.tgz"] {
            std::fs::copy(
                format!("{tests}/github_schema/{file}"),
                scratch.path().join(file),
            )
            .expect("the schema check is copied");
        }
        let stale = scratch.path().join("node_modules/graphql");
        std::fs::create_dir_all(&stale).expect("a stale copy's directory");
        std::fs::write(stale.join(".onetaskgraph-integrity"), marker).expect("its marker");
        std::fs::write(
            stale.join("index.mjs"),
            "throw new Error('the stale copy was imported');\n",
        )
        .expect("its code");

        let output = std::process::Command::new("bun")
            .arg(scratch.path().join("validate.mjs"))
            .arg(format!("{tests}/fixtures/github-schema.docs.graphql"))
            .env("BUN_RUNTIME_TRANSPILER_CACHE_PATH", "0")
            .stdin(std::process::Stdio::null())
            .output()
            .expect("bun runs the schema check");
        let stdout = String::from_utf8_lossy(&output.stdout);
        let answer: serde_json::Value =
            serde_json::from_str(stdout.lines().next().unwrap_or_default())
                .unwrap_or_else(|_| panic!("the schema check answered {stdout:?}"));
        assert_eq!(
            answer["ready"],
            serde_json::json!(true),
            "{marker}: {answer}"
        );
        assert!(output.status.success(), "{marker}: {answer}");
        assert!(
            std::fs::read_to_string(stale.join(".onetaskgraph-integrity"))
                .is_ok_and(|marker| marker.starts_with("sha512-FRWbddMx")),
            "{marker}: the stale copy is replaced by the pinned one"
        );
        assert!(
            std::fs::read_to_string(stale.join("index.mjs"))
                .is_ok_and(|code| !code.contains("the stale copy was imported")),
            "{marker}: the stale copy's code is gone"
        );
    }
}