oakum 0.12.1

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

mod env;
#[cfg(test)]
mod fake;
mod op;
mod reach;
mod reply;

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Mutex, OnceLock};

use cap_std::fs::Dir;

use super::CliError;
pub(super) use op::Op;
use op::{Answer, Contact, Direction, OpShape, SKIP_CHECKS_ATOM};
use reply::split_nul_paths;
pub(super) use reply::Reply;

/// How an accessor decides whether stdout carries an answer. The two disagree,
/// and the guard has to ask the one doing the reading: `text` and
/// `optional_text` trim, so a lone `\x0B` reaches the caller as `""`, while
/// `paths` keeps every non-empty NUL record byte-for-byte, because a file named
/// `" "` is a filename and not silence.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Reads {
    Text,
    Paths,
}

/// The trace2 channels, whose destination git config can set even when the
/// environment does not.
const TRACE2: [&str; 3] = ["GIT_TRACE2", "GIT_TRACE2_EVENT", "GIT_TRACE2_PERF"];

/// Whether a trace setting sends its output somewhere other than our stderr.
/// Measured on git 2.55: `1`, `2`, and `true` all print to stderr, an
/// unrecognised value warns and then prints to stderr, and only an absolute
/// path is written to a file. Anything that is not a path is dropped, so a
/// caller tracing to a file — `tests/it/reachable_tags.rs` counts children that
/// way — keeps it.
fn traces_to_a_file(value: &std::ffi::OsStr) -> bool {
    Path::new(value).is_absolute()
}

/// Drops inherited trace settings that would land on our stderr, where every
/// rule above would read them as a diagnostic: with `GIT_TRACE=1` exported a
/// healthy repository reports `unverified`, and `GIT_TRACE_PACKET=1` writes
/// 2704 bytes during an `ls-remote` that legitimately found no tags.
///
/// Matched by prefix rather than against a list. Git ships more than fifteen of
/// these and adds more; a list is a thing to be caught out by, one variable at
/// a time.
pub(super) fn untrace(command: &mut Command) {
    untrace_from(command, std::env::vars_os());
}

/// Split from [`untrace`] so a test can state an environment instead of
/// mutating the process's own: `cargo test` runs tests as threads of one
/// process, and a test that sets `GIT_TRACE` reaches every git child any other
/// test spawns concurrently.
fn untrace_from(
    command: &mut Command,
    env: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
) {
    let mut keeps_a_file = [false; TRACE2.len()];
    for (name, value) in env {
        let Some(name) = name.to_str() else { continue };
        if !name.starts_with("GIT_TRACE") {
            continue;
        }
        let to_a_file = traces_to_a_file(&value);
        if let Some(at) = TRACE2.iter().position(|trace2| *trace2 == name) {
            keeps_a_file[at] = to_a_file;
        }
        if !to_a_file {
            command.env_remove(name);
        }
    }
    // Trace2 also takes its destination from git config, which no edit to the
    // environment reaches and which `-c` is too late to change: trace2
    // initialises before the option is parsed. Setting the variable off does
    // reach it. Measured with `trace2.normalTarget=2` in global config: a
    // `status` writes 585 bytes to stderr, removing the variable leaves it at
    // 585, `-c trace2.normalTarget=0` raises it to 610 by tracing the option
    // itself, and setting the variable to 0 takes it to nothing.
    //
    // Read from `env` rather than the process, so this stays a function of its
    // argument: consulting both let an exported `GIT_TRACE2_EVENT` decide the
    // answer for an environment that never mentioned it.
    for (at, name) in TRACE2.iter().enumerate() {
        if !keeps_a_file[at] {
            command.env(name, "0");
        }
    }
}

/// Stderr that says git could not read part of what it was walking, as against
/// the noise it makes while answering completely.
///
/// [`op::Spec::whole`] is fail-closed on a short listing and open on a whole one,
/// because the two are measurably different here. An unreadable
/// `.git/info/exclude` warns twice and lists exactly what a readable one does;
/// refusing on that turns an unrelated permission bit into a red gate, with a
/// message that says part of the tree went unread when none of it did.
///
/// One of the set's forms is reachable and the set holds four, matched without
/// case. In git 2.55.0's `dir.c` the only diagnostic that shortens the walk is
/// `warning_errno(_("could not open directory '%s'"))` at line 2587; its
/// siblings there report sparse-checkout and pattern-file trouble and leave the
/// listing whole. The rest are written elsewhere: `cannot opendir` and
/// `cannot lstat` by other commands — fatally by `blame`, `clean`, `entry.c`
/// and `setup.c`, non-fatally by `ls-files` and `mailsplit` — and `opendir(`
/// by the fsmonitor daemon. Nothing spawns those here, and the only operation
/// this matcher judges runs `status`.
///
/// `status` shortens its listing one further way, which no spelling catches.
/// `diff-lib.c` drops an index entry it cannot `lstat` through `perror`, which
/// writes a bare `<path>: <strerror>`. Measured with the parent directory at
/// mode 444, where `readdir` succeeds and the `lstat` of its children does
/// not: exit 0, and the modified file beneath it reads as unmodified.
/// `permission denied` as a substring would also catch the benign
/// `.git/info/exclude` warning, so the rule is on the line's shape: no git
/// message prefix ([`GIT_PREFIXES`]) and a system error at the end
/// ([`LSTAT_ERRORS`]). A prefix alone is not enough: a clean filter or a
/// wrapped warning writes unprefixed lines of its own beside a whole listing.
/// Accepted both ways: a filter printing exactly `<path>: <error>` is refused,
/// and a tracked path holding `": "` slips past.
///
/// The set is kept because a translated or re-spelled message is the failure
/// mode that matters. What holds it honest is
/// `a_partial_worktree_listing_is_not_read_as_a_whole_one`, which seals a real
/// directory and runs the installed git: a git that words this differently
/// turns that test red rather than opening the guard quietly.
///
/// Unmatched stderr is passed over, so a form nobody has seen costs the
/// silence that was already there rather than a false refusal on the command
/// this repository gates with.
fn hides_part_of_the_tree(said: &str) -> bool {
    let lower = said.to_ascii_lowercase();
    [
        "could not open directory",
        "cannot opendir",
        "opendir(",
        "cannot lstat",
    ]
    .iter()
    .any(|form| lower.contains(form))
        || said.lines().map(str::trim).any(|line| {
            !GIT_PREFIXES.iter().any(|prefix| line.starts_with(prefix))
                && LSTAT_ERRORS.iter().any(|error| {
                    line.strip_suffix(error)
                        .and_then(|head| head.strip_suffix(": "))
                        .is_some_and(|path| !path.is_empty() && !path.contains(": "))
                })
        })
}

/// Every message family git 2.55 writes (`strings` on the binary). Children
/// run under `LC_ALL=C`, so the prefixes arrive in this spelling.
const GIT_PREFIXES: [&str; 6] = ["BUG:", "error:", "fatal:", "hint:", "note:", "warning:"];

/// What `strerror` says, in the C locale, for the ways an `lstat` of a listed
/// path fails and `diff-lib.c` reports it. A missing file or directory
/// (`ENOENT`, `ENOTDIR`) reads as a deletion there, not an error, so neither
/// is listed: a filter's `cat: x: No such file or directory` is not git's.
const LSTAT_ERRORS: [&str; 7] = [
    "Permission denied",
    "Input/output error",
    "Too many levels of symbolic links",
    "File name too long",
    "Operation not permitted",
    "Stale file handle",
    "Stale NFS file handle",
];

/// Why git cannot load one reftable stack, read by path as git reads it: a
/// directory it may search but not list is one git still reads, and a table
/// must be a regular file starting with reftable's `REFT` magic.
fn unreadable_stack(stack: &Path) -> Option<String> {
    let list = stack.join("tables.list");
    let mut names = String::new();
    if let Err(why) = open_regular(&list).and_then(|mut file| {
        std::io::Read::read_to_string(&mut file, &mut names)
            .map_err(|err| format!("`{}` could not be read: {err}", list.display()))
    }) {
        return Some(why);
    }
    names
        .lines()
        .filter(|name| !name.is_empty())
        .find_map(|name| unreadable_table(&stack.join(name)))
}

fn unreadable_table(table: &Path) -> Option<String> {
    let mut file = match open_regular(table) {
        Ok(file) => file,
        Err(why) => return Some(why),
    };
    let mut magic = [0_u8; 4];
    match std::io::Read::read_exact(&mut file, &mut magic) {
        Ok(()) if &magic == b"REFT" => None,
        Ok(()) => Some(format!("`{}` is not a reftable table", table.display())),
        Err(err) => Some(format!("`{}` could not be read: {err}", table.display())),
    }
}

/// Non-blocking, so a FIFO in the stack cannot stall the look.
fn open_regular(path: &Path) -> Result<std::fs::File, String> {
    let shown = path.display();
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        options.custom_flags(libc::O_NONBLOCK);
    }
    let not_regular = || format!("`{shown}` is not a regular file");
    // Windows refuses to open a directory at all, where unix opens it.
    let file = options.open(path).map_err(|err| {
        if std::fs::metadata(path).is_ok_and(|meta| !meta.is_file()) {
            not_regular()
        } else {
            format!("`{shown}` could not be opened: {err}")
        }
    })?;
    if !file.metadata().is_ok_and(|meta| meta.is_file()) {
        return Err(not_regular());
    }
    Ok(file)
}

/// `refs verify` walks only the ref store, so components `refs` then `tags`
/// mark a tag directory wherever the git dir lives. Doubt fails toward
/// unverified: a quote not closed by `': ` (a path holding a newline), or a git dir
/// kept under a folder `refs/tags`.
fn names_a_tag_directory(line: &str) -> bool {
    let Some((quoted, _)) = line
        .split_once('\'')
        .and_then(|(_, rest)| rest.rsplit_once("': "))
    else {
        return true;
    };
    let parts: Vec<&str> = quoted.split(['/', '\\']).collect();
    parts.windows(2).any(|pair| pair == ["refs", "tags"])
}

/// The diagnostic a ref listing writes when git skipped a ref it could not
/// read, garbage or unreadable alike, and listed the rest at exit 0.
fn skips_a_ref(said: &str) -> bool {
    said.to_ascii_lowercase().contains("ignoring broken ref")
}

/// From [`Op::Promisors`]' `-z` output: `extensions.partialclone` set, or a
/// `promisor` git reads as true. A key with no value prints without its
/// newline and is true; git's booleans ignore case, and any nonzero integer
/// is true.
fn names_a_promisor(stdout: &str) -> bool {
    stdout
        .split('\0')
        .map(|entry| entry.trim_start_matches('\n'))
        .filter(|entry| !entry.is_empty())
        .any(|entry| match entry.split_once('\n') {
            None | Some(("extensions.partialclone", _)) => true,
            Some((_, value)) => {
                let value = value.to_ascii_lowercase();
                matches!(value.as_str(), "true" | "yes" | "on")
                    || git_integer(&value).unwrap_or(0) != 0
            }
        })
}

/// A config integer as git reads one: C's base-0 prefixes and a `k`, `m` or
/// `g` unit.
fn git_integer(value: &str) -> Option<i64> {
    let (digits, unit) = match value.char_indices().last()? {
        (at, 'k') => (&value[..at], 1 << 10),
        (at, 'm') => (&value[..at], 1 << 20),
        (at, 'g') => (&value[..at], 1 << 30),
        _ => (value, 1),
    };
    let (negative, digits) = match digits.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, digits.strip_prefix('+').unwrap_or(digits)),
    };
    let number = if let Some(hex) = digits.strip_prefix("0x") {
        i64::from_str_radix(hex, 16).ok()?
    } else if digits.len() > 1 && digits.starts_with('0') {
        i64::from_str_radix(&digits[1..], 8).ok()?
    } else {
        digits.parse().ok()?
    };
    if negative { -number } else { number }.checked_mul(unit)
}

/// The first of [`Op::FollowedBlob`]'s replies and what follows it; `None`
/// for one framed any other way. A `missing` line echoes the query, whose
/// path may hold spaces, so it is read from the end. Every other kind carries
/// `<size>` bytes and a newline.
fn parse_followed(stdout: &[u8]) -> Option<(Followed, &[u8])> {
    let end = stdout.iter().position(|byte| *byte == b'\n')?;
    let header = std::str::from_utf8(&stdout[..end]).ok()?;
    if header.ends_with(" missing") {
        return Some((Followed::Absent, &stdout[end + 1..]));
    }
    let words: Vec<&str> = header.split(' ').collect();
    let size: usize = words.last()?.parse().ok()?;
    let body = stdout.get(end + 1..end + 1 + size)?;
    let rest = stdout.get(end + 1 + size..)?.strip_prefix(b"\n")?;
    let followed = match words.as_slice() {
        [_, "blob", _] => Followed::File(body.to_vec()),
        ["dangling", _] => Followed::Dangling,
        ["loop", _] => Followed::Unfollowed("a symlink loop"),
        ["notdir", _] => Followed::Unfollowed("a path through a file"),
        // Absolute targets land here even when they point inside the
        // repository (measured, git 2.56).
        ["symlink", _] => Followed::Unfollowed(
            "a symlink git will not follow (absolute, or out of the repository)",
        ),
        [_, _, _] => Followed::Unfollowed("not a file"),
        _ => return None,
    };
    Some((followed, rest))
}

/// What a scripted child does: answers, or never answers before the deadline.
#[cfg(test)]
pub(super) enum Scripted {
    Says(Reply),
    NoAnswer,
}

#[cfg(test)]
impl Scripted {
    fn into_outcome(self) -> Result<Reply, env::RemoteFailure> {
        match self {
            Self::Says(reply) => Ok(reply),
            Self::NoAnswer => Err(env::RemoteFailure::Deadline {
                limit: std::time::Duration::from_secs(2),
                reach: oakum::discover::child::Reach::Killed(Vec::new()),
            }),
        }
    }
}

/// Where a child's answer comes from. Only [`Runner::Child`] ships. The fake
/// stands in at the spawn, below the transport guard and the remote notes, so
/// what [`Git::child`] decides before one runs against the script instead of
/// being bypassed by it.
enum Runner {
    Child,
    #[cfg(test)]
    Fake(fake::Fake),
}

/// A commit id, kept distinct from a ref name so the two cannot be transposed
/// at a call site: `git check-ref-format` accepts a bare sha, so validating the
/// name catches nothing. Minted by [`Git::head`], [`Git::tag_commit`], and
/// [`Self::from_advertised`] (ls-remote tips), so every value is what a
/// commit-naming git read produced.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Commit(String);

/// [`Git::blob_kind`]'s answer. `Other` is any entry: a regular blob, but
/// also a symlink, a tree or a gitlink, which `cat-file blob` then reads as
/// its link text or refuses on its own.
#[derive(Debug)]
pub(super) enum BlobKind {
    Absent,
    Other,
}

/// One entry of [`Git::tree_files`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct TreeFile {
    pub(super) mode: String,
    pub(super) object: String,
    /// Lossy when the path is not UTF-8, which `exact` says.
    pub(super) path: String,
    pub(super) exact: bool,
}

/// [`Git::followed_blob`]'s answer.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Followed {
    File(Vec<u8>),
    Absent,
    /// A link whose target is not in that commit, as when the target is
    /// gitignored: no file there, but not nothing.
    Dangling,
    /// A path git would not follow to a file in that commit, named for the
    /// refusal: a loop, a path through a file, a link out of the repository.
    Unfollowed(&'static str),
}

impl Commit {
    pub(super) fn as_str(&self) -> &str {
        &self.0
    }

    /// Same provenance rule as [`Git::head`]: the string came from a
    /// commit-naming git read.
    pub(super) fn from_advertised(sha: &str) -> Result<Self, CliError> {
        if sha.is_empty() {
            return Err(CliError::unverified(
                "unverified: ls-remote advertised an empty commit id",
            ));
        }
        Ok(Self(sha.to_owned()))
    }

    /// A tag's peeled commit, as the reachable-tags listing reports it.
    pub(super) fn from_tag_listing(sha: &str) -> Result<Self, CliError> {
        if sha.is_empty() {
            return Err(CliError::unverified(
                "unverified: the tag listing named an empty commit id",
            ));
        }
        Ok(Self(sha.to_owned()))
    }

    /// A commit `git log` listed.
    pub(super) fn from_log(sha: &str) -> Result<Self, CliError> {
        if sha.is_empty() {
            return Err(CliError::unverified(
                "unverified: the commit listing named an empty commit id",
            ));
        }
        Ok(Self(sha.to_owned()))
    }
}

/// A commit's message and git's parse of its `skip-checks` trailer values,
/// one value per line.
#[derive(Debug)]
pub(super) struct CommitText {
    pub(super) message: String,
    pub(super) skip_checks: String,
}

/// Runs git in one repository.
pub(super) struct Git {
    repo: PathBuf,
    /// Each child re-checks that `repo` still names this directory.
    /// [`Self::at`] leaves this empty (cwd plumbing, tests).
    held: Option<Dir>,
    runner: Runner,
    /// Resolved on the first child and reused. The answer comes from the
    /// process environment and the repository config, neither of which changes
    /// while oakum runs, so resolving it per child costs a `git config` spawn
    /// each time. A scripted [`Git`] carries its own in the fake and leaves
    /// this empty.
    ///
    /// The failure is cached too, and travels as the bare reason so the caller
    /// phrases it: an operation that needed the transport turns it into an
    /// `unverified` error, one that did not says it plainly. Pre-wrapped, both
    /// phrasings land in the same line and contradict each other.
    transport: OnceLock<std::sync::Arc<Result<env::BatchSsh, env::TransportUnknown>>>,
    /// What each named remote's listed URLs established, per direction, so
    /// the notes are asked about the remote in hand.
    reach_by_remote: Mutex<BTreeMap<(String, Direction), reach::Reach>>,
    /// Notes already said, keyed by their text: distinct fetch and push notes
    /// each land, while a byte-identical one says itself once.
    warned: Mutex<BTreeSet<String>>,
    /// Read once: oakum never fetches, so a clone's depth holds for the run.
    shallow: OnceLock<Result<bool, CliError>>,
    /// [`Op::Commits`] by range, read once: no operation here moves `HEAD`.
    commit_listings: Mutex<BTreeMap<Option<String>, Result<String, CliError>>>,
    /// The base a command falls back to without `--from`, found once: no
    /// operation here moves a branch ref.
    default_base: OnceLock<Result<String, CliError>>,
    offline: bool,
    promisor: OnceLock<bool>,
    empty_tree: OnceLock<Commit>,
}

impl Git {
    pub(super) fn at(repo: impl Into<PathBuf>) -> Self {
        Self::new(repo.into(), Runner::Child, None)
    }

    pub(super) fn at_repository(
        repo: &super::repository::Repository,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let path = repo.ambient_path()?.to_path_buf();
        let held = repo.dir().try_clone().map_err(|err| {
            CliError::new(format!("failed to clone the repository capability: {err}"))
        })?;
        Ok(Self::new(path, Runner::Child, Some(held)))
    }

    /// Answers from a script instead of a repository, each keyed by the command
    /// it answers, over a composed ssh transport. The path is never read.
    #[cfg(test)]
    pub(super) fn answering(replies: impl IntoIterator<Item = (&'static str, Reply)>) -> Self {
        Self::scripted(
            replies
                .into_iter()
                .map(|(op, reply)| (op, Scripted::Says(reply))),
        )
    }

    /// [`Self::answering`] where a child may also never answer, the way a
    /// deadline-killed one does, so the paths that re-read after a no-answer
    /// are drivable without a process.
    #[cfg(test)]
    pub(super) fn scripted(outcomes: impl IntoIterator<Item = (&'static str, Scripted)>) -> Self {
        Self::new(
            PathBuf::new(),
            Runner::Fake(fake::Fake::answering(
                Ok(env::BatchSsh::Composed(String::from(
                    "ssh -o BatchMode=yes",
                ))),
                outcomes
                    .into_iter()
                    .map(|(op, scripted)| (op, scripted.into_outcome())),
            )),
            None,
        )
    }

    /// [`Self::answering`] with the transport the probe would have resolved,
    /// so the guard every child passes through is drivable both ways. Private
    /// to this module, whose types the transport is made of.
    #[cfg(test)]
    fn answering_over(
        transport: Result<env::BatchSsh, env::TransportUnknown>,
        replies: impl IntoIterator<Item = (&'static str, Reply)>,
    ) -> Self {
        Self::new(
            PathBuf::new(),
            Runner::Fake(fake::Fake::answering(
                transport,
                replies.into_iter().map(|(op, reply)| (op, Ok(reply))),
            )),
            None,
        )
    }

    fn new(repo: PathBuf, runner: Runner, held: Option<Dir>) -> Self {
        Self {
            repo,
            held,
            runner,
            transport: OnceLock::new(),
            reach_by_remote: Mutex::new(BTreeMap::new()),
            warned: Mutex::new(BTreeSet::new()),
            shallow: OnceLock::new(),
            commit_listings: Mutex::new(BTreeMap::new()),
            default_base: OnceLock::new(),
            offline: false,
            promisor: OnceLock::new(),
            empty_tree: OnceLock::new(),
        }
    }

    /// For a command that writes nothing, `.git` included: a partial clone's
    /// missing object fails the read rather than being fetched.
    pub(super) fn offline(mut self) -> Self {
        self.offline = true;
        self
    }

    pub(super) fn default_base(
        &self,
        find: impl FnOnce() -> Result<String, CliError>,
    ) -> Result<String, CliError> {
        self.default_base.get_or_init(find).clone()
    }

    /// [`Op::Commits`] for `from..HEAD`, or all of `HEAD`'s history when
    /// `from` is `None`.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn commits(&self, from: Option<&str>) -> Result<String, CliError> {
        let key = from.map(str::to_owned);
        let mut listings = self
            .commit_listings
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        listings
            .entry(key)
            .or_insert_with(|| self.text(Op::Commits { from }))
            .clone()
    }

    pub(super) fn shallow(
        &self,
        read: impl FnOnce() -> Result<bool, CliError>,
    ) -> Result<bool, CliError> {
        self.shallow.get_or_init(read).clone()
    }

    /// Each operation the caller asked for, in order, named as [`OpShape::name`]
    /// names it — the same phrase a failure quotes.
    ///
    /// # Panics
    ///
    /// When called on a [`Git`] that runs real children, which cannot report
    /// what it spawned.
    #[cfg(test)]
    pub(super) fn asked(&self) -> Vec<String> {
        match &self.runner {
            Runner::Fake(fake) => fake.asked(),
            Runner::Child => panic!("only a scripted Git records what it was asked"),
        }
    }

    /// Each note a child said, in order; a scripted [`Git`] hears them instead
    /// of writing them to stderr.
    ///
    /// # Panics
    ///
    /// When called on a [`Git`] that runs real children.
    #[cfg(test)]
    pub(super) fn said(&self) -> Vec<String> {
        match &self.runner {
            Runner::Fake(fake) => fake.heard(),
            Runner::Child => panic!("only a scripted Git records what it said"),
        }
    }

    /// What `path` is in `commit`'s tree, so a caller never parses `ls-tree`
    /// output itself.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn blob_kind(&self, commit: &Commit, path: &str) -> Result<BlobKind, CliError> {
        let entries = self.paths(Op::TreeEntry { commit, path })?;
        Ok(if entries.is_empty() {
            BlobKind::Absent
        } else {
            BlobKind::Other
        })
    }

    /// `path` in `commit`, its symlinks followed in that commit's own tree.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class, or a reply oakum cannot frame.
    pub(super) fn followed_blob(&self, commit: &Commit, path: &str) -> Result<Followed, CliError> {
        let mut answers = self.followed_blobs(&[(commit, path)])?;
        Ok(answers.swap_remove(0))
    }

    /// [`Self::followed_blob`] for each query, in order, from one child.
    ///
    /// # Errors
    ///
    /// As [`Self::followed_blob`].
    pub(super) fn followed_blobs(
        &self,
        queries: &[(&Commit, &str)],
    ) -> Result<Vec<Followed>, CliError> {
        // A batch query ends at a newline, so one inside the path would ask
        // a second question and read the first answer as this one. Never
        // asked is unanswered, which a caller's wrapper keeps unverified.
        if let Some((commit, path)) = queries.iter().find(|(_, path)| path.contains('\n')) {
            return Err(CliError::unanswered(format!(
                "unverified: `{}` holds a newline, which git's batch read cannot frame, so it was not read at {}",
                path.escape_debug(),
                commit.as_str()
            )));
        }
        if queries.is_empty() {
            return Ok(Vec::new());
        }
        let shape = Op::FollowedBlob { queries }.shape();
        let reply = self.checked(&shape, Reads::Text)?;
        let mut rest = reply.stdout.as_slice();
        queries
            .iter()
            .map(|(commit, path)| {
                let (followed, after) = parse_followed(rest)
                    .ok_or_else(|| shape.fail("answered in a shape oakum cannot read"))?;
                rest = after;
                if matches!(followed, Followed::Absent | Followed::Dangling) {
                    self.absent(commit, path)?;
                }
                Ok(followed)
            })
            .collect()
    }

    /// Why a reftable ref store cannot be read, when it cannot. git loads the
    /// common stack and a linked worktree's own stack whole, and one table or
    /// `tables.list` it cannot read makes every ref read as absent at exit 0,
    /// while `refs verify` crashes (measured, git 2.56). `None` for the files
    /// backend, whose unreadable `packed-refs` git refuses itself.
    ///
    /// # Errors
    ///
    /// git could not be run, or answered in a shape oakum cannot read.
    pub(super) fn unreadable_reftable(&self) -> Result<Option<String>, CliError> {
        let shape = Op::RefStore.shape();
        // Untrimmed, and split once: a path may end in whitespace or hold a
        // newline, and only git's own line ending is not part of it.
        let text = self.blob(Op::RefStore)?;
        let Some((format, common)) = text.strip_suffix('\n').unwrap_or(&text).split_once('\n')
        else {
            return Err(shape.fail("answered in a shape oakum cannot read"));
        };
        if format != "reftable" {
            return Ok(None);
        }
        let git_dir = self.blob(Op::GitDir)?;
        let git_dir = git_dir.strip_suffix('\n').unwrap_or(&git_dir);
        let mut stacks = vec![Path::new(common).join("reftable")];
        if git_dir != common {
            stacks.push(Path::new(git_dir).join("reftable"));
        }
        Ok(stacks.iter().find_map(|stack| unreadable_stack(stack)))
    }

    /// What `git refs verify` says that leaves the tag store partly unread:
    /// a directory under `refs/tags` it could not open, or the check killed
    /// before it finished. Its warnings about a ref's form (a missing
    /// newline, a symlink, a stray file) name refs it did read, so they are
    /// `None`, as is a git before 2.47, which has no such command.
    ///
    /// # Errors
    ///
    /// git could not be run.
    pub(super) fn tag_refs_complaint(&self) -> Result<Option<String>, CliError> {
        let reply = self.child(&Op::VerifyRefs.shape())?;
        if reply.code.is_none() {
            return Ok(Some(String::from(
                "it was terminated by a signal before it finished",
            )));
        }
        Ok(reply.diagnostic().and_then(|said| {
            let mut unopened = said
                .lines()
                .filter(|line| line.contains("error opening directory"))
                .peekable();
            let first = (*unopened.peek()?).to_owned();
            // A line no git message starts is a path's newline continuing
            // the last one, and no line can then be framed with certainty.
            let continued = said.lines().any(|line| {
                !line.trim().is_empty()
                    && !GIT_PREFIXES.iter().any(|prefix| line.starts_with(prefix))
            });
            if continued {
                return Some(first);
            }
            unopened
                .find(|line| names_a_tag_directory(line))
                .map(str::to_owned)
        }))
    }

    /// Trimmed stdout.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn text(&self, op: Op<'_>) -> Result<String, CliError> {
        let shape = op.shape();
        let reply = self.checked(&shape, Reads::Text)?;
        if shape.spec.lossy() {
            return Ok(String::from_utf8_lossy(&reply.stdout).trim().to_owned());
        }
        String::from_utf8(reply.stdout)
            .map(|text| text.trim().to_owned())
            .map_err(|_| shape.fail("output is not valid UTF-8"))
    }

    /// Stdout less its one trailing newline, for a path that may itself end
    /// in whitespace, which [`Self::text`] would trim away.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn line(&self, op: Op<'_>) -> Result<String, CliError> {
        let shape = op.shape();
        let reply = self.checked(&shape, Reads::Text)?;
        let mut text =
            String::from_utf8(reply.stdout).map_err(|_| shape.fail("output is not valid UTF-8"))?;
        if text.ends_with('\n') {
            text.pop();
        }
        Ok(text)
    }

    /// HEAD's commit id. With [`Self::tag_commit`] and [`Self::merge_base`],
    /// one of the mints for [`Commit`]: kept to the commit-naming reads, so a
    /// listing or URL read cannot be wrapped as a commit.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn head(&self) -> Result<Commit, CliError> {
        self.text(Op::Head).map(Commit)
    }

    /// The commit a local tag points at, peeled; `None` when the tag is
    /// absent.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn tag_commit(&self, tag: &str) -> Result<Option<Commit>, CliError> {
        Ok(self.optional_text(Op::LocalTagCommit { tag })?.map(Commit))
    }

    /// `None` when `tip` and `HEAD` share no ancestor.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn merge_base(&self, tip: &str) -> Result<Option<Commit>, CliError> {
        Ok(self.optional_text(Op::MergeBase { tip })?.map(Commit))
    }

    /// `commit`'s first parent; for a root, the empty tree, which reads as a
    /// commit holding no file.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn first_parent_or_empty(&self, commit: &Commit) -> Result<Commit, CliError> {
        let parents = self.text(Op::Parents { commit })?;
        if let Some(parent) = parents.lines().next() {
            return Commit::from_log(parent);
        }
        if let Some(tree) = self.empty_tree.get() {
            return Ok(tree.clone());
        }
        let tree = Commit(self.text(Op::EmptyTree)?.trim().to_owned());
        Ok(self.empty_tree.get_or_init(|| tree).clone())
    }

    /// [`Op::FirstParentWriters`], newest first.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn first_parent_writers(&self, paths: &[&str]) -> Result<Vec<Commit>, CliError> {
        Ok(self
            .text(Op::FirstParentWriters { paths })?
            .lines()
            .filter(|line| !line.is_empty())
            .map(|line| Commit(line.to_owned()))
            .collect())
    }

    /// A blob exactly as git stored it.
    ///
    /// [`Self::text`] trims, which is right for a hash or a ref name and wrong
    /// for a file whose parser reads from byte zero: a bump file with a blank
    /// line before its frontmatter is malformed on disk and would parse here,
    /// so the two copies of one file would be judged by different rules.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class, or invalid UTF-8.
    pub(super) fn blob(&self, op: Op<'_>) -> Result<String, CliError> {
        let shape = op.shape();
        let reply = self.checked(&shape, Reads::Text)?;
        String::from_utf8(reply.stdout).map_err(|_| shape.fail("blob is not valid UTF-8"))
    }

    /// Each of `paths` at `commit` as text, in order, from one child.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class; a path holding a newline, which
    /// stdin cannot frame; or an entry that is missing, not a file, or not
    /// UTF-8.
    pub(super) fn blobs(&self, commit: &Commit, paths: &[&str]) -> Result<Vec<String>, CliError> {
        // Without `absent_ok` a missing entry fails, so every entry is `Some`.
        Ok(self
            .batch_blobs(commit, paths, false)?
            .into_iter()
            .flatten()
            .collect())
    }

    /// The repository's directory, as given.
    pub(super) fn root(&self) -> &Path {
        &self.repo
    }

    /// Every entry in `commit`'s tree, read without fetching.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class, a tree a partial clone lacks among
    /// them, or a reply oakum cannot frame.
    pub(super) fn tree_files(&self, commit: &Commit) -> Result<Vec<TreeFile>, CliError> {
        let shape = Op::TreeFiles { commit }.shape();
        let stdout = self.checked(&shape, Reads::Text)?.stdout;
        stdout
            .split(|byte| *byte == 0)
            .filter(|record| !record.is_empty())
            .map(|record| {
                let exact = std::str::from_utf8(record).is_ok();
                let record = String::from_utf8_lossy(record);
                let (head, path) = record
                    .split_once('\t')
                    .ok_or_else(|| shape.fail("answered in a shape oakum cannot read"))?;
                match head.split(' ').collect::<Vec<_>>().as_slice() {
                    [mode, _, object] => Ok(TreeFile {
                        mode: (*mode).to_owned(),
                        object: (*object).to_owned(),
                        path: path.to_owned(),
                        exact,
                    }),
                    _ => Err(shape.fail("answered in a shape oakum cannot read")),
                }
            })
            .collect()
    }

    /// Each object's bytes, in order, read without fetching; `None` for one
    /// the repository lacks, as a partial clone may.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class, or a reply oakum cannot frame.
    pub(super) fn objects(&self, objects: &[&str]) -> Result<Vec<Option<Vec<u8>>>, CliError> {
        if objects.is_empty() {
            return Ok(Vec::new());
        }
        let shape = Op::Objects { objects }.shape();
        let stdout = self.checked(&shape, Reads::Text)?.stdout;
        let mut rest = stdout.as_slice();
        objects
            .iter()
            .map(|object| {
                let cut = || shape.fail(&format!("stopped at {object}"));
                let end = rest
                    .iter()
                    .position(|byte| *byte == b'\n')
                    .ok_or_else(cut)?;
                let header = std::str::from_utf8(&rest[..end]).map_err(|_| cut())?;
                if header == format!("{object} missing") {
                    rest = &rest[end + 1..];
                    return Ok(None);
                }
                let size = match header.split(' ').collect::<Vec<_>>().as_slice() {
                    [_, _, size] => size.parse::<usize>().map_err(|_| cut())?,
                    _ => return Err(cut()),
                };
                let body = rest.get(end + 1..end + 1 + size).ok_or_else(cut)?;
                if rest.get(end + 1 + size) != Some(&b'\n') {
                    return Err(cut());
                }
                let body = body.to_vec();
                rest = &rest[end + 2 + size..];
                Ok(Some(body))
            })
            .collect()
    }

    /// [`Self::blobs`], with a path `commit` does not hold as `None`.
    ///
    /// # Errors
    ///
    /// As [`Self::blobs`], short of a missing entry; see [`Self::absent`].
    pub(super) fn blobs_or_absent(
        &self,
        commit: &Commit,
        paths: &[&str],
    ) -> Result<Vec<Option<String>>, CliError> {
        self.batch_blobs(commit, paths, true)
    }

    /// Offline, a batch read answers `missing` or `dangling` alike for an
    /// absent path and for an object the repository lacks, whatever its
    /// config says (measured, git 2.56), so the tree, walked through its
    /// links, tells them apart.
    fn absent(&self, commit: &Commit, path: &str) -> Result<(), CliError> {
        if !self.offline {
            return Ok(());
        }
        let lacked = |what: &str| {
            CliError::unverified(format!(
                "unverified: `{path}` at {} reaches {what}, which this repository does not hold, and `check` reads without fetching; a clone without `--filter` lets it read",
                commit.as_str()
            ))
        };
        let mut walked = path.to_owned();
        // Each link followed restarts the walk; a chain this long is a loop.
        for _ in 0..40 {
            let parts: Vec<&str> = walked.split('/').collect();
            let mut through_link = None;
            for end in 1..=parts.len() {
                let prefix = parts[..end].join("/");
                let entries = self
                    .paths(Op::TreeEntry {
                        commit,
                        path: &prefix,
                    })
                    .map_err(|_| lacked(&format!("a tree holding `{prefix}`")))?;
                let Some(entry) = entries.first() else {
                    return Ok(());
                };
                let head = entry
                    .split_once('\t')
                    .map_or(entry.as_str(), |(head, _)| head);
                let [mode, _, object] = head.split(' ').collect::<Vec<_>>()[..] else {
                    return Err(lacked(&format!(
                        "`{prefix}`, listed in a shape oakum cannot read"
                    )));
                };
                if mode == "040000" {
                    continue;
                }
                // git does not follow a path into a submodule's commit.
                if mode == "160000" {
                    return Ok(());
                }
                let Some(Some(bytes)) = self.objects(&[object])?.pop() else {
                    return Err(lacked(&format!("`{prefix}`")));
                };
                if mode != "120000" {
                    return Ok(());
                }
                let parent = prefix.rsplit_once('/').map_or("", |(parent, _)| parent);
                let Some(mut target) =
                    super::base_tree::normalized(parent, &String::from_utf8_lossy(&bytes))
                else {
                    return Ok(());
                };
                for rest in &parts[end..] {
                    target = super::base_tree::in_dir(&target, rest);
                }
                if target.is_empty() {
                    return Ok(());
                }
                through_link = Some(target);
                break;
            }
            match through_link {
                Some(target) => walked = target,
                None => return Ok(()),
            }
        }
        Ok(())
    }

    fn batch_blobs(
        &self,
        commit: &Commit,
        paths: &[&str],
        absent_ok: bool,
    ) -> Result<Vec<Option<String>>, CliError> {
        if paths.is_empty() {
            return Ok(Vec::new());
        }
        let op = Op::Blobs { commit, paths };
        let shape = op.shape();
        if paths.iter().any(|path| path.contains('\n')) {
            return Err(
                shape.fail("was asked for a path holding a newline, which stdin cannot frame")
            );
        }
        let stdout = self.checked(&shape, Reads::Text)?.stdout;
        let mut rest = stdout.as_slice();
        let mut texts = Vec::with_capacity(paths.len());
        for path in paths {
            let end = rest
                .iter()
                .position(|byte| *byte == b'\n')
                .ok_or_else(|| shape.fail(&format!("stopped before {path}")))?;
            let header = std::str::from_utf8(&rest[..end]).unwrap_or_default();
            if absent_ok && header == format!("{}:{path} missing", commit.as_str()) {
                self.absent(commit, path)?;
                texts.push(None);
                rest = &rest[end + 1..];
                continue;
            }
            let size = match header.split(' ').collect::<Vec<_>>().as_slice() {
                [_, "blob", size] => size.parse::<usize>().ok(),
                _ => None,
            }
            .ok_or_else(|| shape.fail(&format!("{path} is not a file: {header}")))?;
            let body = rest
                .get(end + 1..end + 1 + size)
                .ok_or_else(|| shape.fail(&format!("stopped inside {path}")))?;
            if rest.get(end + 1 + size) != Some(&b'\n') {
                return Err(shape.fail(&format!("stopped inside {path}")));
            }
            texts
                .push(Some(String::from_utf8(body.to_vec()).map_err(|_| {
                    shape.fail(&format!("{path} is not valid UTF-8"))
                })?));
            rest = &rest[end + 2 + size..];
        }
        Ok(texts)
    }

    /// The paths each of `hashes` changed against its first parent, from one
    /// child; a commit that changed nothing maps to no paths. Merges belong
    /// nowhere in `hashes`: `diff-tree` lists none for them. Once the batch
    /// fails each commit is read alone, so a failure is its own commit's,
    /// worded as the per-commit read words it.
    pub(super) fn commit_paths(
        &self,
        hashes: &[&str],
    ) -> BTreeMap<String, Result<Vec<String>, CliError>> {
        match self.commit_paths_batched(hashes) {
            Ok(by_commit) => by_commit
                .into_iter()
                .map(|(hash, paths)| (hash, Ok(paths)))
                .collect(),
            Err(_) => hashes
                .iter()
                .map(|hash| ((*hash).to_owned(), self.paths(Op::CommitPath { hash })))
                .collect(),
        }
    }

    fn commit_paths_batched(
        &self,
        hashes: &[&str],
    ) -> Result<BTreeMap<String, Vec<String>>, CliError> {
        let mut by_commit: BTreeMap<String, Vec<String>> = hashes
            .iter()
            .map(|hash| ((*hash).to_owned(), Vec::new()))
            .collect();
        if hashes.is_empty() {
            return Ok(by_commit);
        }
        let op = Op::CommitPaths { hashes };
        let shape = op.shape();
        let records =
            split_nul_paths(&self.checked(&shape, Reads::Paths)?.stdout).ok_or_else(|| {
                shape.fail(
                    "listed a path that is not valid UTF-8; oakum cannot attribute it to a package",
                )
            })?;
        let mut current: Option<String> = None;
        let mut first = false;
        for record in records {
            if let Some(hash) = record.strip_prefix('\u{1}') {
                if by_commit.contains_key(hash) {
                    current = Some(hash.to_owned());
                    first = true;
                    continue;
                }
            }
            // The format's newline opens each commit's first path.
            let path = if first {
                record.strip_prefix('\n')
            } else {
                Some(record.as_str())
            };
            let (Some(paths), Some(path)) = (
                current.as_ref().and_then(|hash| by_commit.get_mut(hash)),
                path,
            ) else {
                return Err(shape.fail("listed a path under no commit it was asked about"));
            };
            paths.push(path.to_owned());
            first = false;
        }
        Ok(by_commit)
    }

    /// NUL-separated paths. `-z` turns quoting off, so a path carrying newlines,
    /// boundary whitespace, or non-ASCII bytes arrives byte-for-byte and
    /// package-prefix attribution stays exact. A non-UTF-8 path cannot be
    /// compared against manifest-derived package directories, so it fails loudly
    /// rather than being lossily rewritten into one that misses its package.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn paths(&self, op: Op<'_>) -> Result<Vec<String>, CliError> {
        let shape = op.shape();
        let stdout = self.checked(&shape, Reads::Paths)?.stdout;
        split_nul_paths(&stdout).ok_or_else(|| {
            shape.fail(
                "listed a path that is not valid UTF-8; oakum cannot attribute it to a package",
            )
        })
    }

    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn run(&self, op: Op<'_>) -> Result<(), CliError> {
        self.checked(&op.shape(), Reads::Text)?;
        Ok(())
    }

    /// For the queries git answers with an exit code. `Ok(false)` only for exit 1
    /// with nothing written, which is how git says "no"; a diagnosed failure is
    /// an error, so "we could not look" never becomes a verdict.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn predicate(&self, op: Op<'_>) -> Result<bool, CliError> {
        let shape = op.shape();
        let reply = self.answered(&shape, Reads::Text)?;
        if reply.succeeded() {
            return Ok(true);
        }
        if reply.said_no() {
            return Ok(false);
        }
        Err(self.failed(&shape, &reply))
    }

    /// `Ok(None)` for a search that matched nothing: exit 1 with both streams
    /// silent, which is how `git grep` says no. Unlike [`Self::optional_text`]
    /// the answer is split on NUL rather than trimmed, so a path that is or ends
    /// in whitespace survives.
    ///
    /// A search that matched nothing and one that searched nothing look alike
    /// here; only the caller knows whether there was anything to search.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn matched_paths(&self, op: Op<'_>) -> Result<Option<Vec<String>>, CliError> {
        let shape = op.shape();
        let reply = self.answered(&shape, Reads::Paths)?;
        if !reply.succeeded() {
            if reply.said_no() {
                return Ok(None);
            }
            return Err(self.failed(&shape, &reply));
        }
        split_nul_paths(&reply.stdout).map(Some).ok_or_else(|| {
            shape.fail("listed a path that is not valid UTF-8; oakum cannot name it as a gate")
        })
    }

    /// `Ok(None)` for the queries that report "absent" as exit 1 with nothing
    /// written — `config --get-regexp` with no match, `rev-parse --verify
    /// --quiet` on a missing ref. Any other failure is still an error: a
    /// wrapper that exits 1 with a diagnostic did not look, which is not the
    /// same as looking and finding nothing.
    ///
    /// # Errors
    ///
    /// The operation's own outcome class.
    pub(super) fn optional_text(&self, op: Op<'_>) -> Result<Option<String>, CliError> {
        let shape = op.shape();
        let reply = self.answered(&shape, Reads::Text)?;
        if !reply.succeeded() {
            if reply.said_no() {
                return Ok(None);
            }
            return Err(self.failed(&shape, &reply));
        }
        let text =
            String::from_utf8(reply.stdout).map_err(|_| shape.fail("output is not valid UTF-8"))?;
        Ok(Some(text.trim().to_owned()).filter(|text| !text.is_empty()))
    }

    /// The answer, with a failed child already turned into the operation's own
    /// error. Callers that read an exit code as data go through [`Self::ask`].
    fn checked(&self, shape: &OpShape<'_>, reads: Reads) -> Result<Reply, CliError> {
        let reply = self.answered(shape, reads)?;
        if reply.succeeded() {
            return Ok(reply);
        }
        Err(self.failed(shape, &reply))
    }

    /// A read an offline handle could not make for want of an object is one
    /// that did not look, whatever the operation's class: git names the
    /// object it could not read (measured, git 2.56).
    fn failed(&self, shape: &OpShape<'_>, reply: &Reply) -> CliError {
        let detail = reply.detail();
        if self.offline
            && (detail.contains("unable to read") || detail.contains("lazy fetching disabled"))
            && self.has_promisor()
        {
            return CliError::unverified(format!(
                "unverified: {}; this partial clone lacks it, and `check` reads without fetching",
                shape
                    .fail(&detail)
                    .detail()
                    .trim_start_matches("unverified: ")
            ));
        }
        shape.fail(&detail)
    }

    /// A full clone missing an object is corrupt, not partial. A config that
    /// cannot be read names no promisor, so the failure keeps its own class.
    fn has_promisor(&self) -> bool {
        *self.promisor.get_or_init(|| {
            let shape = Op::Promisors.shape();
            self.answered(&shape, Reads::Text)
                .is_ok_and(|reply| names_a_promisor(&String::from_utf8_lossy(&reply.stdout)))
        })
    }

    /// The answer, refusing a child that exited 0 without giving one. What
    /// silence means is a property of the operation, not of the accessor
    /// reading it: keyed on the outcome class instead, this reached neither
    /// `predicate` nor `optional_text`, and a config read that never ran came
    /// back as "no remote suppresses tags".
    fn answered(&self, shape: &OpShape<'_>, reads: Reads) -> Result<Reply, CliError> {
        let reply = self.child(shape)?;
        // Before the `spoke` shortcut, because a listing that must be whole is
        // disqualified by its diagnostic whether or not it also wrote records —
        // one record of stdout would otherwise turn a partial walk into a
        // complete answer. Only for a child that exited 0: one that failed
        // listed none of the tree, and `checked` says that better below.
        if let Some(whole) = shape.spec.whole().filter(|_| reply.succeeded()) {
            if let Some(said) = reply.diagnostic().filter(|said| whole.skipped(said)) {
                return Err(shape.phrase(|what| {
                    format!(
                        "git {what} may have listed only {}, reporting: {said}",
                        whole.part()
                    )
                }));
            }
        }
        if !reply.succeeded() || reply.spoke(reads) {
            return Ok(reply);
        }
        match shape.spec.answer() {
            Answer::Always => Err(Self::empty_answer(shape, &reply)),
            // Any stderr text disqualifies, benign text included: an `ls-remote`
            // that found no tags while ssh wrote `Warning: Permanently added
            // ... to the list of known hosts` is refused. Deliberate — nothing
            // reliably separates a benign line from a consequential one, and
            // unlike `core.fsmonitor` no setting drops the diagnostic without
            // dropping the check with it. The refusal quotes the warning, so a
            // second run resolves it.
            Answer::Sometimes if reply.diagnostic().is_some() => {
                Err(Self::empty_answer(shape, &reply))
            }
            Answer::Sometimes | Answer::Never => Ok(reply),
        }
    }

    /// One commit's message and its `skip-checks` trailer values, split
    /// where [`Op::CommitMessage`]'s format puts the separator. Parsed here,
    /// beside the format that creates the framing, so no caller re-inherits
    /// the contract — and a reply that lacks the separator, or still carries
    /// the unexpanded specifier (a git too old to parse trailers), is an
    /// error rather than a silent "no trailers": guessing there would release
    /// a commit whose workflow GitHub suppresses.
    pub(super) fn commit_text(&self, commit: &str) -> Result<CommitText, CliError> {
        let raw = self.text(Op::CommitMessage { commit })?;
        let Some((message, trailers)) = raw.split_once('\0') else {
            return Err(CliError::new(format!(
                "git log for `{commit}` omitted the trailer separator oakum's \
                 format requests"
            )));
        };
        if trailers.trim() == SKIP_CHECKS_ATOM && !message.contains(SKIP_CHECKS_ATOM) {
            return Err(CliError::new(format!(
                "this git did not parse the skip-checks trailers for \
                 `{commit}`; oakum cannot tell whether the commit suppresses \
                 CI"
            )));
        }
        Ok(CommitText {
            message: message.to_owned(),
            skip_checks: trailers.to_owned(),
        })
    }

    /// The ssh transport for this repository, resolved once per process: it
    /// is a property of the environment and the repository config, neither of
    /// which changes while oakum runs, and `Git` values are constructed
    /// throughout the cli — per-instance caching re-probed on every one now
    /// that every child carries the transport.
    fn transport(&self) -> Result<&env::BatchSsh, &env::TransportUnknown> {
        use std::collections::HashMap;
        use std::sync::{Arc, Mutex, OnceLock};
        type Resolved =
            Mutex<HashMap<std::path::PathBuf, Arc<Result<env::BatchSsh, env::TransportUnknown>>>>;
        static RESOLVED: OnceLock<Resolved> = OnceLock::new();
        #[cfg(test)]
        if let Runner::Fake(fake) = &self.runner {
            return fake.transport();
        }
        self.transport
            .get_or_init(|| {
                let mut resolved = RESOLVED
                    .get_or_init(|| Mutex::new(HashMap::new()))
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                resolved
                    .entry(self.repo.clone())
                    .or_insert_with(|| Arc::new(env::batch_transport(&self.repo)))
                    .clone()
            })
            .as_ref()
            .as_ref()
    }

    /// Each distinct note lands once. The transport resolves the same way
    /// for every child, so without this an N-tag release repeats it 1 + 2N
    /// times.
    fn say_once(&self, note: &str) {
        match &self.runner {
            Runner::Child => {
                self.say_once_with(note, env::warn);
            }
            #[cfg(test)]
            Runner::Fake(fake) => {
                self.say_once_with(note, |note| fake.hear(note));
            }
        }
    }

    /// Takes the sayer, because the rollback below is otherwise the one branch
    /// no test can drive: `say_once` reaches stderr through `env::warn`, and a
    /// refused write there is not reproducible in process.
    ///
    /// The lock spans the write: released first, a second caller skips on a
    /// reservation about to be rolled back and both stay silent. `warn`
    /// re-enters nothing, so holding it cannot deadlock the way it would around
    /// a spawn, and with `Git` driven from one thread it orders a race that
    /// cannot yet happen.
    fn say_once_with(&self, note: &str, say: impl FnOnce(&str) -> bool) -> bool {
        let key = note.to_owned();
        let mut warned = self
            .warned
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if !warned.insert(key.clone()) {
            return false;
        }
        // A stderr that could not take the line must not consume the one chance
        // to say it. A write that failed partway still leaves its fragment, and
        // the retry then says the whole note again; a fragment plus the note
        // beats losing the note.
        let said = say(note);
        if !said {
            warned.remove(&key);
        }
        said
    }

    /// Whether the note about ssh prompts applies to the remote this operation
    /// contacts. One `remote -v` child lists every remote's fetch and push
    /// URLs — pushurl included, so a remote that fetches over https and
    /// pushes over ssh still warns on the push — and fills the cache for all
    /// of them, so the unconditional read costs one spawn per run rather than
    /// one per operation. Neither URL changes while oakum runs.
    ///
    /// A failed read is cached alongside a settled one, which is safe only
    /// while the sole consumer is an advisory note — an unread verdict from a
    /// transient signal is cached exactly like an established one.
    fn remote_reach(&self, contact: Contact<'_>) -> reach::Reach {
        let key = contact.key();
        if let Some(answer) = self.remembered_reach(&key) {
            return answer;
        }
        // The listing child spawns before the lock is taken: a `Mutex` is not
        // reentrant, so holding it across the spawn deadlocks outright — no
        // error, no output — if the listing operation is ever itself classed
        // as contacting a remote. Two callers racing here duplicate one cheap
        // read rather than hanging.
        let parsed = self.text(Op::RemoteNames).and_then(|names| {
            let names: Vec<&str> = names.lines().collect();
            let listing = self.text(Op::RemoteUrls)?;
            reach::parse_remote_urls(&listing, &names)
        });
        let mut cache = self
            .reach_by_remote
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let answer = match parsed {
            Ok(urls) => {
                for (entry, urls) in urls {
                    cache.insert(entry, reach::classify(Ok(&urls)));
                }
                cache.get(&key).cloned().unwrap_or_else(|| {
                    let direction = match contact.direction {
                        Direction::Fetch => "fetch",
                        Direction::Push => "push",
                    };
                    reach::classify(Err(&CliError::new(format!(
                        "the listing shows no {direction} URL for remote {:?}",
                        contact.remote
                    ))))
                })
            }
            Err(err) => reach::classify(Err(&err)),
        };
        cache.insert(key, answer.clone());
        answer
    }

    /// A cache, so a torn entry is not a correctness problem: a poisoned lock is
    /// recovered rather than turned into a second panic that hides the first.
    fn remembered_reach(&self, key: &(String, Direction)) -> Option<reach::Reach> {
        self.reach_by_remote
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(key)
            .cloned()
    }

    /// Everything one child carries, whichever runner answers it.
    fn child(&self, shape: &OpShape<'_>) -> Result<Reply, CliError> {
        if let Some(held) = &self.held {
            super::repository::confirm_ambient(held, &self.repo)
                .map_err(|err| shape.fail(&err.to_string()))?;
        }
        // Every child carries the transport: git opens sockets on its own
        // schedule — a partial clone's `diff` lazily fetches over ssh from an
        // op typed local (measured) — so protection cannot key on the
        // classification, and an unreadable ssh configuration stops every
        // operation rather than guessing away the user's key or proxy.
        let batch = self
            .transport()
            .map_err(|unknown| shape.unreadable_transport(unknown))?;
        if let Some(contact) = shape.contact {
            // Unconditional: a helper remote owes its note even when the
            // transport composed, because `BatchMode` never reaches what
            // a helper runs.
            let reach = self.remote_reach(contact);
            for note in reach::notes_for(contact, &reach, batch) {
                self.say_once(&note);
            }
        }
        self.spawn(shape, batch)
    }

    /// Where the fake answers from its script; the transport and the notes
    /// reach it above.
    fn spawn(&self, shape: &OpShape<'_>, batch: &env::BatchSsh) -> Result<Reply, CliError> {
        let answered = match &self.runner {
            Runner::Child => {
                let args: Vec<&str> = shape.argv.iter().map(String::as_str).collect();
                let command = env::deadlined_command(&self.repo, &args, batch);
                let command = if self.offline || shape.spec.offline() {
                    command.without_lazy_fetch()
                } else {
                    command
                };
                command
                    .output(shape.input.as_deref().map(str::as_bytes))
                    .map(Reply::from)
            }
            #[cfg(test)]
            Runner::Fake(fake) => fake.answer(shape.name),
        };
        answered.map_err(|failure| {
            if failure.left_no_answer() {
                shape.no_answer(&failure.to_string())
            } else {
                shape.fail(&failure.to_string())
            }
        })
    }

    /// Separate from [`OpShape::fail`] because the child exited 0: a reader told
    /// that git "failed" checks the exit code, finds success, and concludes
    /// oakum is wrong.
    fn empty_answer(shape: &OpShape<'_>, reply: &Reply) -> CliError {
        shape.phrase(|what| match reply.diagnostic() {
            Some(said) => format!("git {what} answered nothing while reporting: {said}"),
            None => format!("git {what} exited 0 without answering"),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::env::{BatchSsh, TransportUnknown};
    use super::op::fixture_commit;
    use super::{parse_followed, split_nul_paths, Contact, Direction, Followed, Git, Op, Reply};

    /// As `git config --type=bool` reads each value (measured, git 2.56).
    #[test]
    fn a_promisor_is_whatever_git_reads_as_true() {
        for named in [
            "remote.origin.promisor\ntrue\0",
            "remote.origin.promisor\nTRUE\0",
            "remote.origin.promisor\n2\0",
            "remote.origin.promisor\n1k\0",
            "remote.origin.promisor\n0x1\0",
            "remote.origin.promisor\0",
            "remote.a.promisor\nfalse\0remote.origin.promisor\nyes\0",
            "extensions.partialclone\norigin\0",
        ] {
            assert!(super::names_a_promisor(named), "{named:?}");
        }
        for unnamed in [
            "",
            "remote.origin.promisor\nfalse\0",
            "remote.origin.promisor\n0\0",
            "remote.origin.promisor\n0k\0",
        ] {
            assert!(!super::names_a_promisor(unnamed), "{unnamed:?}");
        }
    }

    #[test]
    fn blobs_split_one_batch_by_size() {
        let git = Git::answering([(
            "cat-file --batch",
            Reply::said("o1 blob 4\na\nb\n\no2 blob 0\n\no3 blob 2\nhi\n"),
        )]);
        let texts = git
            .blobs(fixture_commit(), &["x.md", "y.md", "z.md"])
            .expect("texts");
        assert_eq!(texts, ["a\nb\n", "", "hi"]);
    }

    #[test]
    fn blobs_refuse_what_is_not_a_whole_file() {
        for (reply, why) in [
            ("o1 commit 3\nabc\n", "not a file"),
            (".changeset/x.md missing\n", "not a file"),
            ("o1 blob 9\nabc", "stopped inside"),
            ("o1 blob 3\nabcX", "stopped inside"),
            ("", "stopped before"),
        ] {
            let err = Git::answering([("cat-file --batch", Reply::said(reply))])
                .blobs(fixture_commit(), &["x.md"])
                .expect_err(reply);
            assert!(err.to_string().contains(why), "{reply:?}: {err}");
        }
    }

    #[test]
    fn blobs_ask_nothing_for_no_paths() {
        let git = Git::answering([]);
        assert_eq!(
            git.blobs(fixture_commit(), &[]).expect("empty"),
            Vec::<String>::new()
        );
        assert!(git.asked().is_empty(), "{:?}", git.asked());
    }

    #[test]
    fn commit_paths_splits_one_listing_by_commit() {
        let git = Git::answering([(
            "diff-tree --stdin",
            Reply::said("\u{1}a1\0\nx/lib.rs\0\nodd\0\u{1}c3\0\n\nlead\0"),
        )]);
        let paths = git.commit_paths(&["a1", "b2", "c3"]);
        assert_eq!(paths["a1"].as_deref().expect("a1"), ["x/lib.rs", "\nodd"]);
        assert!(paths["b2"].as_deref().expect("b2").is_empty(), "{paths:?}");
        assert_eq!(paths["c3"].as_deref().expect("c3"), ["\nlead"]);
    }

    #[test]
    fn a_batch_that_cannot_be_attributed_is_read_again_per_commit() {
        let git = Git::answering([
            ("diff-tree --stdin", Reply::said("\u{1}zz\0\nx\0")),
            ("diff-tree", Reply::said("x/lib.rs\0")),
        ]);
        let paths = git.commit_paths(&["a1"]);
        assert_eq!(
            paths["a1"].as_deref().expect("per-commit read"),
            ["x/lib.rs"]
        );
    }

    #[test]
    fn a_failed_batch_is_worded_as_the_per_commit_read() {
        let not_utf8 = || Reply::said(b"\x01a1\0\nbad\xff\0".to_vec());
        let alone = Git::answering([("diff-tree", Reply::said(b"bad\xff\0".to_vec()))])
            .paths(Op::CommitPath { hash: "a1" })
            .expect_err("not UTF-8");
        let paths = Git::answering([
            ("diff-tree --stdin", not_utf8()),
            ("diff-tree", Reply::said(b"bad\xff\0".to_vec())),
        ])
        .commit_paths(&["a1"]);
        let err = paths["a1"].as_ref().expect_err("not UTF-8");
        assert_eq!(err.to_string(), alone.to_string());
    }

    #[test]
    fn a_failed_batch_fails_only_the_commits_that_fail_alone() {
        let paths = Git::answering([
            (
                "diff-tree --stdin",
                Reply::said(b"\x01a1\0\nbad\xff\0".to_vec()),
            ),
            ("diff-tree", Reply::said(b"one\xff\0".to_vec())),
            ("diff-tree", Reply::said("b/lib.rs\0")),
        ])
        .commit_paths(&["a1", "b2"]);
        let err = paths["a1"].as_ref().expect_err("not UTF-8");
        assert!(err.to_string().contains("a1"), "{err}");
        assert_eq!(
            paths["b2"].as_deref().expect("b2 reads alone"),
            ["b/lib.rs"]
        );
    }

    #[test]
    fn commit_paths_asks_nothing_for_no_commits() {
        let git = Git::answering([]);
        assert!(git.commit_paths(&[]).is_empty());
        assert!(git.asked().is_empty(), "{:?}", git.asked());
    }

    #[test]
    fn a_path_holding_a_newline_is_refused_before_git_is_asked() {
        let git = Git::answering([]);
        let err = git
            .followed_blob(fixture_commit(), "pkg\nage/CHANGELOG.md")
            .expect_err("unframeable");
        assert!(err.to_string().starts_with("unverified: "), "{err}");
        assert!(git.said().is_empty(), "{:?}", git.said());
    }

    /// The replies measured from git 2.55's `cat-file --batch
    /// --follow-symlinks`.
    #[test]
    fn a_followed_blob_reply_reads_every_kind_git_answers() {
        let parse_followed = |reply: &[u8]| super::parse_followed(reply).map(|(kind, _)| kind);
        let oid = "45b983be36b73c0788dc9cbcb76cbb80fc7bb057";
        assert_eq!(
            parse_followed(format!("{oid} blob 3\nhi\n\n").as_bytes()),
            Some(Followed::File(b"hi\n".to_vec()))
        );
        assert_eq!(
            parse_followed(b"HEAD:my notes.md missing\n"),
            Some(Followed::Absent)
        );
        assert_eq!(
            parse_followed(b"dangling 9\nHEAD:DANG\n"),
            Some(Followed::Dangling)
        );
        for (reply, why) in [
            ("loop 10\nHEAD:LOOP1\n", "a symlink loop"),
            ("notdir 7\nHEAD:ND\n", "a path through a file"),
            (
                "symlink 6\n/etc/x\n",
                "a symlink git will not follow (absolute, or out of the repository)",
            ),
            (&*format!("{oid} tree 4\nabcd\n"), "not a file"),
        ] {
            assert_eq!(
                parse_followed(reply.as_bytes()),
                Some(Followed::Unfollowed(why)),
                "{reply}"
            );
        }
        for unframed in [
            format!("{oid} blob 9\nhi\n"),
            format!("{oid} blob x\nhi\n"),
            String::from("no newline"),
        ] {
            assert_eq!(parse_followed(unframed.as_bytes()), None, "{unframed}");
        }
    }

    #[test]
    fn followed_replies_are_read_one_after_another() {
        let oid = "45b983be36b73c0788dc9cbcb76cbb80fc7bb057";
        let stdout = format!("dangling 9\nHEAD:DANG\nHEAD:a b missing\n{oid} blob 3\nhi\n\n");
        let (first, rest) = parse_followed(stdout.as_bytes()).expect("first");
        let (second, rest) = parse_followed(rest).expect("second");
        let (third, rest) = parse_followed(rest).expect("third");
        assert_eq!(
            [first, second, third],
            [
                Followed::Dangling,
                Followed::Absent,
                Followed::File(b"hi\n".to_vec())
            ]
        );
        assert!(rest.is_empty(), "{rest:?}");
    }

    const SSH_URL: &str = "git@example.invalid:demo/demo.git";
    const HTTPS_URL: &str = "https://example.invalid/demo/demo.git";
    const HELPER_URL: &str = "ext::ssh -p 22 git@example.invalid %S demo.git";

    const WORKTREE: &str = "status --porcelain -z";

    /// `color.ui=always` colours git's own errors; the words are what a
    /// failed op quotes.
    #[test]
    fn a_failure_quotes_git_without_its_colour() {
        let reply = Reply::failed(128, "\u{1b}[31mfatal\u{1b}[0m: denied\r\n");
        assert_eq!(reply.detail(), "exit 128: fatal: denied");
    }

    /// The listing is short and git said why, so the look did not happen.
    #[test]
    fn a_whole_listing_that_names_unread_tree_is_refused() {
        let err = Git::answering([(
            WORKTREE,
            Reply::said_and_warned(
                " M alpha/src/lib.rs\0",
                "warning: could not open directory 'beta/hidden/': Permission denied",
            ),
        )])
        .paths(Op::UncommittedPaths)
        .expect_err("refused");
        assert_eq!(err.exit_code(), 2, "{err}");
        assert!(err.to_string().contains("only part of the tree"), "{err}");
    }

    /// The listing is whole and the warning is about something else, so the
    /// answer stands. Measured on git 2.55: an unreadable `.git/info/exclude`
    /// warns twice and lists byte-for-byte what a readable one lists, and
    /// refusing on it would fail the gate this repository runs in CI over a
    /// permission bit on an unrelated file.
    #[test]
    fn a_whole_listing_is_kept_when_the_warning_is_not_about_unread_tree() {
        assert_eq!(
            Git::answering([(
                WORKTREE,
                Reply::said_and_warned(
                    " M alpha/src/lib.rs\0",
                    "warning: unable to access '.git/info/exclude': Permission denied",
                ),
            )])
            .paths(Op::UncommittedPaths)
            .expect("kept"),
            [" M alpha/src/lib.rs"]
        );
    }

    /// `diff-lib.c` drops an index entry it cannot `lstat` through `perror`,
    /// a bare `<path>: <strerror>`. Measured on git 2.55 with the parent at
    /// mode 444: exit 0, and the modified file beneath reads as unmodified.
    #[test]
    fn a_whole_listing_beside_an_unprefixed_line_is_refused() {
        let err = Git::answering([(
            WORKTREE,
            Reply::said_and_warned(
                " M alpha/src/lib.rs\0",
                "beta/src/lib.rs: Permission denied",
            ),
        )])
        .paths(Op::UncommittedPaths)
        .expect_err("refused");
        assert_eq!(err.exit_code(), 2, "{err}");
        assert!(err.to_string().contains("only part of the tree"), "{err}");
    }

    /// Stderr that names no unread tree leaves a whole listing standing: each
    /// git message family, and the unprefixed lines git does not write
    /// itself — a wrapped warning's second line (measured, a negative pattern
    /// in `.gitattributes`) and a clean filter's own output (measured).
    #[test]
    fn a_line_that_names_no_unread_tree_is_kept() {
        for said in [
            "BUG: something odd",
            "error: something odd",
            "fatal: something odd",
            "hint: the hook was ignored because it is not executable",
            "note: something odd",
            "warning: unable to access '.git/info/exclude': Permission denied",
            "warning: Negative patterns are ignored in git attributes\nUse '\\!' for literal leading exclamation.",
            "chat: cleaning",
            "cat: optional-cache: Permission denied",
            "cat: /nonexistent: No such file or directory",
            "chat: access was Permission denied",
            "warning: x\n\nhint: y",
        ] {
            Git::answering([(
                WORKTREE,
                Reply::said_and_warned(" M alpha/src/lib.rs\0", said),
            )])
            .paths(Op::UncommittedPaths)
            .expect(said);
        }
    }

    /// The empty-stdout sibling of the test above, and the only test that
    /// tells this operation's two axes apart by behavior — the axis table
    /// states them, and nothing in `tests/it/check/` reads the difference. A listing
    /// that says something exits through the `spoke` shortcut before the
    /// silence rule is read, so only an empty one reaches `Answer::Never`
    /// here. A clean tree beside a warning the wholeness rule passes over is a
    /// clean tree; reading that silence as `Answer::Sometimes` would refuse it,
    /// which is the gate this repository runs in CI failing over a permission
    /// bit.
    #[test]
    fn a_clean_tree_is_kept_when_the_warning_is_not_about_unread_tree() {
        let kept = Git::answering([(
            WORKTREE,
            Reply::warned("warning: unable to access '.git/info/exclude': Permission denied"),
        )])
        .paths(Op::UncommittedPaths)
        .expect("a clean tree that warned benignly is still a clean tree");
        assert!(kept.is_empty(), "{kept:?}");
    }

    /// Every spelling the set holds, whether or not `status` reaches it: the
    /// matcher is what is under test here, and a case-sensitive one reaches
    /// five of the seven. Not every shortening `status` can report —
    /// [`hides_part_of_the_tree`] names the `perror` shape the set does not
    /// hold. Two spellings elsewhere in the binary go unmatched deliberately:
    /// `refs/files-backend.c`'s `cannot open directory` is reachable only from
    /// `fsck`, and `prune`'s `Unable to open directory` walks the object store.
    #[test]
    fn every_shape_of_unread_tree_is_recognised() {
        for said in [
            "cannot lstat 'beta/x'",
            "Cannot lstat 'beta/x'",
            "cannot opendir 'beta/hidden'",
            "cannot opendir beta/hidden",
            "warning: could not open directory 'beta/hidden/': Permission denied",
            "Could not open directory beta/hidden",
            "opendir('beta/hidden') failed",
        ] {
            let err = Git::answering([(
                WORKTREE,
                Reply::said_and_warned(" M alpha/src/lib.rs\0", said),
            )])
            .paths(Op::UncommittedPaths)
            .expect_err(said);
            assert!(
                err.to_string().contains("only part of the tree"),
                "{said}: {err}"
            );
        }
    }

    /// A child that failed listed none of the tree, not part of it, so it takes
    /// the failure wording rather than the truncation wording — both are exit
    /// 2, which is why asserting the class alone would not tell them apart.
    ///
    /// The diagnostic has to name unread tree for this to discriminate:
    /// against stderr the set does not match, dropping the `succeeded` gate
    /// leaves the wording right by accident.
    #[test]
    fn a_whole_listing_that_failed_outright_is_not_called_partial() {
        let err = Git::answering([(
            WORKTREE,
            Reply::failed(128, "fatal: cannot opendir 'beta/hidden'"),
        )])
        .paths(Op::UncommittedPaths)
        .expect_err("refused");
        assert_eq!(err.exit_code(), 2, "{err}");
        assert!(err.to_string().contains("failed: exit 128"), "{err}");
        assert!(
            !err.to_string().contains("only part of the tree"),
            "it listed none of it: {err}"
        );
    }

    /// A scripted `Git` whose one remote, `origin`, lists `url` both ways, so
    /// a remote child finds the listing its notes read.
    fn at_remote(url: &str, replies: impl IntoIterator<Item = (&'static str, Reply)>) -> Git {
        Git::answering(listing(url).into_iter().chain(replies))
    }

    fn listing(url: &str) -> [(&'static str, Reply); 2] {
        [
            ("remote", Reply::said("origin")),
            (
                "remote -v",
                Reply::said(format!("origin\t{url} (fetch)\norigin\t{url} (push)")),
            ),
        ]
    }

    fn advertised() -> (&'static str, Reply) {
        ("ls-remote --tags", Reply::said("cafe\trefs/tags/v1.0.0\n"))
    }

    /// A transport `BatchMode` cannot reach, with the reason the probe gives.
    fn opaque() -> BatchSsh {
        BatchSsh::Unprotected(String::from(
            "GIT_SSH names `my-ssh`, which takes its arguments from git, not from oakum",
        ))
    }

    /// The shapes below all arrive as "git exited non-zero" or "git printed
    /// nothing", and telling them apart is the whole of the three-outcome rule.
    /// A real repository produces them only through a shell shim on `PATH`,
    /// which `tests/it/check/` does and which runs on unix alone.
    #[test]
    fn exit_one_with_nothing_written_is_how_git_says_absent() {
        assert_eq!(
            Git::answering([("config --get-regexp url|tagopt|fetch", Reply::absent())])
                .optional_text(Op::RemoteTagConfig)
                .expect("absent"),
            None
        );
        assert!(!Git::answering([("rev-parse --verify", Reply::absent())])
            .predicate(Op::RefExists {
                reference: "refs/tags/v1.0.0",
            })
            .expect("absent"));
    }

    /// The other three ways a child can exit without answering. Each was a
    /// surviving mutant: drop any conjunct of `said_no` and a git that could not
    /// look reports "absent", which decides whether a tag exists.
    #[test]
    fn only_exit_one_with_both_streams_empty_means_absent() {
        let diagnosed = Git::answering([(
            "config --get-regexp url|tagopt|fetch",
            Reply::failed(1, "fatal: not a git repository"),
        )])
        .optional_text(Op::RemoteTagConfig)
        .expect_err("a diagnosed exit must not read as absence");
        assert!(diagnosed.is_unverified(), "{diagnosed:?}");
        assert!(
            diagnosed.to_string().contains("not a git repository"),
            "{diagnosed}"
        );

        let silent = Git::answering([(
            "config --get-regexp url|tagopt|fetch",
            Reply::exactly(Some(128), b"", b""),
        )])
        .optional_text(Op::RemoteTagConfig)
        .expect_err("exit 128 is not exit 1");
        assert!(silent.to_string().contains("exit 128"), "{silent}");

        let spoke = Git::answering([(
            "config --get-regexp url|tagopt|fetch",
            Reply::exactly(Some(1), b"remote.origin.tagopt --no-tags", b""),
        )])
        .optional_text(Op::RemoteTagConfig)
        .expect_err("a child that wrote an answer did not say no");
        assert!(spoke.to_string().contains("exit 1"), "{spoke}");

        let killed = Git::answering([("rev-parse --verify", Reply::was_signalled())])
            .predicate(Op::RefExists {
                reference: "refs/tags/v1.0.0",
            })
            .expect_err("a signal is not an answer of no");
        assert!(
            killed.to_string().contains("terminated by a signal"),
            "{killed}"
        );
    }

    /// A cached failure is handed to later callers unchanged, and the class is
    /// decided where it is needed rather than carried: an operation that wanted
    /// the transport reports `unverified`, one that did not says it plainly.
    #[test]
    fn a_cached_transport_failure_is_repeated_verbatim() {
        let git = Git::at("/nonexistent");
        git.transport
            .set(
                Err(super::env::TransportUnknown::SshConfig(String::from(
                    "git config was killed by a signal",
                )))
                .into(),
            )
            .expect("the cache starts empty");
        for _ in 0..3 {
            assert_eq!(
                git.transport().expect_err("a cached failure").detail(),
                "git config was killed by a signal"
            );
        }
        let raised = Op::AdvertisedTags { remote: "origin" }
            .shape()
            .unreadable_transport(&super::env::TransportUnknown::SshConfig(String::from(
                "git config was killed by a signal",
            )));
        assert!(raised.is_unverified(), "{raised:?}");
        assert!(
            raised.to_string().contains("killed by a signal"),
            "{raised}"
        );
    }

    /// Git's trace settings write to stderr unless pointed at a file, and every
    /// rule above treats stderr as a diagnostic. Measured on git 2.55: `1`,
    /// `2`, and `true` all print to stderr, an unrecognised value warns and
    /// then prints to stderr, and only an absolute path is written to a file.
    #[test]
    fn only_a_trace_that_names_a_file_is_left_in_place() {
        for value in ["1", "2", "true", "relative.log", ""] {
            assert!(
                !super::traces_to_a_file(std::ffi::OsStr::new(value)),
                "{value:?} reaches our stderr"
            );
        }
        let file = std::env::temp_dir().join("oakum-trace.event");
        assert!(super::traces_to_a_file(file.as_os_str()));
    }

    /// Asserted against the command `untrace` actually builds. Written against
    /// its own literals instead, this test passed with `untrace` gutted to an
    /// empty body — the whole suite did.
    #[test]
    fn untrace_silences_every_channel_and_leaves_the_rest_alone() {
        let file = std::env::temp_dir().join("oakum-trace.perf");
        let inherited = [
            (
                std::ffi::OsString::from("GIT_TRACE"),
                std::ffi::OsString::from("1"),
            ),
            (
                std::ffi::OsString::from("GIT_TRACE_PACKET"),
                std::ffi::OsString::from("1"),
            ),
            (
                std::ffi::OsString::from("GIT_TRACE_A_CHANNEL_ADDED_LATER"),
                std::ffi::OsString::from("1"),
            ),
            (
                std::ffi::OsString::from("GIT_TRACE2_EVENT"),
                std::ffi::OsString::from("relative.log"),
            ),
            (
                std::ffi::OsString::from("GIT_TRACE2_PERF"),
                file.into_os_string(),
            ),
        ];
        let mut command = std::process::Command::new("git");
        command.env("GIT_TERMINAL_PROMPT", "0");
        super::untrace_from(&mut command, inherited);

        let envs: Vec<(String, Option<String>)> = command
            .get_envs()
            .map(|(name, value)| {
                (
                    name.to_string_lossy().into_owned(),
                    value.map(|value| value.to_string_lossy().into_owned()),
                )
            })
            .collect();
        let setting = |name: &str| {
            envs.iter()
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.clone())
        };

        // Removed outright, including one nobody enumerated.
        for name in [
            "GIT_TRACE",
            "GIT_TRACE_PACKET",
            "GIT_TRACE_A_CHANNEL_ADDED_LATER",
        ] {
            assert_eq!(setting(name), Some(None), "{name} still reaches the child");
        }
        // Trace2 is set off rather than removed, because git config can turn it
        // back on where an environment edit cannot reach.
        assert_eq!(
            setting("GIT_TRACE2_EVENT"),
            Some(Some(String::from("0"))),
            "config-driven trace2 is still live"
        );
        // A trace2 channel the caller pointed at a file is left entirely alone —
        // the answer has to come from the environment handed in, not the
        // process's own, or an exported value decides for an environment that
        // never mentioned it.
        assert_eq!(
            setting("GIT_TRACE2_PERF"),
            None,
            "a trace2 file target was overridden"
        );
        assert_eq!(
            setting("GIT_TERMINAL_PROMPT"),
            Some(Some(String::from("0")))
        );
    }

    /// And matching stops at token boundaries. `RefExists` asks for
    /// `refs/tags/v1.0.0`; `LocalTagCommit` asks for the same string with
    /// `^{}` appended, so a character-wise prefix would let a script for one
    /// answer the other's child — the substitution this fake exists to expose.
    #[test]
    #[should_panic(expected = "nothing scripted answers")]
    fn a_command_that_only_shares_a_character_prefix_does_not_answer() {
        let git = Git::answering([(
            "rev-parse --verify --quiet refs/tags/v1.0.0",
            Reply::said("cafebabe"),
        )]);
        let _ = git.optional_text(Op::LocalTagCommit { tag: "v1.0.0" });
    }

    /// One of the two rules: a child that always prints and printed nothing did
    /// not answer, whatever it exited with. Keying this on the outcome class
    /// left it off `predicate` and `optional_text` entirely, which is how a
    /// config read that never ran came back as "no remote suppresses tags".
    #[test]
    fn a_child_that_always_prints_and_printed_nothing_is_refused_on_every_accessor() {
        let warning = "warning: unable to access '/etc/gitconfig': Permission denied";
        let asked = Git::answering([(
            "config --get-regexp url|tagopt|fetch",
            Reply::warned(warning),
        )])
        .optional_text(Op::RemoteTagConfig)
        .expect_err("optional_text");
        assert!(asked.is_unverified(), "{asked:?}");
        assert!(asked.to_string().contains("Permission denied"), "{asked}");

        let voted = Git::answering([("rev-parse --verify", Reply::warned(warning))])
            .predicate(Op::RefExists {
                reference: "refs/tags/v1.0.0",
            })
            .expect_err("predicate");
        assert!(voted.to_string().contains("answered nothing"), "{voted}");

        let read = Git::answering([("rev-parse HEAD", Reply::warned(warning))])
            .text(Op::Head)
            .expect_err("text");
        assert!(read.to_string().contains("Permission denied"), "{read}");

        // Nothing on either stream: `rev-parse --verify --quiet` reports absence
        // as exit 1, so exit 0 in silence is a wrapper, not an answer.
        let mute = Git::answering([(
            "config --get-regexp url|tagopt|fetch",
            Reply::exactly(Some(0), b"", b""),
        )])
        .optional_text(Op::RemoteTagConfig)
        .expect_err("silence is not absence");
        assert!(
            mute.to_string().contains("exited 0 without answering"),
            "{mute}"
        );
    }

    /// The second rule. `for-each-ref` legitimately prints nothing — a
    /// repository can have no reachable tags — but a diagnostic alongside that
    /// silence means the emptiness was never established (ADR-0014).
    #[test]
    fn a_verification_that_reported_nothing_while_warning_is_not_an_empty_look() {
        let err = Git::answering([(
            "for-each-ref --merged HEAD",
            Reply::warned("warning: refname 'v1.0.0' is ambiguous"),
        )])
        .text(Op::ReachableTags)
        .expect_err("a warned look must not read as no tags");
        assert!(err.is_unverified(), "{err:?}");
        assert!(err.to_string().contains("ambiguous"), "{err}");
    }

    /// `Answer::Sometimes`: the emptiness is a real answer, and a diagnostic
    /// alongside it is not. These two gate `oakum release`, and a `status` or
    /// `log` that never ran must not read as "clean" and "no skip-ci marker".
    #[test]
    fn a_refusal_gate_that_never_looked_is_not_a_clean_answer() {
        for (command, op) in [
            ("status --porcelain", Op::WorktreeStatus),
            ("log -1", Op::CommitMessage { commit: "HEAD" }),
            (
                "diff-tree --stdin",
                Op::CommitPaths {
                    hashes: &["cafebabe"],
                },
            ),
        ] {
            let err = Git::answering([(command, Reply::warned("fatal: could not read index"))])
                .text(op)
                .expect_err("{op:?} must not read as an empty answer");
            assert!(err.to_string().contains("could not read index"), "{err}");
        }
    }

    /// `Answer::Never`: silence proves nothing either way, so no rule is drawn
    /// from it. A successful `git push` writes its whole report to stderr and
    /// nothing to stdout, and `check-ref-format` writes nothing on either
    /// verdict — refusing these would fail every release.
    #[test]
    fn work_that_answers_through_its_exit_code_is_not_refused_for_writing_to_stderr() {
        at_remote(
            SSH_URL,
            [(
                "push",
                Reply::warned("To github.com:oakoss/oakum.git\n * [new tag] v1.0.0 -> v1.0.0"),
            )],
        )
        .run(Op::PushTag {
            remote: "origin",
            tag: "v1.0.0",
        })
        .expect("push reports through stderr on success");

        assert!(Git::answering([(
            "check-ref-format",
            Reply::warned("warning: unable to access '/etc/gitconfig'"),
        )])
        .predicate(Op::ValidRefName {
            reference: "v1.0.0",
        })
        .expect("check-ref-format reports through its exit code"));
    }

    /// A path git listed but oakum cannot read as UTF-8 fails in the
    /// operation's own voice rather than being lossily rewritten into a path
    /// that misses its package. `split_nul_paths` refusing the record is
    /// tested directly; this drives one through the accessor.
    #[test]
    fn a_non_utf8_path_fails_in_the_operations_own_voice() {
        let err = Git::answering([("diff --name-only", Reply::said(b"pkg/\xff.bin\0".to_vec()))])
            .paths(Op::ChangedPaths { from: "v1.0.0" })
            .expect_err("a non-UTF-8 path cannot name a package");
        assert!(
            err.to_string().contains("cannot attribute it to a package"),
            "{err}"
        );
        assert!(
            err.is_unverified(),
            "`diff --name-only` is a verification: {err:?}"
        );
    }

    /// The guard asks the accessor doing the reading, because the two draw the
    /// line in different places and one rule is wrong for one of them. `text`
    /// trims — `str::trim`, so Unicode `White_Space`, not the ASCII subset —
    /// while `paths` keeps every non-empty NUL record byte-for-byte.
    #[test]
    fn each_accessor_draws_the_silence_line_where_it_reads() {
        // Silence to `str::trim`, an answer to anything narrower: a vertical
        // tab, a no-break space, a line separator. `\x0B` is the one that was
        // live — `u8::is_ascii_whitespace` rejects it, and a `status` writing it
        // alongside a fatal passed the dirty-worktree gate.
        for stdout in ["\u{0B}", "\u{A0}", "\u{2028}"] {
            let err = Git::answering([(
                "status --porcelain",
                Reply::exactly(
                    Some(0),
                    stdout.as_bytes(),
                    b"fatal: could not read the index",
                ),
            )])
            .text(Op::WorktreeStatus)
            .expect_err("whitespace is not a clean worktree");
            assert!(
                err.to_string().contains("could not read the index"),
                "{err}"
            );
        }

        // `-z` turns quoting off, so a file named " " arrives as a one-byte
        // record and is a filename, not silence. Only a genuinely empty record
        // means nothing was listed.
        let listed = Git::answering([(
            "diff --name-only",
            Reply::exactly(
                Some(0),
                b" \0",
                b"warning: unable to access '/etc/gitconfig'",
            ),
        )])
        .paths(Op::ChangedPaths { from: "v1.0.0" })
        .expect("a whitespace filename is a filename");
        assert_eq!(listed, [" "]);

        let none = Git::answering([(
            "diff --name-only",
            Reply::exactly(
                Some(0),
                b"\0\0",
                b"warning: unable to access '/etc/gitconfig'",
            ),
        )])
        .paths(Op::ChangedPaths { from: "v1.0.0" })
        .expect_err("empty records listed nothing");
        assert!(none.to_string().contains("answered nothing"), "{none}");

        let absent = Git::answering([("rev-parse --verify refs/tags", Reply::said("  \n"))])
            .optional_text(Op::LocalTagCommit { tag: "v1.0.0" })
            .expect_err("whitespace is not a commit");
        assert!(absent.to_string().contains("without answering"), "{absent}");

        // The same trimming on the other stream: a diagnostic of only
        // whitespace has reported nothing, so an empty look stays an answer.
        assert_eq!(
            Git::answering([("remote", Reply::exactly(Some(0), b"", b" \n"))])
                .text(Op::RemoteNames)
                .expect("a blank diagnostic is not a diagnostic"),
            ""
        );
    }

    /// Every accessor trims, so a lone newline reaches the caller as `""`. The
    /// guard has to judge emptiness the same way or it is one byte wide.
    #[test]
    fn whitespace_on_stdout_is_not_an_answer() {
        let err = Git::answering([(
            "config --get-regexp url|tagopt|fetch",
            Reply::exactly(Some(0), b" \n\t", b"fatal: bad config line 9"),
        )])
        .optional_text(Op::RemoteTagConfig)
        .expect_err("whitespace is not an answer");
        assert!(err.to_string().contains("bad config line 9"), "{err}");

        let looked = Git::answering([(
            "status --porcelain",
            Reply::exactly(Some(0), b"\n", b"fatal: could not read index"),
        )])
        .text(Op::WorktreeStatus)
        .expect_err("nor for a gate whose empty answer means clean");
        assert!(
            looked.to_string().contains("could not read index"),
            "{looked}"
        );
    }

    /// The other side of the same rule, and the reason it is not simply "any
    /// stderr is a failure". Both shapes are ones git produces: `for-each-ref`
    /// lists the tags beside a warning that skipped none of them, and a
    /// successful `git push` writes its whole report to stderr.
    #[test]
    fn a_child_that_answered_or_had_nothing_to_answer_is_not_refused() {
        let listed = Git::answering([(
            "for-each-ref --merged HEAD",
            Reply::said_and_warned(
                "refs/tags/v1.0.0\0commit\0cafebabe\0\0",
                "warning: unable to access '/home/u/.config/git/attributes': Permission denied",
            ),
        )])
        .text(Op::ReachableTags)
        .expect("a warning alongside an answer leaves the answer standing");
        assert!(listed.contains("v1.0.0"), "{listed}");

        at_remote(
            SSH_URL,
            [(
                "push",
                Reply::warned("To github.com:oakoss/oakum.git\n * [new tag] v1.0.0"),
            )],
        )
        .run(Op::PushTag {
            remote: "origin",
            tag: "v1.0.0",
        })
        .expect("push reports through stderr on success");
    }

    /// git skips a tag ref it cannot read, lists the rest and exits 0, so the
    /// listing is short by one tag that may be the last release (measured,
    /// git 2.55: 11 of 12 tags beside this warning).
    #[test]
    fn a_tag_listing_that_skipped_a_broken_ref_is_refused() {
        for (op, name, listed) in [
            (
                Op::ReachableTags,
                "for-each-ref --merged HEAD",
                "refs/tags/v1.0.0\0commit\0cafebabe\0\0",
            ),
            (
                Op::AllTags,
                "for-each-ref refs/tags",
                "refs/tags/v1.0.0\0cafebabe",
            ),
        ] {
            let err = Git::answering([(
                name,
                Reply::said_and_warned(listed, "warning: ignoring broken ref refs/tags/v2.0.0"),
            )])
            .text(op)
            .expect_err("a skipped tag leaves the listing short");
            assert!(
                err.to_string()
                    .contains("ignoring broken ref refs/tags/v2.0.0"),
                "{err}"
            );
            assert!(err.to_string().contains("some of the refs"), "{err}");
            assert!(!err.to_string().contains("part of the tree"), "{err}");
            assert!(err.is_unverified(), "{err:?}");
        }
    }

    #[test]
    fn a_silent_failure_and_a_signal_do_not_render_alike() {
        let silent = Git::answering([("rev-parse HEAD", Reply::exactly(Some(128), b"", b""))])
            .text(Op::Head)
            .expect_err("exit 128");
        assert!(
            silent.to_string().contains("exit 128 with no diagnostic"),
            "{silent}"
        );
        let killed = Git::answering([("rev-parse HEAD", Reply::was_signalled())])
            .text(Op::Head)
            .expect_err("signalled");
        assert!(
            killed.to_string().contains("terminated by a signal"),
            "{killed}"
        );
        // `git push` writes its success banner to stderr before a signal can
        // kill it; the banner must not stand in for the death (measured — the
        // banner alone was the whole reported reason).
        let banner = at_remote(
            SSH_URL,
            [(
                "push",
                Reply::exactly(None, b"", b"To /private/tmp/origin.git\n"),
            )],
        )
        .run(Op::PushTag {
            remote: "origin",
            tag: "v1.0.0",
        })
        .expect_err("a signal death with stderr");
        assert!(
            banner.to_string().contains("terminated by a signal"),
            "{banner}"
        );
        assert!(
            banner.to_string().contains("To /private/tmp/origin.git"),
            "git's words stay as evidence: {banner}"
        );
    }

    /// `Spec::lossy` decides this, and both sides of it are worth pinning: a
    /// commit message survives a stray byte, an object name does not.
    #[test]
    fn only_a_lossy_read_accepts_bytes_that_are_not_utf8() {
        let message = Git::answering([("log -1", Reply::said(b"fix: caf\xff\n".to_vec()))])
            .text(Op::CommitMessage { commit: "HEAD" })
            .expect("a commit message is read lossily");
        assert_eq!(message, "fix: caf\u{fffd}");
        let err = Git::answering([("rev-parse HEAD", Reply::said(b"\xff".to_vec()))])
            .text(Op::Head)
            .expect_err("an object name must be valid UTF-8");
        assert!(err.to_string().contains("not valid UTF-8"), "{err}");
    }

    /// A failed action stays a plain error even though the same runner handles
    /// the verifications above.
    #[test]
    fn a_failed_action_is_not_unverified() {
        let err = Git::answering([("tag", Reply::failed(128, "fatal: tag already exists"))])
            .run(Op::AnnotatedTag {
                name: "v1.0.0",
                commit: fixture_commit(),
            })
            .expect_err("tag failed");
        assert!(!err.is_unverified(), "{err:?}");
    }

    /// oakum empties the askpass chain on every git child, so a credential
    /// failure there is a state oakum caused; the report must name the way
    /// out while keeping git's text as the evidence.
    #[test]
    fn a_credential_starved_remote_failure_names_the_fix() {
        // One case per matched phrasing, each carrying only its own pattern,
        // so dropping any single arm fails a distinct assertion.
        for starved in [
            "fatal: could not read Username for 'https://gitlab.com': prompts off",
            "fatal: could not read Password for 'https://gitlab.com': prompts off",
            "fatal: Authentication failed for 'https://gitlab.com/'",
            "fatal: Username not available: terminal prompts disabled",
        ] {
            let err = at_remote(
                HTTPS_URL,
                [("ls-remote --tags", Reply::failed(128, starved))],
            )
            .text(Op::AdvertisedTags { remote: "origin" })
            .expect_err("a starved remote read fails");
            let text = err.to_string();
            assert!(text.contains(starved), "{text}");
            assert!(text.contains("credential helper"), "{text}");
            assert!(text.contains("gh auth setup-git"), "{text}");
            assert!(text.starts_with("unverified:"), "{text}");
        }

        let err = at_remote(
            SSH_URL,
            [(
                "ls-remote --tags",
                Reply::failed(128, "fatal: repository not found"),
            )],
        )
        .text(Op::AdvertisedTags { remote: "origin" })
        .expect_err("an unrelated remote failure");
        assert!(!err.to_string().contains("credential helper"), "{err}");

        let starved =
            "fatal: could not read Username for 'https://gitlab.com': terminal prompts disabled";
        let err = Git::answering([("log -1", Reply::failed(128, starved))])
            .text(Op::CommitMessage { commit: "HEAD" })
            .expect_err("a local child never gets the note");
        assert!(!err.to_string().contains("credential helper"), "{err}");
    }

    /// An old git echoes the trailer atom verbatim; a genuine trailer value
    /// quoting the atom also reproduces it — the difference is that the
    /// genuine one carries the atom in the message half too.
    #[test]
    fn the_unparsed_trailer_guard_spares_a_value_that_quotes_the_atom() {
        let old_git = Git::answering([(
            "log -1",
            Reply::said(format!("chore: release\0{}\n", super::SKIP_CHECKS_ATOM)),
        )]);
        let err = old_git.commit_text("cafe").expect_err("old git refuses");
        assert!(err.to_string().contains("did not parse"), "{err}");

        let quoting = Git::answering([(
            "log -1",
            Reply::said(format!(
                "chore: x\n\nskip-checks: {atom}\0{atom}\n",
                atom = super::SKIP_CHECKS_ATOM
            )),
        )]);
        let text = quoting
            .commit_text("cafe")
            .expect("a quoting value is a value");
        assert_eq!(text.skip_checks.trim(), super::SKIP_CHECKS_ATOM);
    }

    /// A remote the listing does not name was never looked at, and "we didn't
    /// look" must not become "it's fine": the fallback is unread, not safe.
    #[test]
    fn an_unlisted_remote_is_unread_not_safe() {
        let git = Git::answering([
            ("remote", Reply::said("other")),
            (
                "remote -v",
                Reply::said("other\thttps://host/r.git (fetch)"),
            ),
        ]);
        let reach = git.remote_reach(Contact {
            remote: "origin",
            direction: Direction::Fetch,
        });
        let unread = reach.unread.expect("an unlisted remote is unread");
        assert!(!reach.ssh && !reach.helper);
        assert!(
            unread.to_string().contains("shows no fetch URL"),
            "{unread}"
        );
    }

    /// A refused write leaves the note owed, so the next remote child says it.
    #[test]
    fn a_refused_note_stays_owed_until_it_lands() {
        let git = Git::answering([]);

        let mut offered = String::new();
        assert!(
            !git.say_once_with("a note", |note| {
                offered.push_str(note);
                false
            }),
            "a refused write must not report the note as said"
        );
        assert_eq!(offered, "a note", "the sayer is given the note verbatim");

        assert!(
            git.say_once_with("a note", |_| true),
            "a refused note is still owed, so the next child may say it"
        );
        assert!(
            !git.say_once_with("a note", |_| panic!("said twice")),
            "once it lands it must not repeat, once per remote child"
        );
    }

    /// A remote that pushes elsewhere owes two notes, not one — while the
    /// byte-identical note, owed by both directions, says itself once.
    #[test]
    fn distinct_notes_say_themselves_and_identical_ones_do_not_repeat() {
        let git = Git::answering([]);
        assert!(git.say_once_with("fetch note", |_| true));
        assert!(git.say_once_with("push note", |_| true));
        assert!(!git.say_once_with("fetch note", |_| panic!("repeated")));
    }

    /// A transport oakum could not read stops every child before it spawns,
    /// in the operation's own outcome class: a verification that could not
    /// look is `unverified`, a push that never ran is a plain failure, and a
    /// local read stops too, because git dials sockets from local-classed
    /// children. Refusing after the spawn would read the same from stderr and
    /// still be the prompt hang.
    #[test]
    fn an_unreadable_transport_stops_every_child_before_it_spawns() {
        let git = Git::answering_over(
            Err(TransportUnknown::SshConfig(String::from(
                "fatal: unable to read config file",
            ))),
            [
                advertised(),
                ("push", Reply::warned("To example.invalid:demo/demo.git")),
                ("log -1", Reply::said("fix: typo\0\n")),
            ],
        );

        let looked = git
            .text(Op::AdvertisedTags { remote: "origin" })
            .expect_err("a look whose transport could not be resolved");
        assert!(looked.is_unverified(), "{looked:?}");
        let text = looked.to_string();
        assert!(
            text.contains(
                "git ls-remote --tags origin needs an ssh configuration oakum could not read"
            ),
            "{text}"
        );
        assert!(text.contains("unable to read config file"), "{text}");
        assert!(text.contains("will not guess a transport"), "{text}");

        let acted = git
            .run(Op::PushTag {
                remote: "origin",
                tag: "v1.0.0",
            })
            .expect_err("a push that never ran");
        assert!(!acted.is_unverified(), "{acted:?}");

        let local = git
            .commit_text("HEAD")
            .expect_err("a local child carries the transport too");
        assert!(
            local
                .to_string()
                .contains("git log -1 HEAD needs an ssh configuration"),
            "{local}"
        );

        assert!(
            git.asked().is_empty(),
            "no child may spawn without a resolved transport: {:?}",
            git.asked()
        );
        assert!(git.said().is_empty(), "{:?}", git.said());
    }

    /// The remote listing is read for the child that contacts a remote, not
    /// for every child: a local read that asked for it would spawn two extra
    /// children per run — and, with the notes unchanged, pass every test that
    /// reads only the notes.
    #[test]
    fn a_local_child_reads_no_remote_listing() {
        let git = Git::answering([("log -1", Reply::said("fix: typo\0\n"))]);
        git.commit_text("HEAD").expect("a local read");
        assert_eq!(git.asked(), ["log -1"]);
        assert!(git.said().is_empty(), "{:?}", git.said());
    }

    /// A helper remote owes its note under every transport: `BatchMode` never
    /// reaches what a helper runs, so a composed transport is not evidence the
    /// remote is safe, and "does not reach ssh" would assert something untrue.
    /// oakum read this URL fine; what it could not establish is the transport.
    #[test]
    fn a_helper_remote_owes_its_note_under_a_composed_transport() {
        let git = at_remote(HELPER_URL, [advertised()]);
        git.text(Op::AdvertisedTags { remote: "origin" })
            .expect("the look runs; the note is advisory");
        let said = git.said();
        assert_eq!(said.len(), 1, "{said:?}");
        assert!(
            said[0].contains("\"origin\" runs a helper command oakum cannot inspect"),
            "{said:?}"
        );
        assert!(
            !said[0].contains("could not be protected"),
            "a composed transport owes no transport rider: {said:?}"
        );
        assert!(
            !said[0].contains("could not read that remote's URL"),
            "the note must not claim a read failed when it did not: {said:?}"
        );
    }

    /// The note about ssh prompts is gated on the remote's URL, not on the
    /// transport alone: the transport resolves from the environment before any
    /// URL is known, and gating on it alone printed the note for an `https://`
    /// remote, where ssh is never invoked. The ssh remote is the control — an
    /// absent note reads the same when no note is ever said.
    #[test]
    fn only_an_ssh_remote_is_told_about_ssh_prompts() {
        let quiet = Git::answering_over(
            Ok(opaque()),
            listing(HTTPS_URL).into_iter().chain([advertised()]),
        );
        quiet
            .text(Op::AdvertisedTags { remote: "origin" })
            .expect("an https look");
        assert_eq!(
            quiet.asked(),
            ["remote", "remote -v", "ls-remote --tags"],
            "an absent note reads the same when no remote child ran"
        );
        assert!(quiet.said().is_empty(), "{:?}", quiet.said());

        let told = Git::answering_over(
            Ok(opaque()),
            listing(SSH_URL).into_iter().chain([advertised()]),
        );
        told.text(Op::AdvertisedTags { remote: "origin" })
            .expect("an ssh look");
        let said = told.said();
        assert_eq!(said.len(), 1, "{said:?}");
        assert!(
            said[0].contains("cannot refuse ssh prompts for the transport \"origin\" uses"),
            "{said:?}"
        );
        assert!(said[0].contains("GIT_SSH names `my-ssh`"), "{said:?}");
    }

    /// One listing per run and one note per text, under the seam: the reach
    /// is cached for every remote the listing names, and a note owed by two
    /// children lands once.
    #[test]
    fn the_listing_is_read_once_and_a_note_said_once_per_run() {
        let git = at_remote(
            HELPER_URL,
            [
                advertised(),
                ("push", Reply::warned("To example.invalid:demo/demo.git")),
            ],
        );
        git.text(Op::AdvertisedTags { remote: "origin" })
            .expect("the look");
        git.run(Op::PushTag {
            remote: "origin",
            tag: "v1.0.0",
        })
        .expect("the push");
        assert_eq!(
            git.asked(),
            ["remote", "remote -v", "ls-remote --tags", "push"]
        );
        assert_eq!(git.said().len(), 1, "{:?}", git.said());
    }

    /// A URL oakum could not read is unestablished rather than not-ssh. The
    /// note is advisory, so it is still said: hedged, naming the remote,
    /// carrying git's reason, and saying the read failed rather than claiming
    /// the remote is ssh. Under a composed transport the hedge stays, because
    /// oakum cannot rule a helper out, without the transport rider.
    #[test]
    fn an_unreadable_listing_still_gets_a_hedged_note() {
        let unread = |transport| {
            Git::answering_over(
                transport,
                [
                    ("remote", Reply::said("origin")),
                    ("remote -v", Reply::failed(2, "fatal: unreadable")),
                    advertised(),
                ],
            )
        };

        let unprotected = unread(Ok(opaque()));
        unprotected
            .text(Op::AdvertisedTags { remote: "origin" })
            .expect("the look still runs");
        let said = unprotected.said();
        assert_eq!(said.len(), 1, "{said:?}");
        assert!(
            said[0].contains("could not establish what transport \"origin\" uses"),
            "{said:?}"
        );
        assert!(
            said[0].contains("could not read that remote's URL"),
            "{said:?}"
        );
        assert!(said[0].contains("fatal: unreadable"), "{said:?}");
        assert!(
            said[0].contains("could not be protected either: GIT_SSH names"),
            "{said:?}"
        );
        assert!(
            !said[0].contains("cannot refuse ssh prompts"),
            "an unread URL is not an ssh URL: {said:?}"
        );

        let composed = unread(Ok(BatchSsh::Composed(String::from("ssh -o BatchMode=yes"))));
        composed
            .text(Op::AdvertisedTags { remote: "origin" })
            .expect("the look still runs");
        let said = composed.said();
        assert_eq!(said.len(), 1, "{said:?}");
        assert!(
            said[0].contains("could not establish what transport"),
            "{said:?}"
        );
        assert!(
            !said[0].contains("could not be protected"),
            "a composed transport owes no transport rider: {said:?}"
        );
    }

    /// A repository git will not open is not an ssh problem:
    /// [`super::env::TransportUnknown`] splits the causes apart so the message
    /// stops offering a remedy that was measured to move the failure without
    /// fixing it.
    #[test]
    fn a_repository_git_cannot_open_is_not_reported_as_an_ssh_problem() {
        let refused = Op::AdvertisedTags { remote: "origin" }
            .shape()
            .unreadable_transport(&super::env::TransportUnknown::Repository(String::from(
                "exit 128: fatal: Expected git repo version <= 1, found 99",
            )))
            .to_string();
        assert!(
            refused.contains("could not read this repository"),
            "{refused}"
        );
        assert!(refused.contains("found 99"), "{refused}");
        assert!(!refused.contains("ssh"), "{refused}");
        assert!(!refused.contains("GIT_SSH_COMMAND"), "{refused}");
    }

    /// The remedy for an unreadable ssh variable cannot be to set that
    /// variable. Measured before the arm existed: an invalid-UTF-8
    /// `GIT_SSH_COMMAND` was answered by advising that both it and
    /// `GIT_SSH_VARIANT` be set.
    #[test]
    fn an_unreadable_ssh_variable_is_not_answered_by_setting_it() {
        let said = Op::AdvertisedTags { remote: "origin" }
            .shape()
            .unreadable_transport(&super::env::TransportUnknown::SshVariable(String::from(
                "GIT_SSH_COMMAND is not valid UTF-8",
            )))
            .to_string();
        assert!(
            said.contains("GIT_SSH_COMMAND is not valid UTF-8"),
            "{said}"
        );
        assert!(said.contains("repair or unset that variable"), "{said}");
        assert!(
            !said.contains("set both GIT_SSH_COMMAND and GIT_SSH_VARIANT"),
            "circular: {said}"
        );
    }

    /// A probe that never reached git establishes nothing — not about ssh, and
    /// not about the repository. Both remedies would be diagnoses nobody made,
    /// and the ssh one was measured being offered for a git that is not
    /// installed.
    #[test]
    fn a_probe_that_never_reached_git_claims_neither_cause() {
        let unasked = Op::AdvertisedTags { remote: "origin" }
            .shape()
            .unreadable_transport(&super::env::TransportUnknown::Unasked(String::from(
                "could not run git: No such file or directory (os error 2)",
            )))
            .to_string();
        assert!(unasked.contains("could not ask git"), "{unasked}");
        assert!(unasked.contains("No such file or directory"), "{unasked}");
        assert!(!unasked.contains("GIT_SSH_COMMAND"), "{unasked}");
        assert!(
            !unasked.contains("could not read this repository"),
            "a probe that did not run says nothing about the repository: {unasked}"
        );
    }

    /// okm-3cbq: a config probe that never answered leaves even a push
    /// unverified; one that could not be started keeps the push's class.
    #[test]
    fn a_probe_that_never_answered_is_unverified_whatever_the_op() {
        let push = Op::PushTag {
            remote: "origin",
            tag: "v1.0.0",
        }
        .shape();
        let detail = String::from("gave up after 2s with no answer");
        let unanswered =
            push.unreadable_transport(&super::env::TransportUnknown::Unanswered(detail.clone()));
        assert_eq!(unanswered.exit_code(), 2, "{unanswered}");
        let unasked = push.unreadable_transport(&super::env::TransportUnknown::Unasked(detail));
        assert_eq!(unasked.exit_code(), 1, "{unasked}");
    }

    /// `-z` turns quoting off, so a path carrying newlines, boundary
    /// whitespace, or non-ASCII bytes must arrive byte-for-byte.
    #[test]
    fn nul_records_are_preserved_exactly() {
        let parsed = split_nul_paths(b"pkg/a b\0pkg/\n weird \0pkg/caf\xc3\xa9.rs\0")
            .expect("valid utf-8 records");
        assert_eq!(parsed, ["pkg/a b", "pkg/\n weird ", "pkg/caf\u{e9}.rs"]);
        assert_eq!(split_nul_paths(b"").expect("empty"), Vec::<String>::new());
    }

    #[test]
    fn a_non_utf8_record_is_refused_rather_than_lossily_rewritten() {
        assert_eq!(split_nul_paths(b"pkg/\xff.bin\0"), None);
    }
}

#[cfg(test)]
mod base_tree_reads {
    use std::path::Path;
    use std::process::Command;

    use super::super::base_tree::base_workspace_in_scratch as in_scratch;
    use super::{Commit, Git};
    use crate::cli::Outcome;

    fn git(dir: &Path, args: &[&str]) -> String {
        let global = dir.join("..").join("gitconfig");
        std::fs::write(&global, "").expect("global config");
        let out = Command::new("git")
            .args([
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "-c",
                "commit.gpgSign=false",
            ])
            .args(args)
            .current_dir(dir)
            .env("GIT_CONFIG_GLOBAL", &global)
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .output()
            .expect("git");
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8(out.stdout)
            .expect("utf-8")
            .trim()
            .to_owned()
    }

    /// A base manifest a blob-filtered clone lacks is unverified, and the
    /// read fetches nothing into `.git`.
    #[test]
    fn a_blob_a_partial_clone_lacks_is_unverified_and_not_fetched() {
        let (read, before, after) = in_scratch(&[], |dir: &Path| {
            let source = dir.join("source");
            std::fs::create_dir_all(source.join("app/src")).expect("source");
            git(&source, &["init", "-q"]);
            std::fs::write(
                source.join("Cargo.toml"),
                "[workspace]\nmembers = [\"app\"]\n",
            )
            .expect("root");
            let manifest = "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n";
            std::fs::write(source.join("app/Cargo.toml"), manifest).expect("app");
            std::fs::write(source.join("app/src/lib.rs"), "").expect("lib");
            git(&source, &["add", "-A"]);
            git(&source, &["commit", "-qm", "base"]);
            std::fs::write(
                source.join("app/Cargo.toml"),
                format!("{manifest}# changed\n"),
            )
            .expect("app");
            git(&source, &["commit", "-qam", "head"]);
            git(&source, &["config", "uploadpack.allowFilter", "true"]);
            let url = format!("file://{}", source.display());
            git(dir, &["clone", "-q", "--filter=blob:none", &url, "clone"]);
            let clone = dir.join("clone");
            let base = git(&clone, &["rev-parse", "HEAD^"]);
            (clone, base)
        });
        let err = read.expect_err("unverified");
        assert!(
            err.to_string().contains("is not in this partial clone"),
            "{err}"
        );
        assert_eq!(after, before);
    }

    /// A workspace of one member `app`, committed in a new repository at `dir`.
    fn one_member_repo(dir: &Path) -> std::path::PathBuf {
        let repo = dir.join("repo");
        std::fs::create_dir_all(repo.join("app/src")).expect("repo");
        git(&repo, &["init", "-q"]);
        std::fs::write(
            repo.join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\"]\n",
        )
        .expect("root");
        std::fs::write(
            repo.join("app/Cargo.toml"),
            "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .expect("app");
        std::fs::write(repo.join("app/src/lib.rs"), "").expect("lib");
        git(&repo, &["add", "-A"]);
        repo
    }

    /// cargo would read this base without `vendor/lib`, which HEAD has as a
    /// member, so the base read is unverified rather than short a member.
    #[test]
    fn a_submodule_holding_a_member_is_unverified() {
        let (read, _, _) = in_scratch(&[("app", "app"), ("vendor/lib", "lib")], |dir: &Path| {
            let repo = one_member_repo(dir);
            let commit = "1111111111111111111111111111111111111111";
            git(
                &repo,
                &[
                    "update-index",
                    "--add",
                    "--cacheinfo",
                    &format!("160000,{commit},vendor/lib"),
                ],
            );
            git(&repo, &["commit", "-qm", "base"]);
            let base = git(&repo, &["rev-parse", "HEAD"]);
            (repo, base)
        });
        let err = read.expect_err("unverified");
        assert!(err.to_string().contains("`vendor/lib`"), "{err}");
        assert!(err.to_string().contains("is a submodule"), "{err}");
    }

    /// A crate at `dir` named `name`, with its manifest and an empty lib.
    fn write_crate(dir: &Path, name: &str) {
        std::fs::create_dir_all(dir.join("src")).expect("crate");
        std::fs::write(
            dir.join("Cargo.toml"),
            format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
        )
        .expect("manifest");
        std::fs::write(dir.join("src/lib.rs"), "").expect("lib");
    }

    /// A repository at `dir/repo` whose root manifest is `root`, committed
    /// once `build` has laid out the rest; answers it and its commit.
    fn base_repo(
        dir: &Path,
        root: &str,
        build: impl FnOnce(&Path),
    ) -> (std::path::PathBuf, String) {
        let repo = dir.join("repo");
        std::fs::create_dir_all(&repo).expect("repo");
        git(&repo, &["init", "-q"]);
        std::fs::write(repo.join("Cargo.toml"), root).expect("root");
        build(&repo);
        git(&repo, &["add", "-A"]);
        git(&repo, &["commit", "-qm", "base"]);
        let base = git(&repo, &["rev-parse", "HEAD"]);
        (repo, base)
    }

    fn names(read: Result<Option<oakum::plan::Workspace>, super::CliError>) -> Vec<String> {
        let workspace = read.expect("read").expect("a workspace");
        let mut names: Vec<String> = workspace.packages().map(|p| p.id().name.clone()).collect();
        names.sort();
        names
    }

    /// Links inside a linked directory, and a link to the repository root,
    /// read as cargo reads them in a checkout.
    #[cfg(unix)]
    #[test]
    fn nested_links_and_a_link_to_the_root_read_as_a_checkout_does() {
        use std::os::unix::fs::symlink;
        let (read, _, _) = in_scratch(&[], |dir: &Path| {
            base_repo(dir, "[workspace]\nmembers = [\"crates/*\"]\n", |repo| {
                write_crate(&repo.join("real/a"), "a");
                write_crate(&repo.join("other/c"), "c");
                symlink("../other/c", repo.join("real/c")).expect("inner link");
                symlink("real", repo.join("crates")).expect("outer link");
            })
        });
        assert_eq!(names(read), ["a", "c"]);
        let (read, _, _) = in_scratch(&[], |dir: &Path| {
            base_repo(dir, "[workspace]\nmembers = [\"self/app\"]\n", |repo| {
                write_crate(&repo.join("app"), "app");
                symlink(".", repo.join("self")).expect("root link");
            })
        });
        assert_eq!(names(read), ["app"]);
    }

    /// A base lock holding the workspace crates `x` and `y`.
    const LOCK_X_Y: &str = "version = 4\n\n[[package]]\nname = \"x\"\nversion = \"0.1.0\"\n\n[[package]]\nname = \"y\"\nversion = \"0.1.0\"\n";

    /// `.cargo/config.toml` leads through `d/a -> ..` out of the tree on
    /// disk, though its text names a path inside, so it is unread there.
    #[cfg(unix)]
    #[test]
    fn a_config_link_leaving_the_tree_through_another_link_is_unverified() {
        use std::os::unix::fs::symlink;
        let (read, _, _) = in_scratch(&[("app", "app")], |dir: &Path| {
            let repo = one_member_repo(dir);
            std::fs::create_dir_all(repo.join(".cargo")).expect(".cargo");
            std::fs::create_dir_all(repo.join("d")).expect("d");
            symlink("..", repo.join("d/a")).expect("d/a");
            symlink("a/../../outside.toml", repo.join("d/b")).expect("d/b");
            symlink("../d/b", repo.join(".cargo/config.toml")).expect("config");
            git(&repo, &["add", "-A"]);
            git(&repo, &["commit", "-qm", "base"]);
            let base = git(&repo, &["rev-parse", "HEAD"]);
            (repo, base)
        });
        let err = read.expect_err("unverified");
        assert!(err.to_string().contains("`.cargo/config.toml`"), "{err}");
    }

    /// `.cargo -> conf` and `conf/config` leaves the tree: cargo reads that
    /// link as `.cargo/config`, so the base is unread there.
    #[cfg(unix)]
    #[test]
    fn a_config_leaving_the_tree_behind_a_directory_link_is_unverified() {
        use std::os::unix::fs::symlink;
        for target in ["../../outside", "/outside/config"] {
            let (read, _, _) = in_scratch(&[("app", "app")], |dir: &Path| {
                let repo = one_member_repo(dir);
                std::fs::create_dir_all(repo.join("conf")).expect("conf");
                symlink(target, repo.join("conf/config")).expect("conf/config");
                symlink("conf", repo.join(".cargo")).expect(".cargo");
                git(&repo, &["add", "-A"]);
                git(&repo, &["commit", "-qm", "base"]);
                let base = git(&repo, &["rev-parse", "HEAD"]);
                (repo, base)
            });
            let err = read.expect_err("unverified");
            assert!(
                err.to_string().contains("`.cargo/config`"),
                "{target}: {err}"
            );
        }
    }

    /// A blob the clone lacks is not an absent file, reached through a
    /// directory link or not, and with or without a promisor remote left.
    #[cfg(unix)]
    #[test]
    fn a_lacked_blob_through_a_link_is_unread_not_absent() {
        let _ = in_scratch(&[("app", "app")], |dir: &Path| {
            let source = dir.join("source");
            std::fs::create_dir_all(source.join("old")).expect("old");
            git(&source, &["init", "-q", "-b", "main"]);
            std::fs::write(source.join("old/Cargo.toml"), "[workspace]\n").expect("base");
            std::os::unix::fs::symlink("old", source.join("rust")).expect("link");
            std::fs::write(source.join(".aa"), "sorts first\n").expect("first");
            std::fs::create_dir_all(source.join("sub")).expect("sub");
            std::os::unix::fs::symlink("..", source.join("sub/up")).expect("up");
            git(&source, &["add", "-A"]);
            git(&source, &["commit", "-qm", "base"]);
            std::fs::write(source.join("old/Cargo.toml"), "[workspace]\n# head\n").expect("head");
            git(&source, &["commit", "-qam", "head"]);
            git(&source, &["config", "uploadpack.allowFilter", "true"]);
            let url = format!("file://{}", source.display());
            git(dir, &["clone", "-q", "--filter=blob:none", &url, "clone"]);
            let clone = dir.join("clone");
            let base = Commit::from_log(&git(&clone, &["rev-parse", "HEAD^"])).expect("base");
            let full = Git::at(&source).offline();
            assert!(matches!(
                full.followed_blob(&base, "sub/up/old/Cargo.toml")
                    .expect("full"),
                super::Followed::File(_)
            ));
            git(
                &source,
                &[
                    "update-index",
                    "--add",
                    "--cacheinfo",
                    &format!("160000,{},vendor/sub", "1".repeat(40)),
                ],
            );
            git(&source, &["commit", "-qm", "submodule"]);
            let tip = Commit::from_log(&git(&source, &["rev-parse", "HEAD"])).expect("tip");
            assert_eq!(
                full.blobs_or_absent(&tip, &["vendor/sub/Cargo.toml"])
                    .expect("into a submodule"),
                [None]
            );
            for removed in [false, true] {
                if removed {
                    git(&clone, &["remote", "remove", "origin"]);
                }
                let reader = Git::at(&clone).offline();
                let err = reader
                    .followed_blob(&base, "rust/Cargo.toml")
                    .expect_err("through the link");
                assert!(
                    err.to_string().contains("reaches `old/Cargo.toml`"),
                    "{err}"
                );
                let err = reader
                    .followed_blob(&base, "sub/up/old/Cargo.toml")
                    .expect_err("through a link to the root");
                assert!(
                    err.to_string().contains("reaches `old/Cargo.toml`"),
                    "{err}"
                );
                let err = reader
                    .blobs_or_absent(&base, &["old/Cargo.toml"])
                    .expect_err("in place");
                assert_eq!(err.class(), Outcome::Unverified, "{err}");
                assert_eq!(
                    reader
                        .blobs_or_absent(&base, &["nope.toml"])
                        .expect("absent"),
                    [None]
                );
            }
            let head = git(&clone, &["rev-parse", "HEAD"]);
            (clone, head)
        });
    }

    /// A root's base holds no file; a commit a partial clone lacks holds none
    /// that can be read.
    #[test]
    fn a_roots_base_is_empty_and_a_missing_commit_is_unread() {
        let _ = in_scratch(&[("app", "app")], |dir: &Path| {
            let repo = one_member_repo(dir);
            git(&repo, &["commit", "-qm", "root"]);
            let head = git(&repo, &["rev-parse", "HEAD"]);
            git(&repo, &["config", "extensions.partialclone", "origin"]);
            let reader = Git::at(&repo).offline();
            let root = Commit::from_log(&head).expect("root");
            let base = reader.first_parent_or_empty(&root).expect("base");
            assert_eq!(
                reader
                    .blobs_or_absent(&base, &["Cargo.toml"])
                    .expect("read"),
                [None]
            );
            let err = reader
                .blobs_or_absent(&Commit("1".repeat(40)), &["Cargo.toml"])
                .expect_err("a commit the repository lacks");
            assert_eq!(err.class(), Outcome::Unverified, "{err}");
            (repo, head)
        });
    }

    /// A root commit compares against the empty tree, and an empty workspace
    /// has no members: neither is a base cargo could not read. A commit the
    /// repository lacks is.
    #[test]
    fn a_root_commits_parent_and_an_empty_workspace_have_no_base() {
        let (read, _, _) = in_scratch(&[("app", "app")], |dir: &Path| {
            let repo = one_member_repo(dir);
            git(&repo, &["commit", "-qm", "root"]);
            let root = Commit::from_log(&git(&repo, &["rev-parse", "HEAD"])).expect("root");
            let base = Git::at(&repo).first_parent_or_empty(&root).expect("base");
            (repo, base.as_str().to_owned())
        });
        assert!(read.expect("read").is_none());
        let (read, _, _) = in_scratch(&[("app", "app")], |dir: &Path| {
            let repo = one_member_repo(dir);
            git(&repo, &["commit", "-qm", "root"]);
            (repo, "1".repeat(40))
        });
        let err = read.expect_err("a commit the repository lacks");
        assert_eq!(err.class(), Outcome::Unverified, "{err}");
        let (read, _, _) = in_scratch(&[("app", "app")], |dir: &Path| {
            base_repo(dir, "[workspace]\nmembers = []\n", |_| {})
        });
        assert!(read.expect("read").is_none());
    }

    /// With no base lock to say what was a crate there, a member cargo did not
    /// list beside a submodule a glob covers is unverified.
    #[test]
    fn without_a_base_lock_a_glob_covered_submodule_is_unverified() {
        let (read, _, _) = in_scratch(&[("crates/x", "x"), ("vendor/y", "y")], |dir: &Path| {
            base_repo(dir, "[workspace]\nmembers = [\"vendor/*\"]\n", |repo| {
                write_crate(&repo.join("vendor/y"), "y");
                std::fs::create_dir_all(repo.join("vendor/x")).expect("submodule dir");
                git(repo, &["add", "-A"]);
                let commit = "1111111111111111111111111111111111111111";
                git(
                    repo,
                    &[
                        "update-index",
                        "--add",
                        "--cacheinfo",
                        &format!("160000,{commit},vendor/x"),
                    ],
                );
            })
        });
        let err = read.expect_err("unverified");
        assert!(err.to_string().contains("`vendor/x`"), "{err}");
    }

    /// `.cargo -> conf` and `conf/config -> ../real/settings`: cargo reads
    /// `real/settings` as its config, so it is written whole, here as the
    /// TOML cargo refuses in a checkout.
    #[cfg(unix)]
    #[test]
    fn a_config_behind_two_links_is_written_whole() {
        use std::os::unix::fs::symlink;
        let (read, _, _) = in_scratch(&[("app", "app")], |dir: &Path| {
            let repo = one_member_repo(dir);
            std::fs::create_dir_all(repo.join("conf")).expect("conf");
            std::fs::create_dir_all(repo.join("real")).expect("real");
            std::fs::write(repo.join("real/settings"), "[registries\n").expect("settings");
            symlink("../real/settings", repo.join("conf/config")).expect("conf/config");
            symlink("conf", repo.join(".cargo")).expect(".cargo");
            git(&repo, &["add", "-A"]);
            git(&repo, &["commit", "-qm", "base"]);
            let base = git(&repo, &["rev-parse", "HEAD"]);
            (repo, base)
        });
        let err = read.expect_err("cargo refuses the config");
        assert!(
            err.to_string().contains("could not read the workspace"),
            "{err}"
        );
    }

    /// A crate new on the branch beside an unrelated submodule is no member
    /// the submodule could have hidden: the base lock never held it.
    #[test]
    fn a_new_member_beside_an_unrelated_submodule_reads() {
        let (read, _, _) = in_scratch(&[("vendor/y", "y"), ("crates/new", "new")], |dir: &Path| {
            base_repo(dir, "[workspace]\nmembers = [\"vendor/*\"]\n", |repo| {
                write_crate(&repo.join("vendor/y"), "y");
                std::fs::write(repo.join("Cargo.lock"), LOCK_X_Y).expect("lock");
                std::fs::create_dir_all(repo.join("docs/theme")).expect("submodule dir");
                git(repo, &["add", "-A"]);
                let commit = "1111111111111111111111111111111111111111";
                git(
                    repo,
                    &[
                        "update-index",
                        "--add",
                        "--cacheinfo",
                        &format!("160000,{commit},docs/theme"),
                    ],
                );
            })
        });
        assert_eq!(names(read), ["y"]);
    }

    /// A submodule a `members` glob covers may hide a member HEAD has, here
    /// moved to `crates/x`, so the base read is unverified.
    #[test]
    fn a_submodule_a_glob_covers_is_unverified_when_a_member_is_missing() {
        let (read, _, _) = in_scratch(&[("crates/x", "x"), ("vendor/y", "y")], |dir: &Path| {
            base_repo(dir, "[workspace]\nmembers = [\"vendor/*\"]\n", |repo| {
                write_crate(&repo.join("vendor/y"), "y");
                std::fs::write(repo.join("Cargo.lock"), LOCK_X_Y).expect("lock");
                std::fs::create_dir_all(repo.join("vendor/x")).expect("submodule dir");
                git(repo, &["add", "-A"]);
                let commit = "1111111111111111111111111111111111111111";
                git(
                    repo,
                    &[
                        "update-index",
                        "--add",
                        "--cacheinfo",
                        &format!("160000,{commit},vendor/x"),
                    ],
                );
            })
        });
        let err = read.expect_err("unverified");
        assert!(err.to_string().contains("`vendor/x`"), "{err}");
    }

    /// A workspace that sat in a submodule at the base is unread there, not
    /// absent.
    #[test]
    fn a_workspace_in_a_submodule_at_the_base_is_unverified() {
        let (read, _, _) = in_scratch(&[("vendor/lib", "lib")], |dir: &Path| {
            let repo = dir.join("repo");
            std::fs::create_dir_all(&repo).expect("repo");
            git(&repo, &["init", "-q"]);
            let commit = "1111111111111111111111111111111111111111";
            git(
                &repo,
                &[
                    "update-index",
                    "--add",
                    "--cacheinfo",
                    &format!("160000,{commit},vendor/lib"),
                ],
            );
            git(&repo, &["commit", "-qm", "base"]);
            let base = git(&repo, &["rev-parse", "HEAD"]);
            (repo, base)
        });
        let err = read.expect_err("unverified");
        assert!(err.to_string().contains("`vendor/lib`"), "{err}");
    }

    /// A manifest-like path that is not UTF-8 is unread, so the base is.
    #[cfg(unix)]
    #[test]
    fn a_toml_path_that_is_not_utf8_is_unverified() {
        use std::os::unix::ffi::OsStrExt;
        let (read, _, _) = in_scratch(&[], |dir: &Path| {
            let repo = one_member_repo(dir);
            let blob = git(&repo, &["hash-object", "-w", "app/Cargo.toml"]);
            let mut info = format!("100644,{blob},").into_bytes();
            info.extend_from_slice(b"app/\xff.toml");
            let out = Command::new("git")
                .args(["update-index", "--add", "--cacheinfo"])
                .arg(std::ffi::OsStr::from_bytes(&info))
                .current_dir(&repo)
                .output()
                .expect("git");
            assert!(
                out.status.success(),
                "{}",
                String::from_utf8_lossy(&out.stderr)
            );
            git(&repo, &["commit", "-qm", "base"]);
            let base = git(&repo, &["rev-parse", "HEAD"]);
            (repo, base)
        });
        let err = read.expect_err("unverified");
        assert!(err.to_string().contains("is not a UTF-8 path"), "{err}");
    }

    /// A path that is not UTF-8 and that cargo never reads is left out.
    #[cfg(unix)]
    #[test]
    fn a_path_cargo_does_not_read_need_not_be_utf8() {
        use std::os::unix::ffi::OsStrExt;
        let (read, _, _) = in_scratch(&[], |dir: &Path| {
            let repo = one_member_repo(dir);
            let blob = git(&repo, &["hash-object", "-w", "app/src/lib.rs"]);
            let mut info = format!("100644,{blob},").into_bytes();
            info.extend_from_slice(b"junk\xff.bin");
            let out = Command::new("git")
                .args(["update-index", "--add", "--cacheinfo"])
                .arg(std::ffi::OsStr::from_bytes(&info))
                .current_dir(&repo)
                .output()
                .expect("git");
            assert!(
                out.status.success(),
                "{}",
                String::from_utf8_lossy(&out.stderr)
            );
            git(&repo, &["commit", "-qm", "base"]);
            let base = git(&repo, &["rev-parse", "HEAD"]);
            (repo, base)
        });
        let workspace = read.expect("read").expect("a workspace");
        assert_eq!(workspace.packages().count(), 1);
    }

    /// A link's own blob a blob-filtered clone lacks is as unread as a file's.
    #[cfg(unix)]
    #[test]
    fn a_link_a_partial_clone_lacks_is_unverified() {
        let (read, before, after) = in_scratch(&[], |dir: &Path| {
            let source = one_member_repo(dir);
            std::fs::rename(source.join("Cargo.toml"), source.join("ws.toml")).expect("move");
            std::os::unix::fs::symlink("ws.toml", source.join("Cargo.toml")).expect("link");
            git(&source, &["add", "-A"]);
            git(&source, &["commit", "-qm", "base"]);
            std::fs::copy(source.join("ws.toml"), source.join("ws2.toml")).expect("copy");
            std::fs::remove_file(source.join("Cargo.toml")).expect("unlink");
            std::os::unix::fs::symlink("ws2.toml", source.join("Cargo.toml")).expect("relink");
            git(&source, &["add", "-A"]);
            git(&source, &["commit", "-qm", "head"]);
            git(&source, &["config", "uploadpack.allowFilter", "true"]);
            let url = format!("file://{}", source.display());
            git(dir, &["clone", "-q", "--filter=blob:none", &url, "clone"]);
            let clone = dir.join("clone");
            let base = git(&clone, &["rev-parse", "HEAD^"]);
            (clone, base)
        });
        let err = read.expect_err("unverified");
        assert!(err.to_string().contains("`Cargo.toml`"), "{err}");
        assert!(
            err.to_string().contains("is not in this partial clone"),
            "{err}"
        );
        assert_eq!(after, before);
    }
}