headwater-cli 0.5.0

The headwater binary, and what CI runs. headwater --help is the verb list
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
// SPDX-License-Identifier: Apache-2.0
//! `headwater taxonomy publish`, from the state an adopter is actually in.
//!
//! # The defect this target exists for
//!
//! The library guarantee is held one crate down, in
//! `headwater-resolve/tests/publish.rs`: a publish that cannot read what its
//! manifest declares leaves `--out` exactly as it found it. The message a person
//! reads is a different component. `main.rs` prints `headwater: nothing was
//! published` for every error the library returns, with no knowledge of whether
//! a byte was written, so that line was a claim about the disk that no code
//! established. [#271] is the issue where it was false: three files and an empty
//! `bundles/` under a directory the run said it had not written to, and a second
//! run refused by the verb's own precondition catching the first run's
//! leftovers.
//!
//! A correctness root can be completely right and still produce a broken result,
//! and only running the next component reveals it. So this case runs the built
//! binary and reads standard error and the disk, rather than calling the library
//! that the case below it already covers.
//!
//! # The root it runs over
//!
//! This repository's own maintained source of `headwater/standard` —
//! `taxonomy-source/headwater-standard/` since #336 moved it out of
//! `.headwater/packages/` — copied to where `--package` looks a package up, and nothing
//! else. That is the state `headwater init` sends a newcomer into: its refusal
//! says *"package headwater/standard is not under `.headwater/packages/`, and nothing here
//! fetches one"*, and the copy that line invites carries a manifest whose
//! `contents.bundles` climbs out with `../..` into a library that the copy left
//! behind. `.headwater/packages/headwater-standard/` itself is no longer this fixture,
//! because #336 also made it a vendored artifact whose manifest carries the
//! library inside it rather than climbing out to reach one.
//!
//! [#271]: https://github.com/headwater-ai/headwater/issues/271

use headwater_resolve::{assembly, flatten, package};
use std::path::{Path, PathBuf};
use std::process::Command;

fn repository() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../..")
        .canonicalize()
        .expect("the repository root resolves")
}

/// A scratch tree that removes itself, named for the case that made it.
struct Root(PathBuf);

impl Root {
    /// An empty tree, for a case whose root is this repository itself.
    fn scratch(label: &str) -> Root {
        let at = std::env::temp_dir().join(format!(
            "headwater-cli-publish-{}-{label}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&at);
        std::fs::create_dir_all(&at).expect("the scratch tree is made");
        Root(at)
    }

    /// This repository's package and the bundle library it points at, copied,
    /// with one regular file named `bundles` added at the package root.
    ///
    /// This root publishes right up to the write phase and fails inside it: the
    /// staged set holds a file at `bundles` and files under `bundles/`, so `put`
    /// writes part of the artifact and then cannot make a directory where it has
    /// just written a file. It is the only provocation in this file that reaches
    /// the undo, and no mode and no race is in it. See the fixture of the same
    /// shape in `headwater-resolve/tests/publish.rs` for why the suite needed
    /// one.
    fn colliding(label: &str) -> Root {
        let root = Root::scratch(label);
        copy(
            &repository().join("taxonomy-source/headwater-standard"),
            &root.0.join(".headwater/packages/headwater-standard"),
        );
        copy(
            &repository().join("docs/taxonomies"),
            &root.0.join("docs/taxonomies"),
        );
        std::fs::write(
            root.0
                .join(".headwater/packages/headwater-standard/bundles"),
            "a regular file where the artifact needs a directory\n",
        )
        .expect("the colliding file is written");
        root
    }

    /// This repository's maintained source, copied to where `--package` looks
    /// a package up, with no library beside it.
    fn copied(label: &str) -> Root {
        let root = Root::scratch(label);
        copy(
            &repository().join("taxonomy-source/headwater-standard"),
            &root.0.join(".headwater/packages/headwater-standard"),
        );
        assert!(
            !root.0.join("docs/taxonomies").exists(),
            "the library the manifest points at must not be in the copy"
        );
        root
    }

    fn publish(&self, out: &Path) -> (Option<i32>, String) {
        publish_from(&self.0, out)
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

/// `taxonomy publish` over a root the caller names, as a person types it.
fn publish_from(root: &Path, out: &Path) -> (Option<i32>, String) {
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish", "--package", "headwater/standard"])
        .arg("--out")
        .arg(out)
        .arg("--root")
        .arg(root)
        .output()
        .expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// `taxonomy publish --from` over this repository's own maintained source.
///
/// `--package headwater/standard` now finds `.headwater/packages/headwater-standard/`,
/// and #366 made that refuse: the directory carries a release record, so it
/// was vendored rather than maintained by hand. `taxonomy-source/headwater-standard/`
/// is the maintained source, and this is the real, substantial artifact this
/// case needs — not a synthetic one — so it names that directory with `--from`
/// rather than switching to a smaller fixture.
fn publish_real_source_into(out: &Path) -> (Option<i32>, String) {
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .arg("taxonomy")
        .arg("publish")
        .arg("--from")
        .arg(repository().join("taxonomy-source/headwater-standard"))
        .arg("--out")
        .arg(out)
        .arg("--root")
        .arg(repository())
        .output()
        .expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// `taxonomy publish --from` over the maintained source, with or without
/// `--json`, and both streams kept apart: the document is on one, and an
/// account of a refusal is on the other.
fn publish_real_source(out: &Path, json: bool) -> (Option<i32>, String, String) {
    let mut command = Command::new(env!("CARGO_BIN_EXE_headwater"));
    command
        .arg("taxonomy")
        .arg("publish")
        .arg("--from")
        .arg(repository().join("taxonomy-source/headwater-standard"))
        .arg("--out")
        .arg(out)
        .arg("--root")
        .arg(repository());
    if json {
        command.arg("--json");
    }
    let output = command.output().expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// Which shape of source `assembly_source` writes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Arm {
    /// Every declared path carries what a reader of it opens.
    Sound,
    /// The recipe names a bundle the package does not ship.
    UnselectableBundle,
    /// Three declared directories exist and hold no file: `doctrine`,
    /// `templates`, and `glossary`, which is a key no table in this engine
    /// names.
    ///
    /// This is the state a *correct* stager still produces, on both publish
    /// paths: `reachable` passes it, because each directory is there and is a
    /// directory, and the walk that carries bytes then carries none. The
    /// manifest reaches a consumer naming three paths the artifact does not
    /// hold.
    ///
    /// **Three keys rather than one, deliberately.** Two guarding cases over
    /// `doctrine` alone would pass a `carried` narrowed to the two keys this
    /// issue happened to be about, so nothing would hold the generality the
    /// issue asks for. `templates` is a second key `required_kind` names,
    /// `glossary` is a key it does not, and the pair of them is what makes
    /// "every key the manifest declares" a measurement. It also pins that every
    /// bad key is reported and not the first.
    UnwrittenMembers,
    /// The recipe selects `alpha` alone, so `shelves.betas.kind` reads `beta`
    /// and only the `beta` bundle declares it.
    ///
    /// **This arm declares no overlay, and that is the whole reason it
    /// measures anything.** The overlay every other arm carries is
    /// `relations.connects {from: [alpha], to: [beta]}`, and `validate_glue`
    /// refuses it the moment `beta` is not selected, because glue that is not
    /// cross-bundle is not glue. An arm that narrowed the selection and kept
    /// the overlay would be refused for that reason, go red before this change
    /// as well as after it, and say nothing at all about referential integrity.
    IncompleteSelection,
}

/// A source package with one named assembly, small enough to make the publish
/// boundary visible in isolation from the real one.
///
/// It carries the shapes the shipped starter does not: an assembly overlay, a
/// templates directory, an arm that names a bundle the package does not ship,
/// and an arm whose declared doctrine directory is empty.
/// `the_shipped_starter_recipe_publishes_vendors_and_resolves` is the case that
/// runs the same verb over the real source.
///
/// **It declares `contents.conformance` and `contents.glossary`, and both are
/// deliberate.** Until #581 no fixture in this file declared a file-valued
/// `contents` key beyond `taxonomy`, so nothing here ever asked whether a
/// flattened artifact carries one; `headwater/standard` declares one and the
/// flattened starter did not carry it. `glossary` is a key **no table in this
/// engine names** — `required_kind` returns `None` for it — so it is what holds
/// the claim that a flattened package carries every declared member rather than
/// the members somebody listed in Rust.
fn assembly_source(root: &Root, arm: Arm) -> PathBuf {
    let source = root.path().join("source/acme-fixture");
    write(
        &source.join("package.yml"),
        "package: acme/fixture\nversion: 1.0.0\ncontents:\n  taxonomy: taxonomy.yml\n  conformance: conformance.yml\n  glossary: glossary.yml\n  bundles: bundles\n  assemblies: assemblies\n  doctrine: doctrine\n  templates: templates\n",
    );
    write(
        &source.join("glossary.yml"),
        "glossary:\n  headwater: the system this fixture is a fixture of\n",
    );
    write(
        &source.join("conformance.yml"),
        "conformance:\n  format: 1\n  rules:\n    - name: pin.current\n      title: The pin names the package that is installed\n      decided_by: tree\n      statement: The pin names a version and a digest that the installed artifact carries.\n      remediation: Publish the package, write the printed digest into the pin, and vendor it.\n  levels:\n    - name: L0\n      title: Pointed at\n      rules: [pin.current]\n",
    );
    write(
        &source.join("taxonomy.yml"),
        "taxonomy: acme/fixture\nversion: 1.0.0\npurposes:\n  behavior: {intent: state what the system does}\nkinds:\n  governed_document: {abstract: true}\n  specification: {is_a: governed_document, purpose: behavior}\nshelves:\n  specifications: {path: docs/specifications/**, homogeneous: true, kind: specification}\n  alphas: {path: docs/alphas/**, homogeneous: true, kind: alpha}\n  betas: {path: docs/betas/**, homogeneous: true, kind: beta}\ncore:\n  requires:\n    - purpose: behavior\n",
    );
    write(
        &source.join("bundles/alpha/bundle.yml"),
        "bundle: alpha\nextends: acme/fixture@1.0.0\nrequires: []\nadd:\n  kinds.alpha: {is_a: governed_document, purpose: behavior}\n",
    );
    write(
        &source.join("bundles/beta/bundle.yml"),
        "bundle: beta\nextends: acme/fixture@1.0.0\nrequires: []\nadd:\n  kinds.beta: {is_a: governed_document, purpose: behavior}\n",
    );
    let selected = match arm {
        Arm::UnselectableBundle => "[alpha, missing]",
        Arm::IncompleteSelection => "[alpha]",
        Arm::Sound | Arm::UnwrittenMembers => "[alpha, beta]",
    };
    let glue = match arm {
        Arm::IncompleteSelection => "",
        Arm::Sound | Arm::UnselectableBundle | Arm::UnwrittenMembers => "overlay: overlay.yml\n",
    };
    write(
        &source.join("assemblies/starter/assembly.yml"),
        &format!(
            "assembly: starter\npackage: acme/starter\nversion: 2.0.0\nfrom:\n  package: acme/fixture@1.0.0\n  bundles: {selected}\n{glue}"
        ),
    );
    write(
        &source.join("assemblies/starter/overlay.yml"),
        "add:\n  relations.connects:\n    family: derivation\n    from: [alpha]\n    to: [beta]\n    nucleus: from\n    inverse: connected_by\n    reciprocal: required\n    created_by: scaffold\n",
    );
    match arm {
        Arm::UnwrittenMembers => {
            for key in ["doctrine", "templates", "glossary"] {
                std::fs::create_dir_all(source.join(key))
                    .expect("the empty declared directory is made");
            }
            // The scalar has to name the directory rather than the file the
            // sound arm writes, or `reachable` refuses this arm for the kind
            // rather than `carried` refusing it for the absence, and the case
            // would report on the wrong rule.
            write(
                &source.join("package.yml"),
                "package: acme/fixture\nversion: 1.0.0\ncontents:\n  taxonomy: taxonomy.yml\n  conformance: conformance.yml\n  glossary: glossary\n  bundles: bundles\n  assemblies: assemblies\n  doctrine: doctrine\n  templates: templates\n",
            );
        }
        Arm::Sound | Arm::UnselectableBundle | Arm::IncompleteSelection => {
            write(&source.join("doctrine/guide.md"), "# Fixture doctrine\n");
            write(&source.join("templates/decision.md"), "# Decision\n");
        }
    }
    source
}

fn write(path: &Path, text: &str) {
    std::fs::create_dir_all(path.parent().expect("the file has a parent"))
        .expect("the parent is made");
    std::fs::write(path, text).expect("the fixture file is written");
}

fn publish_assembly_from(root: &Path, source: &Path, out: &Path) -> (Option<i32>, String, String) {
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish", "--assembly", "starter", "--from"])
        .arg(source)
        .arg("--out")
        .arg(out)
        .arg("--root")
        .arg(root)
        .output()
        .expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// `taxonomy publish --from` over a source the caller names, with no recipe.
///
/// The plain stager, beside `publish_assembly_from`'s flattening one. The two
/// reach `--out` by different functions and #581 is a defect of both, so a case
/// about what an artifact carries needs one call of each.
fn publish_plain_from(root: &Path, source: &Path, out: &Path) -> (Option<i32>, String, String) {
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish", "--from"])
        .arg(source)
        .arg("--out")
        .arg(out)
        .arg("--root")
        .arg(root)
        .output()
        .expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// Run a consumer verb against the root that holds its authored pin.
/// The rule `headwater check` reports a pin that no longer names the vendored
/// bytes under.
const PIN_RULE: &str = "taxonomy.pin.diverged";

/// What its finding says, which the report prints only when the rule fires:
/// the rule id alone is also in the list of rules every run prints.
const PIN_FINDING: &str = "does not hash to it";

fn consumer_run(root: &Path, arguments: &[&str]) -> (Option<i32>, String, String) {
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(arguments)
        .arg("--root")
        .arg(root)
        .output()
        .expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// A consumer takes the flattened package as a package, rather than repeating
/// the source assembly's bundle selection.
fn flattened_consumer(root: &Root, digest: &str) -> PathBuf {
    let consumer = root.path().join("consumer");
    write(
        &consumer.join(".headwater/taxonomy.yml"),
        &format!(
            "taxonomy:\n  package: acme/starter\n  version: 2.0.0\n  digest: {digest}\ncorpus:\n  root: docs\n"
        ),
    );
    consumer
}

impl Drop for Root {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn copy(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).expect("the destination is made");
    for entry in std::fs::read_dir(from).expect("the source reads") {
        let entry = entry.expect("the entry reads").path();
        let name = entry.file_name().expect("it has a name");
        match entry.is_dir() {
            true => copy(&entry, &to.join(name)),
            false => {
                std::fs::copy(&entry, to.join(name)).expect("the file copies");
            }
        }
    }
}

#[test]
fn a_named_assembly_publishes_one_flattened_package() {
    let root = Root::scratch("assembly-publishes");
    let source = assembly_source(&root, Arm::Sound);
    let out = root.path().join("release");

    let (code, stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(0), "{stderr}");
    assert!(stdout.contains("published acme/starter 2.0.0"), "{stdout}");
    assert!(
        out.join("release.yml").is_file(),
        "no release record was written"
    );
    let manifest = std::fs::read_to_string(out.join("package.yml")).expect("the manifest reads");
    assert!(manifest.contains("package: acme/starter"), "{manifest}");
    assert!(manifest.contains("taxonomy: taxonomy.yml"), "{manifest}");
    assert!(manifest.contains("form: flattened"), "{manifest}");
    assert!(
        !out.join("bundles").exists(),
        "a flattened package carries bundles"
    );
    assert!(out.join("doctrine/starter/guide.md").is_file());
    assert!(out.join("templates/starter/decision.md").is_file());
}

/// Every key the source declares reaches the flattened artifact, not five of them.
///
/// `flatten::contents` copies through every `contents` key it does not filter,
/// and `flatten::assets` writes two. `conformance` is on one side of that gap
/// and not the other, so before #581 the flattened manifest named a rule set
/// the artifact did not hold and `headwater conformance` failed on the machine
/// of whoever vendored it.
#[test]
fn a_flattened_package_carries_the_conformance_rule_set_its_source_declared() {
    let root = Root::scratch("assembly-conformance");
    let source = assembly_source(&root, Arm::Sound);
    let out = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(0), "{stderr}");

    let manifest = std::fs::read_to_string(out.join("package.yml")).expect("the manifest reads");
    assert!(
        manifest.contains("conformance: conformance.yml"),
        "{manifest}"
    );
    assert!(
        out.join("conformance.yml").is_file(),
        "the manifest declares a conformance rule set the artifact does not carry"
    );
    // The key no table in this engine names. `required_kind` returns `None` for
    // it, so nothing in the fix knows what a `glossary` is, and it travels
    // anyway. That is the difference between "every declared member" and "the
    // members somebody remembered to list".
    assert!(manifest.contains("glossary: glossary.yml"), "{manifest}");
    assert!(
        out.join("glossary.yml").is_file(),
        "a `contents` key no table names did not travel, so the fix is a list rather than a rule"
    );
    let record = std::fs::read_to_string(out.join("release.yml")).expect("the release reads");
    for member in ["conformance.yml", "glossary.yml"] {
        assert!(
            record.contains(member),
            "the release record does not name {member}: {record}"
        );
    }
}

/// A declared directory with no file in it is the case a correct stager still
/// produces, and it is why the guard is general rather than a second key check.
///
/// `reachable` admits each of these: the directory is there and it is a
/// directory. The walk that carries bytes then carries none, because a directory
/// with no file in it has nothing to copy. Both these cases were measured at
/// exit 0 before #581, with the manifest naming a path the artifact did not
/// hold, on both publish paths.
///
/// **Three keys are asserted, and `glossary` is the one that matters most.**
/// `required_kind` names `doctrine` and `templates` and does not name
/// `glossary`, so a guard narrowed to the keys this issue was about would pass a
/// case over `doctrine` alone. Asserting all three at once also pins that every
/// bad key is reported rather than the first.
#[test]
fn a_flattened_manifest_may_not_name_a_member_the_artifact_does_not_carry() {
    let root = Root::scratch("assembly-unwritten");
    let source = assembly_source(&root, Arm::UnwrittenMembers);
    let out = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(1), "{stderr}");
    for key in ["doctrine", "templates", "glossary"] {
        assert!(stderr.contains(&format!("`contents.{key}`")), "{stderr}");
    }
    // The namespaced form, which is what the flattened manifest declares and
    // what a consumer would have opened.
    assert!(stderr.contains("doctrine/starter"), "{stderr}");
    assert!(stderr.contains("templates/starter"), "{stderr}");
    assert!(
        !out.exists(),
        "the refused run left partial output at {out:?}"
    );
}

#[test]
fn a_published_manifest_may_not_name_a_member_the_artifact_does_not_carry() {
    let root = Root::scratch("plain-unwritten");
    let source = assembly_source(&root, Arm::UnwrittenMembers);
    let out = root.path().join("release");

    let (code, _stdout, stderr) = publish_plain_from(root.path(), &source, &out);
    assert_eq!(code, Some(1), "{stderr}");
    for key in ["doctrine", "templates", "glossary"] {
        assert!(stderr.contains(&format!("`contents.{key}`")), "{stderr}");
    }
    assert!(
        !out.exists(),
        "the refused run left partial output at {out:?}"
    );
}

/// A key a flattened manifest drops is a key the publisher is told about.
///
/// `flatten::DROPPED` is the ruling — `bundles`, `assemblies` and `migrations`
/// state the source package's composition and version line, and a flattened
/// package inherits neither. The ruling is not in question here. What this pins
/// is that the loss is **reported**, because a publisher who declared
/// `migrations` and receives an artifact without it has lost something they
/// asked for, and #581 is the issue that refuses exactly that in the other
/// direction.
///
/// The source carries a real payload, so the case fails if the drop ever becomes
/// a silent one again: before this, the identical source produced an artifact
/// byte-identical to one declaring no migrations at all.
#[test]
fn a_flattened_publish_names_every_contents_key_it_drops() {
    let root = Root::scratch("assembly-drops");
    let source = assembly_source(&root, Arm::Sound);
    write(
        &source.join("package.yml"),
        "package: acme/fixture\nversion: 1.0.0\ncontents:\n  taxonomy: taxonomy.yml\n  conformance: conformance.yml\n  glossary: glossary.yml\n  bundles: bundles\n  assemblies: assemblies\n  migrations: migrations\n  doctrine: doctrine\n  templates: templates\n",
    );
    write(
        &source.join("migrations/0-to-1.yml"),
        "migration:\n  format: 1\n  from: \">=0 <1\"\n  to: \">=1 <2\"\n\nsteps:\n  - subject: overlay_address\n    from: purposes.gone\n    to: [purposes.behavior]\n    because: the case is about what a flattened manifest drops\n",
    );
    let out = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(0), "{stderr}");

    let manifest = std::fs::read_to_string(out.join("package.yml")).expect("the manifest reads");
    // The `contents` block alone. `distribution.derived_from` carries a
    // `bundles:` of its own — the selection this package was flattened from —
    // and that one is provenance rather than a path, so a search over the whole
    // manifest would read it as a declaration and never fail.
    let contents = manifest
        .split_once("contents:")
        .and_then(|(_, rest)| rest.split_once("\ndistribution:"))
        .map(|(block, _)| block.to_string())
        .unwrap_or_else(|| panic!("the flattened manifest has no contents block: {manifest}"));
    for key in ["bundles", "assemblies", "migrations"] {
        assert!(
            !contents.contains(&format!("{key}:")),
            "the flattened `contents` declares `{key}`: {contents}"
        );
        assert!(
            !out.join(key).exists(),
            "the flattened artifact carries `{key}`, which the manifest does not declare"
        );
    }

    // `migrations` is the one the publisher is told about, because it is the one
    // nothing in the artifact represents. `bundles` is resolved into
    // `taxonomy.yml` and `assemblies` is recorded under
    // `distribution.derived_from`, so both are absorbed rather than lost.
    assert!(
        stderr.contains("`contents.migrations`"),
        "the publish dropped a declared payload and said nothing: {stderr}"
    );
    assert!(
        stderr.contains("has no reader here"),
        "the message does not say why the payload was dropped: {stderr}"
    );

    // The absorbed keys stay quiet. A line printed by every flattening publish —
    // and every assembly source declares `bundles`, or there would be no
    // assembly — is a line nobody reads on the publish that loses something.
    for key in ["bundles", "assemblies"] {
        assert!(
            !stderr.contains(&format!("`contents.{key}`")),
            "an absorbed key was reported as a loss: {stderr}"
        );
    }
}

/// The publish that loses nothing says nothing.
///
/// The companion to the case above, and the one that makes its signal worth
/// anything. This repository's own starter recipe is published from a source
/// declaring `bundles` and `assemblies` and no `migrations`, which is the
/// ordinary shape, and its standard error carries no drop notice at all.
#[test]
fn a_flattened_publish_that_loses_nothing_reports_no_drop() {
    let root = Root::scratch("assembly-no-drops");
    let source = assembly_source(&root, Arm::Sound);
    let out = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(0), "{stderr}");
    assert!(
        !stderr.contains("nothing in the flattened package carries it"),
        "a publish that loses nothing printed a drop notice: {stderr}"
    );
}

/// The flattened artifact crosses the entire publisher-consumer boundary.
///
/// The source selection has two bundles, but the consumer names no bundles at
/// all. It pins the release digest before `taxonomy vendor` reads the fetched
/// directory, resolves the installed package, and compares the installed
/// taxonomy with the source assembly after identity is removed. This is the
/// batteries-included consumption form: its declarations are the composer's
/// declarations, but bundle choice is no longer part of the consumer's state.
#[test]
fn a_flattened_assembly_is_pinned_vendored_and_resolved_without_bundle_selection() {
    let root = Root::scratch("assembly-consumer");
    let source = assembly_source(&root, Arm::Sound);
    let artifact = root.path().join("release");
    let (code, _stdout, stderr) = publish_assembly_from(root.path(), &source, &artifact);
    assert_eq!(code, Some(0), "{stderr}");

    let release = headwater_resolve::release::read(
        &std::fs::read_to_string(artifact.join("release.yml")).expect("the release reads"),
    )
    .expect("the published record reads");
    let consumer = flattened_consumer(&root, &release.digest);
    let declaration = package::consumer(&consumer).expect("the consumer declaration reads");
    assert!(
        declaration.bundles.is_empty(),
        "a flattened consumer carries no bundle selection: {:?}",
        declaration.bundles
    );

    let (code, _stdout, stderr) = consumer_run(
        &consumer,
        &[
            "taxonomy",
            "vendor",
            artifact.to_str().expect("the artifact is UTF-8"),
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");
    let installed = consumer.join(".headwater/packages/acme-starter");
    assert!(
        installed.join("release.yml").is_file(),
        "the artifact was not vendored"
    );

    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "resolve"]);
    assert_eq!(code, Some(0), "{stderr}");
    assert!(
        consumer.join(".headwater/taxonomy.lock").is_file(),
        "a resolved consumer has a lock"
    );

    let source_manifest = package::manifest_at(&source).expect("the source manifest reads");
    let recipe = assembly::read(root.path(), &source, &source_manifest, "starter")
        .expect("the source assembly reads");
    let source_resolution = assembly::resolve(root.path(), &source, &source_manifest, &recipe)
        .expect("the source assembly resolves");
    let installed_manifest =
        package::manifest_at(&installed).expect("the installed manifest reads");
    let installed_flattened = flatten::Flattened {
        manifest: installed_manifest,
        taxonomy: std::fs::read_to_string(installed.join("taxonomy.yml"))
            .expect("the installed taxonomy reads"),
        assets: Vec::new(),
        // `equivalent` compares taxonomy declarations and reads neither of
        // these. This value is read back off an installed artifact rather than
        // produced by a publish, so there is no run behind it whose dropped keys
        // this could name.
        dropped: Vec::new(),
    };
    assert!(
        flatten::equivalent(&source_resolution, &installed_flattened, &recipe),
        "the flattened consumer differs from the source assembly after identity is removed"
    );
}

/// The recipe this repository ships, over the whole publisher-consumer boundary.
///
/// The two cases above prove the mechanism over `acme/fixture`, which is a
/// fixture written to make the boundary visible. This is the first case here to
/// run `--assembly` over the real maintained source, and its subject is the
/// artifact spec 0 deliverable 6 promises an adopter:
/// `taxonomy-source/headwater-standard/assemblies/starter/assembly.yml`,
/// published as `headwater/starter`, vendored into a tree that names no bundle,
/// and resolved to a lock.
///
/// It takes the identity and the version out of the recipe rather than writing
/// either one down, so a bump of the starter moves this case with it and never
/// past it.
///
/// **The overlay is the assertion, not scaffolding.** The one answer a
/// batteries-included consumer still owes is the identifier namespace, which no
/// package may hold because a constant a publisher wrote would be minted by
/// every adopter at once. So the consumer below declares two namespace lines and
/// nothing else, and a lock at the end of it is the measurement that the
/// flattened starter needs no other answer.
#[test]
fn the_shipped_starter_recipe_publishes_vendors_and_resolves() {
    let root = Root::scratch("shipped-starter");
    let source = repository().join("taxonomy-source/headwater-standard");
    let artifact = root.path().join("release");

    let source_manifest = package::manifest_at(&source).expect("the source manifest reads");
    let recipe = assembly::read(&repository(), &source, &source_manifest, "starter")
        .expect("the shipped starter recipe reads");
    assert_eq!(recipe.from.bundles.len(), 3, "{:?}", recipe.from.bundles);
    assert!(
        recipe.overlay.is_none(),
        "the shipped recipe declares an overlay, and `validate_glue` admits one only as a \
         relation between two selected bundles"
    );

    let (code, stdout, stderr) = publish_assembly_from(&repository(), &source, &artifact);
    assert_eq!(code, Some(0), "{stderr}");
    assert!(
        stdout.contains(&format!("published {} {}", recipe.package, recipe.version)),
        "{stdout}"
    );
    let manifest =
        std::fs::read_to_string(artifact.join("package.yml")).expect("the manifest reads");
    assert!(
        manifest.contains(&format!("package: {}", recipe.package)),
        "{manifest}"
    );
    assert!(manifest.contains("form: flattened"), "{manifest}");
    assert!(
        !artifact.join("bundles").exists(),
        "a flattened package carries bundles"
    );
    assert!(
        artifact.join("doctrine/starter/starter.md").is_file(),
        "the doctrine this package declares did not reach the flattened artifact"
    );

    let release = headwater_resolve::release::read(
        &std::fs::read_to_string(artifact.join("release.yml")).expect("the release reads"),
    )
    .expect("the published record reads");
    let consumer = root.path().join("consumer");
    write(
        &consumer.join(".headwater/taxonomy.yml"),
        &format!(
            "taxonomy:\n  package: {}\n  version: {}\n  digest: {}\n  overlay: .headwater/overlay.yml\ncorpus:\n  root: docs\n",
            recipe.package, recipe.version, release.digest
        ),
    );
    write(
        &consumer.join(".headwater/overlay.yml"),
        "add:\n  identifier_schemes.decision_id.namespace: ACME\n  identifier_schemes.obligation_record_id.namespace: ACME\n",
    );
    std::fs::create_dir_all(consumer.join("docs")).expect("the corpus root is made");

    let declaration = package::consumer(&consumer).expect("the consumer declaration reads");
    assert!(
        declaration.bundles.is_empty(),
        "a flattened consumer carries no bundle selection: {:?}",
        declaration.bundles
    );

    let (code, _stdout, stderr) = consumer_run(
        &consumer,
        &[
            "taxonomy",
            "vendor",
            artifact.to_str().expect("the artifact is UTF-8"),
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");
    assert!(
        consumer
            .join(".headwater/packages/headwater-starter/doctrine/starter/starter.md")
            .is_file(),
        "the doctrine did not arrive with the vendored package"
    );
    // HW-DR-0084 promises that the doctrine names `outside_root` once the
    // engine reads it, and #1191 is the page that broke that promise. The
    // adopter receives the promise here, in the vendored doctrine, so the
    // assertion reads this copy and not the source.
    let doctrine = std::fs::read_to_string(
        consumer.join(".headwater/packages/headwater-starter/doctrine/starter/starter.md"),
    )
    .expect("the vendored doctrine is readable");
    assert!(
        doctrine.contains("outside_root"),
        "the starter doctrine does not name `outside_root`, the second route a language regime has to prose (HW-DR-0084)"
    );
    assert!(
        !doctrine.contains("reaches prose only through the kinds that bind it"),
        "the starter doctrine still says a kind is the only route a language regime has to prose"
    );

    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "resolve"]);
    assert_eq!(code, Some(0), "{stderr}");
    assert!(
        consumer.join(".headwater/taxonomy.lock").is_file(),
        "a resolved flattened starter has a lock"
    );

    // The verb that reads `contents.conformance`, run against the vendored
    // flattened package rather than against the lock. #581 is the reason it is
    // here: `vendor` and `resolve` both exited 0 over an artifact whose manifest
    // named a rule set it did not carry, and this is the first reader that opens
    // the path. `headwater conformance` also verifies the installed bytes
    // against the release record, so hand-placing the file cannot satisfy it.
    assert!(
        consumer
            .join(".headwater/packages/headwater-starter/conformance.yml")
            .is_file(),
        "the conformance rule set did not arrive with the vendored package"
    );
    let (code, stdout, stderr) = consumer_run(&consumer, &["conformance"]);
    assert_eq!(code, Some(0), "{stderr}");
    assert!(stdout.contains("L1"), "{stdout}");
}

/// **Which verb an adopter runs decides whether a hand edit to a vendored
/// package is found.** `headwater conformance --level L0` recomputes the digest
/// of every installed member and refuses; `headwater taxonomy resolve` exits 0
/// over the same tree, because it compares the version the manifest declares
/// against the version the consumer pinned and reads no digest at all
/// (`headwater_resolve::package::sources`).
///
/// This is [#517](https://github.com/headwater-ai/headwater/issues/517)'s only
/// surviving complaint. The recheck it asked for landed in `c09625a` on
/// 2026-08-25, eleven days before the issue was filed, so what remains is the
/// pairing: the recheck exists and the verb an adopter is most likely to put in
/// a build does not perform it. `resolve` still reads no digest, and
/// [#1186](https://github.com/headwater-ai/headwater/issues/1186) put the
/// recheck in the two verbs an adopter's commit hook and CI do run:
/// `check --strict` reports `taxonomy.pin.diverged` as an error, and
/// `taxonomy validate` refuses with exit 1, in both arms below.
///
/// The conformance crate holds the same pairing at the library level. This case
/// is the CLI half of it, because an exit status is what a build reads, and a
/// library call that returns `Ok` is not the same claim as a process that
/// returns 0.
///
/// **The order is the assertion.** Publish, then pin, then vendor, then resolve,
/// and the hand edit lands after the publish that computed the pinned digest. A
/// resolve before the publish would move the sources with the record and both
/// sides of the comparison would agree.
///
/// The edited member is a doctrine file, which is a member of the release and
/// names no path in the lock's `sources:` list. That is the same shape as
/// `conformance.yml` in this repository's own package, and it is the shape that
/// no other gate covers.
///
/// **Two arms, because the two numbers fail differently.** A pin that no longer
/// names the installed bytes is a gap in a reading, so a plain run exits 0 with
/// `pin.current` in its report and `--level L0` is what turns that into a
/// non-zero exit. Installed bytes that no longer match their own record refuse
/// ahead of every reading and at every level, because a rule set read out of a
/// diverged package is a rule set the run cannot trust. Only the first arm is
/// the one `--level` decides, and a sentence that credited `--level` with both
/// would be wrong about the second.
#[test]
fn a_pin_that_no_longer_names_the_installed_bytes_fails_check_validate_and_conformance_and_not_resolve(
) {
    let root = Root::scratch("pin-recheck-pairing");
    let source = repository().join("taxonomy-source/headwater-standard");
    let artifact = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(&repository(), &source, &artifact);
    assert_eq!(code, Some(0), "{stderr}");
    let release = headwater_resolve::release::read(
        &std::fs::read_to_string(artifact.join("release.yml")).expect("the release reads"),
    )
    .expect("the published record reads");

    let source_manifest = package::manifest_at(&source).expect("the source manifest reads");
    let recipe = assembly::read(&repository(), &source, &source_manifest, "starter")
        .expect("the shipped starter recipe reads");
    let consumer = root.path().join("consumer");
    write(
        &consumer.join(".headwater/taxonomy.yml"),
        &format!(
            "taxonomy:\n  package: {}\n  version: {}\n  digest: {}\n  overlay: .headwater/overlay.yml\ncorpus:\n  root: docs\n",
            recipe.package, recipe.version, release.digest
        ),
    );
    write(
        &consumer.join(".headwater/overlay.yml"),
        "add:\n  identifier_schemes.decision_id.namespace: ACME\n  identifier_schemes.obligation_record_id.namespace: ACME\n",
    );
    std::fs::create_dir_all(consumer.join("docs")).expect("the corpus root is made");

    let (code, _stdout, stderr) = consumer_run(
        &consumer,
        &[
            "taxonomy",
            "vendor",
            artifact.to_str().expect("the artifact is UTF-8"),
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");

    // Both verbs agree over the tree `vendor` wrote. Without this, a later
    // non-zero could be anything the fixture got wrong.
    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "resolve"]);
    assert_eq!(code, Some(0), "{stderr}");
    let (code, _stdout, stderr) = consumer_run(&consumer, &["conformance", "--level", "L0"]);
    assert_eq!(
        code,
        Some(0),
        "the freshly vendored tree does not reach L0: {stderr}"
    );
    // The two everyday verbs are clean over the same tree, so that a later 1
    // from either is the drift and not the fixture.
    let (code, stdout, stderr) = consumer_run(&consumer, &["check", "--strict"]);
    assert_eq!(
        code,
        Some(0),
        "the freshly vendored tree fails `check --strict`: {stdout}\n{stderr}"
    );
    assert!(!stdout.contains(PIN_FINDING), "{stdout}");
    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "validate"]);
    assert_eq!(
        code,
        Some(0),
        "the freshly vendored tree fails `validate`: {stderr}"
    );
    // The read set of the clean run carries the pin and every vendored member,
    // so a gate over a later tree sees either move. Over the same tree it
    // carries.
    let read_set = root.path().join("clean.readset");
    let read_set = read_set.to_str().expect("the read set path is UTF-8");
    let (code, _stdout, stderr) = consumer_run(&consumer, &["check", "--read-set", read_set]);
    assert_eq!(code, Some(0), "{stderr}");
    let recorded = std::fs::read_to_string(read_set).expect("the read set reads");
    for needle in [
        ".headwater/taxonomy.yml",
        ".headwater/packages/headwater-starter/doctrine/starter/starter.md",
    ] {
        assert!(
            recorded.contains(needle),
            "the read set does not list `{needle}`: {recorded}"
        );
    }
    // The gate never carries this verdict, because six corpus-grained rules
    // are barriers, so what it names as moved is the assertion and its exit
    // status is not.
    let (_code, stdout, _stderr) = consumer_run(&consumer, &["gate", "--read-set", read_set]);
    for moved in [".headwater/taxonomy.yml", "starter.md"] {
        assert!(
            !stdout.contains(moved),
            "the gate names `{moved}` over the tree the read set was taken from: {stdout}"
        );
    }

    // ---- Arm one: the pin moved and the bytes did not. ------------------
    //
    // `pin.current` reports a gap, so `--level L0` is what turns the report
    // into a non-zero exit and a plain run still exits 0 with the gap in the
    // report. The resolver exits 0 over the same tree because it never reads a
    // digest.
    let stale = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
    let authored = consumer.join(".headwater/taxonomy.yml");
    let pin = std::fs::read_to_string(&authored).expect("the authored pin reads");
    write(&authored, &pin.replace(&release.digest, stale));

    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "resolve"]);
    assert_eq!(
        code,
        Some(0),
        "the resolver read the pinned digest, so this pairing no longer holds: {stderr}"
    );
    let (code, stdout, stderr) = consumer_run(&consumer, &["conformance"]);
    assert_eq!(code, Some(0), "a plain run moved its exit status: {stderr}");
    assert!(
        stdout.contains("pin.current"),
        "the report does not name the reading that found the stale pin: {stdout}"
    );
    let (code, stdout, stderr) = consumer_run(&consumer, &["conformance", "--level", "L0"]);
    assert_ne!(code, Some(0), "a stale pin reached L0: {stdout}\n{stderr}");
    assert!(
        format!("{stdout}\n{stderr}").contains("pin.current"),
        "the refusal does not name the reading: {stdout}\n{stderr}"
    );
    // The commit gate carries the recheck: the pin as written, and the digest
    // of the bytes on disk, which is still the published one.
    let (code, stdout, stderr) = consumer_run(&consumer, &["check", "--strict"]);
    assert_eq!(
        code,
        Some(1),
        "a stale pin passed `check --strict`: {stdout}\n{stderr}"
    );
    for needle in [PIN_RULE, PIN_FINDING, stale, release.digest.as_str()] {
        assert!(
            stdout.contains(needle),
            "`check` does not say `{needle}`: {stdout}"
        );
    }
    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "validate"]);
    assert_eq!(code, Some(1), "a stale pin passed `validate`: {stderr}");
    let (_code, stdout, _stderr) = consumer_run(&consumer, &["gate", "--read-set", read_set]);
    assert!(
        stdout.contains(".headwater/taxonomy.yml"),
        "the gate does not name the moved pin: {stdout}"
    );
    for needle in [stale, release.digest.as_str()] {
        assert!(
            stderr.contains(needle),
            "`validate` does not say `{needle}`: {stderr}"
        );
    }

    // ---- Arm two: the bytes moved and the pin did not. -------------------
    //
    // The hand edit lands after the publish that computed the pinned digest and
    // after the vendor that installed the bytes it names.
    write(&authored, &pin);
    let installed =
        consumer.join(".headwater/packages/headwater-starter/doctrine/starter/starter.md");
    let carried = std::fs::read_to_string(&installed).expect("the installed doctrine reads");
    std::fs::write(
        &installed,
        format!("{carried}\n<!-- hand-edited after vendor, never through `vendor` -->\n"),
    )
    .expect("the hand edit writes");

    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "resolve"]);
    assert_eq!(
        code,
        Some(0),
        "the resolver refused the edited tree, so this pairing no longer holds: {stderr}"
    );

    // The commit gate sees the edit: the pin, a computed digest that is not
    // the pin, and the member that moved.
    let (code, stdout, stderr) = consumer_run(&consumer, &["check", "--strict"]);
    assert_eq!(
        code,
        Some(1),
        "an edited member passed `check --strict`: {stdout}\n{stderr}"
    );
    for needle in [
        PIN_RULE,
        PIN_FINDING,
        release.digest.as_str(),
        "doctrine/starter/starter.md",
    ] {
        assert!(
            stdout.contains(needle),
            "`check` does not say `{needle}`: {stdout}"
        );
    }
    let computed = headwater_resolve::release::digest_of(
        &headwater_resolve::release::members(
            &consumer.join(".headwater/packages/headwater-starter"),
        )
        .expect("the installed members read"),
    );
    assert_ne!(computed, release.digest, "the hand edit moved no byte");
    assert!(
        stdout.contains(&computed),
        "`check` does not name the digest it computed, `{computed}`: {stdout}"
    );
    let (code, _stdout, stderr) = consumer_run(&consumer, &["taxonomy", "validate"]);
    assert_eq!(
        code,
        Some(1),
        "an edited member passed `validate`: {stderr}"
    );
    let (_code, stdout, _stderr) = consumer_run(&consumer, &["gate", "--read-set", read_set]);
    assert!(
        stdout.contains("doctrine/starter/starter.md"),
        "the gate does not name the member that moved: {stdout}"
    );
    for needle in [
        release.digest.as_str(),
        computed.as_str(),
        "doctrine/starter/starter.md",
    ] {
        assert!(
            stderr.contains(needle),
            "`validate` does not say `{needle}`: {stderr}"
        );
    }

    // Moved bytes are refused ahead of every reading and at every level: a rule
    // set read out of a package whose bytes no longer match its record is a rule
    // set nothing can trust, so the run ends rather than reports. `--level` is
    // therefore not what makes this one non-zero, which is the difference
    // between this arm and the one above.
    for arguments in [
        vec!["conformance"],
        vec!["conformance", "--level", "L0"],
        vec!["conformance", "--level", "L1"],
    ] {
        let (code, stdout, stderr) = consumer_run(&consumer, &arguments);
        assert_eq!(
            code,
            Some(1),
            "an edited member passed `{arguments:?}`: {stdout}\n{stderr}"
        );
        let said = format!("{stdout}\n{stderr}");
        assert!(
            said.contains("doctrine/starter/starter.md"),
            "the refusal does not name the member that moved: {said}"
        );
        assert!(
            said.contains("no longer match"),
            "the refusal does not say the bytes moved: {said}"
        );
    }
}

#[test]
fn an_invalid_assembly_refuses_before_it_creates_output() {
    let root = Root::scratch("assembly-refuses");
    let source = assembly_source(&root, Arm::UnselectableBundle);
    let out = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(1), "{stderr}");
    assert!(stderr.contains("`missing`"), "{stderr}");
    assert!(stderr.contains("nothing was published"), "{stderr}");
    assert!(
        !out.exists(),
        "the refused run left partial output at {out:?}"
    );
}

/// A recipe whose selection leaves a name dangling is refused at the publish.
///
/// This is [#582](https://github.com/headwater-ai/headwater/issues/582), and
/// before it the same run exited 0 and printed `published acme/starter 2.0.0`.
/// The artifact it wrote was refused at the consumer's own `taxonomy resolve`,
/// so the publisher was told the handoff was good and the adopter found out it
/// was not.
///
/// **The case lives here rather than in `resolve/tests/publish.rs`, which is
/// where #582's own second clause puts it.** The assembly fixtures are here:
/// `assembly_source` already carries a source package with a recipe and a
/// broken/working boolean, and `an_invalid_assembly_refuses_before_it_creates
/// _output` above already asserts the exit status, the message and the disk over
/// it. A third assembly fixture in the other file would be a second enumeration
/// of one thing. The plain publish path has its own case, over there, beside the
/// widest-set refusal it belongs to.
///
/// Four assertions. The exit status is the one that moved. The recipe path and
/// the selection are what tell a publisher which line to edit. `beta` is the
/// name the omission left dangling, and it is also the bundle the advice names,
/// which is [#579](https://github.com/headwater-ai/headwater/issues/579)'s
/// recipe half arriving here. `!out.exists()` is the same disk claim every
/// refusal on this path makes.
#[test]
fn an_assembly_whose_selection_omits_a_bundle_another_bundle_needs_does_not_publish() {
    let root = Root::scratch("assembly-incomplete");
    let source = assembly_source(&root, Arm::IncompleteSelection);
    let out = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(1), "{stderr}");
    assert!(stderr.contains("nothing was published"), "{stderr}");
    assert!(
        stderr.contains("assembly.yml"),
        "the refusal names the recipe file to edit: {stderr}"
    );
    assert!(
        stderr.contains("[alpha]"),
        "the refusal names the selection: {stderr}"
    );
    assert!(
        stderr.contains("`beta`"),
        "the refusal names the dangling name: {stderr}"
    );
    assert!(
        stderr.contains("shelves.betas.kind"),
        "the refusal names the address that reads it: {stderr}"
    );
    // #579's recipe half. The consumer path already names the bundle to add;
    // a publisher who narrows a recipe is in the same position and, before
    // this, was told nothing at all.
    assert!(
        stderr.contains("`beta` declares 1 of the 1"),
        "the advice names the bundle to add back: {stderr}"
    );
    assert!(
        stderr.contains("`from.bundles:`"),
        "the advice names the key a publisher edits, not the consumer's: {stderr}"
    );
    assert!(
        !stderr.contains(".headwater/taxonomy.yml"),
        "the advice sends a publisher to the recipe and never to a consumer declaration: {stderr}"
    );
    assert!(
        !out.exists(),
        "the refused run left partial output at {out:?}"
    );
}

/// The same recipe with the selection complete still publishes.
///
/// The negative half, and it matters more than the positive: `publish` is the
/// verb a stranger runs to hand an artifact to somebody else, and a false
/// refusal stops a publisher shipping. `assembly_source`'s sound arm ships a
/// taxonomy that shares no name with `headwater/standard`, so this says the new
/// check admits a library nothing like this repository's.
///
/// `the_shipped_starter_recipe_publishes_vendors_and_resolves` is the other
/// half, over the real maintained source and the recipe an adopter is invited to
/// copy.
#[test]
fn an_assembly_whose_selection_is_complete_still_publishes() {
    let root = Root::scratch("assembly-complete");
    let source = assembly_source(&root, Arm::Sound);
    let out = root.path().join("release");

    let (code, stdout, stderr) = publish_assembly_from(root.path(), &source, &out);
    assert_eq!(code, Some(0), "{stderr}");
    assert!(stdout.contains("published acme/starter 2.0.0"), "{stdout}");
}

/// `nothing was published` and the disk agree, and the second run is the proof.
///
/// Three assertions, and the second is the one no wording change satisfies. The
/// third is what an adopter met: before this, the second run said *the output
/// directory holds files already*, so the person had to delete a directory the
/// tool had told them it never wrote to.
#[test]
fn a_publish_that_says_nothing_was_published_wrote_nothing() {
    let root = Root::copied("says-nothing");
    let out = root.path().join("release");

    let (code, first) = root.publish(&out);
    assert_eq!(code, Some(1), "{first}");
    assert!(
        first.contains("headwater: nothing was published"),
        "{first}"
    );
    assert!(
        first.contains("package.yml"),
        "the refusal does not name the manifest that declares the path: {first}"
    );
    assert!(
        first.contains("../../docs/taxonomies"),
        "the refusal does not name the declared value: {first}"
    );
    assert!(
        !out.exists(),
        "the run that published nothing left {:?}",
        std::fs::read_dir(&out).map(|entries| entries
            .filter_map(Result::ok)
            .map(|entry| entry.file_name())
            .collect::<Vec<_>>())
    );

    let (code, again) = root.publish(&out);
    assert_eq!(code, Some(1), "{again}");
    assert_eq!(
        again, first,
        "the second run met a different refusal, so the first left something behind"
    );
}

/// A mode, set on a path.
#[cfg(unix)]
fn mode(at: &Path, bits: u32) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(at, std::fs::Permissions::from_mode(bits)).expect("the mode is set");
}

/// Whether a mode can stop this process. See the note of the same name in
/// `headwater-resolve/tests/publish.rs`, and `engine/README.md` on why the
/// container half of the toolchain runs with `--user`.
#[cfg(unix)]
fn modes_hold(root: &Root) -> bool {
    let at = root.path().join("mode-probe");
    std::fs::create_dir_all(&at).expect("the probe is made");
    std::fs::write(at.join("held"), "x").expect("the probe holds a file");
    mode(&at, 0o300);
    let held = std::fs::read_dir(&at).is_err();
    mode(&at, 0o700);
    std::fs::remove_dir_all(&at).expect("the probe goes");
    held
}

/// `nothing was published` over a directory that could not be read, with a whole
/// artifact written into it.
///
/// This is the same claim as the case above and the state that reached it is the
/// narrower one. The root here is this repository, so the publish would
/// otherwise succeed and the write phase has every file of a real artifact to
/// put somewhere. `--out` is a directory holding a person's file at mode `0300`:
/// no `r`, so the precondition could not see the file, and `w` and `x`, so every
/// write below it lands. Read as absence, that published the artifact beside
/// their file, failed reading the directory back, printed `nothing was
/// published`, and ran an undo whose one instruction is to remove `--out`.
///
/// A verb that says it wrote nothing and wrote 39 files is the defect the issue
/// is named for. This is that defect through a doorway the `--out` precondition
/// does not cover, so the assertion is the disk rather than the wording.
#[cfg(unix)]
#[test]
fn a_publish_into_a_directory_it_cannot_read_writes_nothing_into_it() {
    let holder = Root::scratch("unreadable-out");
    if !modes_hold(&holder) {
        eprintln!("skipped: this process is root, and root reads through mode 0300");
        return;
    }
    let out = holder.path().join("release");
    std::fs::create_dir_all(&out).expect("the caller's directory is made");
    std::fs::write(out.join("theirs.txt"), "the caller's own file").expect("their file is written");
    mode(&out, 0o300);

    let (code, message) = publish_real_source_into(&out);
    mode(&out, 0o700);

    let left: Vec<String> = std::fs::read_dir(&out)
        .expect("it reads once the mode is back")
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .collect();
    assert_eq!(
        left,
        vec!["theirs.txt".to_string()],
        "the run published into a directory it could not read: {message}"
    );
    assert_eq!(code, Some(1), "{message}");
    assert!(
        message.contains("the output directory cannot be read"),
        "the refusal does not say why the directory was refused: {message}"
    );
}

/// An empty `--out` that the caller made is emptied again, not removed.
///
/// The precondition takes an empty directory as well as an absent one, so the
/// undo has two states to return to and this is the second. A person who ran
/// `mkdir release` first gets their directory back, empty.
///
/// **The root here is the colliding one and it used to be the copied one.** With
/// the copied root this case failed in phase 1, so `--out` was never written to
/// and the assertion was that an untouched empty directory is empty: it held
/// with the undo deleted. The root below reaches the write phase, so what is
/// removed between the failure and these lines is a part of an artifact that was
/// really on disk.
#[test]
fn an_output_directory_the_caller_made_is_left_empty_rather_than_removed() {
    let root = Root::colliding("caller-made");
    let out = root.path().join("release");
    std::fs::create_dir_all(&out).expect("the caller makes it");

    let (code, message) = root.publish(&out);
    assert_eq!(code, Some(1), "{message}");
    assert!(
        message.contains("headwater: nothing was published"),
        "{message}"
    );
    assert!(out.is_dir(), "the caller's own directory was removed");
    assert_eq!(
        std::fs::read_dir(&out)
            .expect("it reads")
            .filter_map(Result::ok)
            .count(),
        0,
        "the directory the caller made is not empty again: {message}"
    );
}

/// A write that fails leaves neither `--out` nor the directories the run made to
/// reach it, and the line a person reads is true of the disk.
///
/// `--out` is three levels below a directory that is not there either. `put`
/// reaches it with `create_dir_all`, so before this the verb printed `nothing
/// was published` and left three directories it had made standing.
#[test]
fn a_failed_write_leaves_neither_the_output_directory_nor_the_path_to_it() {
    let root = Root::colliding("nested-out");
    let nested = root.path().join("nested");
    let out = nested.join("a/b/c");

    let (code, message) = root.publish(&out);
    assert_eq!(code, Some(1), "{message}");
    assert!(
        message.contains("headwater: nothing was published"),
        "{message}"
    );
    assert!(
        !out.exists(),
        "the output directory is still there: {message}"
    );
    assert!(
        !nested.exists(),
        "the run that published nothing left the directories it made: {message}"
    );
}

/// #336's `--from <dir>`, exercised as a person would type it: two flags that
/// name the same thing are refused together, and `--from` alone publishes a
/// directory `--package` would never find under `.headwater/packages/`.
///
/// The directory this hands `--from` is `taxonomy-source/headwater-standard/`
/// itself, in this repository's own tree rather than a copy of it, precisely
/// because the point of the flag is that it reads a manifest `find` would never
/// walk to (it does not sit under `.headwater/packages/` at all). A copy would test the
/// read and hide the one thing worth proving: this path bypasses the lookup by
/// name entirely.
#[test]
fn from_and_package_together_are_refused_and_from_alone_publishes_the_relocated_source() {
    let source = repository().join("taxonomy-source/headwater-standard");
    let out_root = Root::scratch("from-flag");
    let out = out_root.path().join("release");

    let both = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish", "--package", "headwater/standard"])
        .arg("--from")
        .arg(&source)
        .arg("--out")
        .arg(&out)
        .arg("--root")
        .arg(repository())
        .output()
        .expect("the binary runs");
    assert_eq!(both.status.code(), Some(1));
    let both_err = String::from_utf8_lossy(&both.stderr);
    assert!(
        both_err.contains("--package") && both_err.contains("--from"),
        "the refusal does not name both flags: {both_err}"
    );
    assert!(!out.exists(), "the refused run wrote into --out anyway");

    let from_alone = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish"])
        .arg("--from")
        .arg(&source)
        .arg("--out")
        .arg(&out)
        .arg("--root")
        .arg(repository())
        .output()
        .expect("the binary runs");
    let stdout = String::from_utf8_lossy(&from_alone.stdout).into_owned();
    assert_eq!(
        from_alone.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&from_alone.stderr)
    );
    assert!(
        stdout.contains("published headwater/standard"),
        "the run did not report a publish: {stdout}"
    );
    assert!(
        out.join("release.yml").is_file(),
        "publishing `--from` a directory outside `.headwater/packages/` wrote no release record"
    );
}

/// The vendored bundles this repository ships agree with a fresh publish of
/// its own maintained source, file for file and byte for byte.
///
/// #407: `taxonomy-source/headwater-standard/package.yml` declares `bundles:
/// ../../docs/taxonomies`, and `headwater taxonomy publish` copies that
/// directory into `bundles/` inside the artifact `taxonomy vendor` later
/// installs at `.headwater/packages/headwater-standard/bundles/`. Nothing re-takes that
/// snapshot or compares it against the source it was taken from, so six of
/// seventy-two files drifted before anyone noticed: every rule that reads
/// this repository's corpus excludes `docs/taxonomies/**` (#350), and every
/// rule that reads the lock reads `bundle.yml`, never `doctrine.md` or a
/// fixtures `README.md`.
///
/// This is the comparison the issue's Done-when names, run against the real
/// publisher rather than a description of it: publish this repository's own
/// maintained source with [`publish_real_source_into`], the same call
/// [`from_and_package_together_are_refused_and_from_alone_publishes_the_relocated_source`]
/// makes, and diff the `bundles/` that publish just wrote against
/// `.headwater/packages/headwater-standard/bundles/`, the copy this repository ships. A
/// path present on one side and not the other, or a path whose bytes differ,
/// is exactly the drift #407 found by grepping for two deleted paths by
/// hand.
#[test]
fn the_vendored_bundles_agree_with_a_fresh_publish_of_the_maintained_source() {
    let root = Root::scratch("vendored-bundles");
    let out = root.path().join("release");

    let (code, message) = publish_real_source_into(&out);
    assert_eq!(
        code,
        Some(0),
        "the publish this comparison depends on failed: {message}"
    );

    let fresh = out.join("bundles");
    let vendored = repository().join(".headwater/packages/headwater-standard/bundles");

    let mut fresh_paths = relative_files(&fresh);
    let mut vendored_paths = relative_files(&vendored);
    fresh_paths.sort();
    vendored_paths.sort();

    let only_in_fresh: Vec<&String> = fresh_paths
        .iter()
        .filter(|p| !vendored_paths.contains(p))
        .collect();
    let only_in_vendored: Vec<&String> = vendored_paths
        .iter()
        .filter(|p| !fresh_paths.contains(p))
        .collect();
    let differing: Vec<&String> = fresh_paths
        .iter()
        .filter(|p| vendored_paths.contains(p))
        .filter(|p| {
            std::fs::read(fresh.join(p)).expect("the fresh file reads")
                != std::fs::read(vendored.join(p)).expect("the vendored file reads")
        })
        .collect();

    assert!(
        only_in_fresh.is_empty() && only_in_vendored.is_empty() && differing.is_empty(),
        ".headwater/packages/headwater-standard/bundles/ has drifted from docs/taxonomies/, the source \
         taxonomy-source/headwater-standard/package.yml declares.\n\
         only in a fresh publish, missing from the vendored copy: {only_in_fresh:?}\n\
         only in the vendored copy, missing from a fresh publish: {only_in_vendored:?}\n\
         present on both sides with different bytes: {differing:?}\n\
         Republish and revendor: `headwater taxonomy publish --from \
         taxonomy-source/headwater-standard --out <dir> && headwater taxonomy vendor <dir>`"
    );
}

/// `taxonomy publish --from <dir> --check` over a root the caller names, with
/// any further arguments after it.
fn publish_check(root: &Path, from: &Path, extra: &[&str]) -> (Option<i32>, String, String) {
    // Each run gets a private temporary directory of its own through
    // `TMPDIR`, which `std::env::temp_dir` reads, so this helper can say that
    // the run left nothing there on every path it took: a pass, a divergence
    // and a refusal alike. A directory shared with the other cases of this
    // binary could not say it, because they run at the same time.
    static RUN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let tmp = std::env::temp_dir().join(format!(
        "headwater-cli-publish-{}-check-tmp-{}",
        std::process::id(),
        RUN.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp).expect("the private temporary directory is made");
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish", "--check", "--from"])
        .arg(from)
        .args(extra)
        .arg("--root")
        .arg(root)
        .env("TMPDIR", &tmp)
        .output()
        .expect("the binary runs");
    let left = relative_files(&tmp);
    let _ = std::fs::remove_dir_all(&tmp);
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(
        left.is_empty(),
        "`--check` left its scratch publish behind: {left:?}\nstderr: {stderr}"
    );
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr,
    )
}

/// A scratch root that is both a publisher and a consumer of
/// `headwater/standard`, in the shape this repository is: the maintained
/// source under `taxonomy-source/`, the library its `bundles` scalar climbs
/// out to at `docs/taxonomies/`, and the vendored artifact under
/// `.headwater/packages/`.
fn publisher_and_consumer(label: &str) -> Root {
    let root = Root::scratch(label);
    for path in [
        "taxonomy-source/headwater-standard",
        ".headwater/packages/headwater-standard",
        "docs/taxonomies",
    ] {
        copy(&repository().join(path), &root.path().join(path));
    }
    std::fs::copy(
        repository().join(".headwater/taxonomy.yml"),
        root.path().join(".headwater/taxonomy.yml"),
    )
    .expect("the declaration copies");
    root
}

/// Every file under a root with its bytes, so a case can say the tree did not
/// move.
fn snapshot(root: &Path) -> Vec<(String, Vec<u8>)> {
    let mut files: Vec<(String, Vec<u8>)> = relative_files(root)
        .into_iter()
        .map(|path| {
            let bytes = std::fs::read(root.join(&path)).expect("the file reads");
            (path, bytes)
        })
        .collect();
    files.sort();
    files
}

/// #1139: a source `taxonomy.yml` changed without a republish leaves the
/// vendored copy stale, and before `--check` nothing said so. The bundles
/// comparison above covers `bundles/` alone, so an edit to `taxonomy.yml`,
/// `conformance.yml`, `package.yml` or `doctrine/` passed every gate.
///
/// The control comes first: a root whose vendored copy is a fresh publish of
/// its source passes, so a check that always fails does not pass this case.
/// Then one comment line in the source's `taxonomy.yml` fails the check, the
/// failure names the file, and the run leaves every file of the tree as it
/// was, because a check that writes is a publish.
#[test]
fn a_source_taxonomy_changed_without_a_republish_fails_publish_check_and_names_the_file() {
    let root = publisher_and_consumer("check-stale-taxonomy");
    let source = root.path().join("taxonomy-source/headwater-standard");

    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(
        code,
        Some(0),
        "a vendored copy that is a fresh publish of its source must pass the check.\nstdout: {stdout}\nstderr: {stderr}"
    );

    let taxonomy = source.join("taxonomy.yml");
    let mut text = std::fs::read_to_string(&taxonomy).expect("the source taxonomy reads");
    text.push_str("# an edit nobody republished\n");
    std::fs::write(&taxonomy, text).expect("the source taxonomy is edited");
    let before = snapshot(root.path());

    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(
        code,
        Some(1),
        "a source edited without a republish must fail the check.\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(
        stderr.contains("taxonomy.yml"),
        "the failure must name the member that moved: {stderr}"
    );
    assert!(
        !stderr.contains("bundles/"),
        "only the edited member moved, so no bundle may be named: {stderr}"
    );
    assert_eq!(
        before,
        snapshot(root.path()),
        "`--check` changed a file in the tree it was checking"
    );
}

/// `--check` compares against a directory it writes to itself, so an `--out`
/// is a request it cannot honor, and a `--package` source is by construction
/// the vendored copy it would be compared with.
#[test]
fn publish_check_refuses_out_package_and_a_missing_from() {
    let root = publisher_and_consumer("check-refusals");
    let source = root.path().join("taxonomy-source/headwater-standard");
    let out = root.path().join("release");

    let (code, _, stderr) = publish_check(
        root.path(),
        &source,
        &["--out", out.to_str().expect("utf-8")],
    );
    assert_eq!(code, Some(1), "`--check --out` must be refused: {stderr}");
    assert!(stderr.contains("--out"), "{stderr}");
    assert!(
        !out.exists(),
        "a refused `--check --out` wrote the artifact"
    );

    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args([
            "taxonomy",
            "publish",
            "--check",
            "--package",
            "headwater/standard",
        ])
        .arg("--root")
        .arg(root.path())
        .output()
        .expect("the binary runs");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(1),
        "`--check --package` must be refused: {stderr}"
    );
    assert!(stderr.contains("`--package`"), "{stderr}");

    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish", "--check"])
        .arg("--root")
        .arg(root.path())
        .output()
        .expect("the binary runs");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code(),
        Some(1),
        "`--check` without `--from` must be refused: {stderr}"
    );
    assert!(
        stderr.contains("Name the source with `--from <dir>`"),
        "{stderr}"
    );
}

/// A root with a source and no vendored copy of it has nothing to compare, and
/// the refusal names the package it looked for.
#[test]
fn publish_check_with_no_vendored_copy_is_refused_and_names_the_package() {
    let root = publisher_and_consumer("check-no-vendored");
    std::fs::remove_dir_all(root.path().join(".headwater/packages/headwater-standard"))
        .expect("the vendored copy is removed");
    let source = root.path().join("taxonomy-source/headwater-standard");

    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(
        code,
        Some(1),
        "no vendored copy must fail the check.\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(stderr.contains("headwater/standard"), "{stderr}");
}

/// Replace the one line of a file that starts with `prefix` (after its
/// indentation) with `line`, keeping the indentation.
fn replace_line(path: &Path, prefix: &str, line: &str) {
    let text = std::fs::read_to_string(path).expect("the file reads");
    let mut hit = false;
    let edited: Vec<String> = text
        .lines()
        .map(|each| {
            let body = each.trim_start();
            match !hit && body.starts_with(prefix) {
                true => {
                    hit = true;
                    format!("{}{line}", &each[..each.len() - body.len()])
                }
                false => each.to_string(),
            }
        })
        .collect();
    assert!(hit, "no line of {} starts with {prefix}", path.display());
    std::fs::write(path, edited.join("\n") + "\n").expect("the file is written");
}

/// A member the source gained since the last publish is one the vendored copy
/// lacks, and a member the source lost is one the vendored copy still carries.
/// Each is named on its own line, and the digest over the member list moves.
#[test]
fn a_member_the_source_adds_or_drops_is_named_on_its_own_line() {
    let root = publisher_and_consumer("check-added");
    let source = root.path().join("taxonomy-source/headwater-standard");
    std::fs::write(
        source.join("doctrine/extra.md"),
        "# Extra\n\nA page nobody published.\n",
    )
    .expect("the added member is written");
    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(code, Some(1), "stdout: {stdout}\nstderr: {stderr}");
    assert!(
        stderr.contains(
            "doctrine/extra.md: a fresh publish writes it, and the vendored copy lacks it"
        ),
        "{stderr}"
    );
    assert!(stderr.contains("the vendored digest is"), "{stderr}");

    let root = publisher_and_consumer("check-dropped");
    let source = root.path().join("taxonomy-source/headwater-standard");
    std::fs::remove_file(
        root.path()
            .join("docs/taxonomies/diataxis-site/templates/tutorial.md"),
    )
    .expect("the dropped member is removed");
    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(code, Some(1), "stdout: {stdout}\nstderr: {stderr}");
    assert!(
        stderr.contains(
            "bundles/diataxis-site/templates/tutorial.md: the vendored copy carries it, and a fresh publish does not write it"
        ),
        "{stderr}"
    );
    assert!(stderr.contains("the vendored digest is"), "{stderr}");
}

/// The vendored record is compared by what it states and not by its bytes. A
/// field it states that a fresh publish does not state fails the check with
/// every member agreeing, and a comment header an engine release rewords
/// passes it.
#[test]
fn the_vendored_record_is_compared_by_what_it_states_and_not_by_its_bytes() {
    let root = publisher_and_consumer("check-record-field");
    let source = root.path().join("taxonomy-source/headwater-standard");
    let record = root
        .path()
        .join(".headwater/packages/headwater-standard/release.yml");
    replace_line(&record, "version:", "version: 0.0.1");
    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(
        code,
        Some(1),
        "a vendored record that states another version must fail.\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(stderr.contains("release.yml:"), "{stderr}");

    let root = publisher_and_consumer("check-record-header");
    let source = root.path().join("taxonomy-source/headwater-standard");
    let record = root
        .path()
        .join(".headwater/packages/headwater-standard/release.yml");
    let text = std::fs::read_to_string(&record).expect("the record reads");
    std::fs::write(
        &record,
        format!("# a header an engine release reworded\n{text}"),
    )
    .expect("the header is edited");
    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(
        code,
        Some(0),
        "a reworded comment header alone must pass.\nstdout: {stdout}\nstderr: {stderr}"
    );
}

/// A vendored file edited by hand fails the check too, and the message says
/// what is known rather than that the source changed.
#[test]
fn a_hand_edited_vendored_copy_fails_and_the_message_does_not_blame_the_source() {
    let root = publisher_and_consumer("check-hand-edited");
    let source = root.path().join("taxonomy-source/headwater-standard");
    let vendored = root
        .path()
        .join(".headwater/packages/headwater-standard/taxonomy.yml");
    let mut text = std::fs::read_to_string(&vendored).expect("the vendored taxonomy reads");
    text.push_str("# a hand edit\n");
    std::fs::write(&vendored, text).expect("the vendored taxonomy is edited");
    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(code, Some(1), "stdout: {stdout}\nstderr: {stderr}");
    assert!(
        stderr.contains("taxonomy.yml: the vendored bytes are"),
        "{stderr}"
    );
    assert!(
        stderr.contains("or somebody edited the vendored copy"),
        "the message must not say the source changed when it may not have: {stderr}"
    );
}

/// `--from` naming the vendored copy has no source to compare, and a directory
/// that declares the name with no release record is not a vendored copy.
#[test]
fn publish_check_refuses_the_vendored_copy_as_its_source_and_a_copy_with_no_record() {
    let root = publisher_and_consumer("check-from-vendored");
    let vendored = root.path().join(".headwater/packages/headwater-standard");
    let (code, stdout, stderr) = publish_check(root.path(), &vendored, &[]);
    assert_eq!(code, Some(1), "stdout: {stdout}\nstderr: {stderr}");
    assert!(stderr.contains("names the vendored copy"), "{stderr}");

    let root = publisher_and_consumer("check-no-record");
    let source = root.path().join("taxonomy-source/headwater-standard");
    std::fs::remove_file(
        root.path()
            .join(".headwater/packages/headwater-standard/release.yml"),
    )
    .expect("the record is removed");
    let (code, stdout, stderr) = publish_check(root.path(), &source, &[]);
    assert_eq!(code, Some(1), "stdout: {stdout}\nstderr: {stderr}");
    assert!(
        stderr.contains("carries no readable release record"),
        "{stderr}"
    );
}

/// What CI runs: this repository's own source against its own vendored copy.
#[test]
fn this_repository_passes_publish_check_on_its_own_source() {
    let (code, stdout, stderr) = publish_check(
        &repository(),
        &repository().join("taxonomy-source/headwater-standard"),
        &[],
    );
    assert_eq!(
        code,
        Some(0),
        "the vendored copy of headwater/standard is not a fresh publish of \
         taxonomy-source/headwater-standard.\nstdout: {stdout}\nstderr: {stderr}"
    );
}

/// #518: an artifact carries no bundle reference corpus, and the publisher
/// keeps every one of its own.
///
/// Spec 7's Publishing section rules that publication takes the package
/// directory whole, and it names one exception: a `fixtures/` directory at the
/// root of a bundle. Those corpora are how a publisher measures its own
/// taxonomy against prose it controls. No consumer verb opens one, and before
/// this exception they were 71 of the 102 members of this repository's own
/// release record.
///
/// This runs the real publisher over the maintained source rather than a
/// description of it, and it holds the publisher's side as well, because the
/// exception is about what the artifact carries and it must delete nothing.
#[test]
fn a_fresh_publish_carries_no_bundle_fixtures_and_the_publisher_keeps_its_own() {
    let root = Root::scratch("bundle-fixtures");
    let out = root.path().join("release");

    let (code, message) = publish_real_source_into(&out);
    assert_eq!(
        code,
        Some(0),
        "the publish this case depends on failed: {message}"
    );

    let mut carried: Vec<String> = relative_files(&out.join("bundles"))
        .into_iter()
        .filter(|path| path.split('/').nth(1) == Some("fixtures"))
        .collect();
    carried.sort();
    assert!(
        carried.is_empty(),
        "the artifact carries {} bundle fixture files that no consumer verb opens: {carried:#?}",
        carried.len()
    );

    assert!(
        repository()
            .join("docs/taxonomies/standards-spec/fixtures/README.md")
            .is_file(),
        "the exception is about the artifact. The publisher's own reference corpora stay where \
         they are"
    );
}

/// #518: no file the artifact carries links at a path inside the bundle tree
/// that the artifact does not carry.
///
/// A publish decides the shape of `bundles/`, and this case is the reason that
/// decision is not free. Dropping each bundle's own corpus left fifteen links
/// across seven carried files pointing at `fixtures/README.md`,
/// `fixtures/n8n/README.md` and `../<bundle>/fixtures/README.md`. Every one of
/// them resolved in the publisher's tree and in the artifact before, and none
/// resolved in the artifact after. **Nothing else in this repository can see
/// that.** The referential integrity a publish runs reads `contents` key
/// scalars and never a carried file's body, `release::verify` compares the
/// record against the bytes and reads no body either, and `docs/taxonomies/**`
/// is outside the corpus root, so `link.fragment.unresolved` never opens the
/// sources.
///
/// **The population is enumerated and never listed.** Every `.md` file in the
/// artifact, every inline link in it, and every target that lands inside
/// `bundles/` after the `..` segments are resolved. A link that climbs out of
/// the artifact is passed over here, because this case asks only about the
/// bundle tree a publish reshapes. It is no longer passed over anywhere:
/// #633 ruled that a doctrine reference to a document the artifact does not
/// carry is written as an absolute URL, and
/// `every_relative_link_a_carried_file_writes_resolves_inside_the_artifact`
/// below judges both classes — the target inside `bundles/` that is missing,
/// and the target that climbs clear of the artifact root.
///
/// A code span and a fenced block are read past, because this repository
/// prints a link as an example inside both, and a check that reddens on correct
/// Markdown is a check the first person it annoys turns off.
#[test]
fn no_file_the_artifact_carries_links_into_a_bundle_tree_it_does_not_carry() {
    let root = Root::scratch("bundle-links");
    let out = root.path().join("release");

    let (code, message) = publish_real_source_into(&out);
    assert_eq!(
        code,
        Some(0),
        "the publish this case depends on failed: {message}"
    );

    let mut read = 0usize;
    let mut dangling: Vec<String> = Vec::new();
    for member in relative_files(&out) {
        if !member.ends_with(".md") {
            continue;
        }
        let text = std::fs::read_to_string(out.join(&member)).expect("a member reads");
        let directory = Path::new(&member)
            .parent()
            .unwrap_or(Path::new(""))
            .to_owned();
        for target in markdown_links(&text) {
            let body = target.split('#').next().unwrap_or_default();
            if body.is_empty() || body.contains("://") {
                continue;
            }
            let Some(at) = inside_the_artifact(&directory, body) else {
                continue;
            };
            if !at.starts_with("bundles") {
                continue;
            }
            read += 1;
            if !out.join(&at).exists() {
                dangling.push(format!("{member} -> {target}"));
            }
        }
    }

    // A scanner that reads nothing passes everything, and this one reads the
    // real library rather than a fixture, so it says how much it saw.
    assert!(
        read > 0,
        "the scanner found no link into the bundle tree at all, so it held nothing"
    );
    assert!(
        dangling.is_empty(),
        "{} of the {read} links into the bundle tree do not resolve inside the artifact. Every \
         one of them resolves in `docs/taxonomies/`, so the publish carried the prose and left \
         the target behind:\n{dangling:#?}",
        dangling.len()
    );
}

/// #633: every relative link a carried `.md` file writes resolves to a file the
/// artifact carries, so a consumer who vendors this package receives no dead
/// relative link at all.
///
/// This is the bound the ruling on #633 needs, and it is wider than the two
/// cases around it. The ruling says a doctrine reference to a document the
/// artifact does not carry is written as an absolute URL. An absolute URL is
/// read past here, so the only relative link that reaches the assertions is one
/// the artifact is expected to resolve.
///
/// **Two classes, and each returns by a different route.** A target that lands
/// inside `bundles/` and is missing is the class the sibling case above already
/// holds. A target that climbs clear of the artifact root is the class nothing
/// read before this case: `../../spec/07-…` written from
/// `bundles/<name>/doctrine.md` normalizes past the artifact root, so the #619
/// publish rule never sees it (the target is not inside the artifact),
/// `link.fragment.unresolved` never opens the file (`docs/taxonomies/**` is
/// outside the corpus root), and `inside_the_artifact` returns `None` for it,
/// which every other walker in this file reads as "skip". It measures 0 today
/// and it is asserted as a bound rather than recorded as a count, because the
/// way the defect this issue repairs comes back is one doctrine author writing
/// one `../../` link that nothing else in this repository can see.
///
/// A `bundle.yml` is out of scope here on purpose. Three of the fifty-two pairs
/// #633 repaired were written in a YAML comment, and
/// `the_real_package_records_exactly_the_references_it_carries` below walks
/// every member rather than the `.md` ones, so the record holds those.
#[test]
fn every_relative_link_a_carried_file_writes_resolves_inside_the_artifact() {
    let root = Root::scratch("relative-links");
    let out = root.path().join("release");

    let (code, message) = publish_real_source_into(&out);
    assert_eq!(
        code,
        Some(0),
        "the publish this case depends on failed: {message}"
    );

    let mut read = 0usize;
    let mut dangling: Vec<String> = Vec::new();
    let mut escaping: Vec<String> = Vec::new();
    for member in relative_files(&out) {
        if !member.ends_with(".md") {
            continue;
        }
        let text = std::fs::read_to_string(out.join(&member)).expect("a member reads");
        let directory = Path::new(&member)
            .parent()
            .unwrap_or(Path::new(""))
            .to_owned();
        for target in markdown_links(&text) {
            let body = target.split('#').next().unwrap_or_default();
            if body.is_empty() || body.contains("://") || body.starts_with("mailto:") {
                continue;
            }
            read += 1;
            let Some(at) = inside_the_artifact(&directory, body) else {
                escaping.push(format!("{member} -> {target}"));
                continue;
            };
            if !out.join(&at).exists() {
                dangling.push(format!("{member} -> {target}"));
            }
        }
    }

    // A scanner that reads nothing passes everything, and this one reads the
    // real library rather than a fixture, so it says how much it saw.
    assert!(
        read > 0,
        "the scanner found no relative link in any carried file, so it held nothing"
    );
    assert!(
        escaping.is_empty(),
        "{} of the {read} relative links a carried file writes climb clear of the artifact root. \
         #633 ruled that a reference to a document the artifact does not carry is written as an \
         absolute URL, and nothing else in this repository reads these:\n{escaping:#?}",
        escaping.len()
    );
    assert!(
        dangling.is_empty(),
        "{} of the {read} relative links a carried file writes name a path the artifact does not \
         carry:\n{dangling:#?}",
        dangling.len()
    );
}

/// #619: the real package publishes, and the population its manifest records is
/// exactly the population the artifact carries.
///
/// Two clauses of the issue meet in one case. The first is that `headwater
/// taxonomy publish` still exits 0 on this repository's own package, proved on
/// the maintained source rather than on a fixture, because the bar as filed
/// refused it: 122 references over 51 pairs, none of them resolvable in any
/// artifact this project has published. The second is that the record which
/// admits them is held to the artifact in both directions.
///
/// **Both directions, and each one catches a different mistake.** A recorded
/// pair the artifact does not dangle is a line somebody repaired and forgot to
/// delete, and a record that outlives its population is a record that quietly
/// admits a reference nobody looked at. A dangling pair the record does not hold
/// cannot reach here at all — publish refuses it — so that half of the equality
/// is a statement that the engine and this walker agree about what dangles,
/// which is the reason this walker is written here rather than called out of the
/// crate under test.
///
/// The walker reads every member and not only the `.md` ones, because two
/// `bundle.yml` files in this library write a link inside a comment.
#[test]
fn the_real_package_records_exactly_the_references_it_carries() {
    let root = Root::scratch("recorded-references");
    let out = root.path().join("release");

    let (code, message) = publish_real_source_into(&out);
    assert_eq!(
        code,
        Some(0),
        "the maintained source no longer publishes, which is the clause this case holds: {message}"
    );

    let members: Vec<String> = relative_files(&out);
    let mut dangling: Vec<(String, String)> = Vec::new();
    let mut read = 0usize;
    for member in &members {
        let Ok(text) = std::fs::read_to_string(out.join(member)) else {
            continue;
        };
        let directory = Path::new(member)
            .parent()
            .unwrap_or(Path::new(""))
            .to_owned();
        for written in markdown_links(&text) {
            let target = written.split('#').next().unwrap_or_default();
            if target.is_empty() || target.contains("://") || target.starts_with("mailto:") {
                continue;
            }
            let Some(at) = inside_the_artifact(&directory, target) else {
                continue;
            };
            read += 1;
            if !out.join(&at).exists() {
                dangling.push((member.clone(), at.display().to_string()));
            }
        }
    }
    dangling.sort();
    dangling.dedup();

    assert!(
        read > 0,
        "the walker resolved no reference at all, so it held nothing"
    );

    let recorded = recorded_references(&out.join("package.yml"));
    assert_eq!(
        recorded,
        dangling,
        "the manifest records {} pairs and the artifact carries {} of {read} resolved references \
         that resolve nowhere. A pair on the left and not on the right is a repair nobody deleted \
         the record of; a pair on the right and not on the left could not have published at all",
        recorded.len(),
        dangling.len()
    );

    // The publish said so on standard error, and the count it printed is the
    // one this walker derived. `dropped` is the other line that reaches here
    // and it names a `contents` key, so a substring of the count alone would
    // pass on the wrong line.
    //
    // #633 emptied the record, and an empty record prints no line at all rather
    // than a line reporting zero. So the assertion is on the account either way:
    // a population is reported when there is one, and nothing is said when there
    // is none. Reading only the first half here would let the account disappear
    // from a run that still ships a population.
    let account = "references that resolve nowhere inside it";
    if recorded.is_empty() {
        assert!(
            !message.contains(account),
            "the manifest records nothing and the publish still reported a population: {message}"
        );
    } else {
        assert!(
            message.contains(&format!(
                "the artifact records {} {account}",
                recorded.len()
            )),
            "the publish did not report the population it shipped: {message}"
        );
    }
}

/// The `(member, target)` pairs a manifest records under
/// `unresolved_references`, sorted.
///
/// Read by hand rather than through the engine's loader, so what this case
/// compares is the file as written and not the engine's reading of it. The block
/// is a mapping of sequences at a fixed indentation, which is the whole shape
/// the key takes.
fn recorded_references(manifest: &Path) -> Vec<(String, String)> {
    let text = std::fs::read_to_string(manifest).expect("the published manifest reads");
    let mut pairs = Vec::new();
    let mut member: Option<String> = None;
    let mut inside = false;
    for line in text.lines() {
        if line.starts_with("unresolved_references:") {
            inside = true;
            continue;
        }
        if !inside {
            continue;
        }
        if line.starts_with('#') || line.trim().is_empty() {
            continue;
        }
        match line.strip_prefix("    - ") {
            Some(target) => match &member {
                Some(at) => pairs.push((at.clone(), target.trim().to_string())),
                None => panic!("a recorded target with no member above it: {line}"),
            },
            None => match line.strip_prefix("  ").map(str::trim_end) {
                Some(key) if key.ends_with(':') && !key.starts_with(' ') => {
                    member = Some(key.trim_end_matches(':').to_string());
                }
                // Anything at the left margin ends the block.
                _ => break,
            },
        }
    }
    pairs.sort();
    pairs
}

/// #619: a flattened package inherits no record of another artifact's
/// references.
///
/// `flatten::manifest` copies every source key it does not replace, and
/// `unresolved_references` rode through on the first cut. The starter recipe
/// then shipped four members and a record of 51 pairs naming members like
/// `bundles/README.md` that its artifact does not hold, and the publish printed
/// the count of them. **That is a standing admission**: a recipe inherits
/// permission to dangle a reference it does not contain, and the first
/// assembly that writes a real one at a recorded path is admitted by it.
///
/// A flattened package takes a new member layout — `doctrine` lands at
/// `doctrine/<recipe>/` and the bundle tree is absorbed — so not one recorded
/// member of the source is carried, and the key is dropped rather than
/// filtered. What the recipe's own publish finds is what its own record would
/// hold, and today that is nothing at all.
#[test]
fn the_shipped_starter_recipe_inherits_no_record_of_another_artifacts_references() {
    let root = Root::scratch("starter-record");
    let source = repository().join("taxonomy-source/headwater-standard");
    let artifact = root.path().join("release");

    let (code, _stdout, stderr) = publish_assembly_from(&repository(), &source, &artifact);
    assert_eq!(code, Some(0), "{stderr}");

    let carried = std::fs::read_to_string(artifact.join("package.yml"))
        .expect("the flattened manifest reads");
    assert!(
        !carried.contains(headwater_resolve::package::RECORDED_REFERENCES),
        "the flattened manifest inherited a record written for another artifact:\n{carried}"
    );
    assert!(
        recorded_references(&artifact.join("package.yml")).is_empty(),
        "the flattened artifact records a pair it cannot be about"
    );
    assert!(
        !stderr.contains("resolve nowhere inside it"),
        "the publish reported a population this artifact does not carry: {stderr}"
    );

    // The assertions above are all satisfied by a source that records nothing,
    // and after #633 the maintained source is one. So the control is a copy of
    // that source with a record planted back into it: the plain publish of the
    // copy carries the pair, and the flattened publish of the same copy carries
    // none. That is the difference this case is about, and the maintained source
    // can no longer show it.
    let planted = root.path().join("planted");
    let source = planted.join("source/headwater-standard");
    copy_tree(
        &repository().join("taxonomy-source/headwater-standard"),
        &source,
    );
    // `contents.bundles` names `../../docs/taxonomies` from the source
    // directory, so the copy has to sit two levels under a tree that carries
    // one.
    let bundles = planted.join("docs/taxonomies");
    copy_tree(&repository().join("docs/taxonomies"), &bundles);

    let readme = bundles.join("README.md");
    let mut body = std::fs::read_to_string(&readme).expect("the copied README reads");
    body.push_str("\n[a planted reference](../../spec/07-distribution-and-federation.md)\n");
    std::fs::write(&readme, body).expect("the copied README writes");
    let manifest = source.join("package.yml");
    let mut declared = std::fs::read_to_string(&manifest).expect("the copied manifest reads");
    declared.push_str(&format!(
        "\n{}:\n  bundles/README.md:\n    - spec/07-distribution-and-federation.md\n",
        headwater_resolve::package::RECORDED_REFERENCES
    ));
    std::fs::write(&manifest, declared).expect("the copied manifest writes");

    let plain = root.path().join("plain");
    // The root is the copy and not the repository: a publish refuses a
    // `contents.bundles` that resolves outside the tree it is reading.
    let (code, _stdout, stderr) = publish_plain_from(&planted, &source, &plain);
    assert_eq!(
        code,
        Some(0),
        "the planted source no longer publishes: {stderr}"
    );
    assert_eq!(
        recorded_references(&plain.join("package.yml")),
        vec![(
            "bundles/README.md".to_string(),
            "spec/07-distribution-and-federation.md".to_string()
        )],
        "the plant did not reach the plain artifact, so the control holds nothing"
    );

    let flattened = root.path().join("planted-recipe");
    let (code, _stdout, stderr) = publish_assembly_from(&planted, &source, &flattened);
    assert_eq!(code, Some(0), "{stderr}");
    let carried = std::fs::read_to_string(flattened.join("package.yml"))
        .expect("the flattened manifest reads");
    assert!(
        !carried.contains(headwater_resolve::package::RECORDED_REFERENCES),
        "a recipe flattened from a source that records a pair inherited the record:\n{carried}"
    );
}

/// Every file under `from`, copied to `to`, directories made as they are met.
fn copy_tree(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).expect("the destination directory is made");
    for entry in std::fs::read_dir(from).expect("the source directory reads") {
        let entry = entry.expect("an entry reads");
        let target = to.join(entry.file_name());
        if entry.file_type().expect("a file type reads").is_dir() {
            copy_tree(&entry.path(), &target);
        } else {
            std::fs::copy(entry.path(), &target).expect("a file copies");
        }
    }
}

/// The destination of every inline Markdown link on a line that is not inside a
/// fenced block, with a code span removed first and a CommonMark link title
/// dropped.
fn markdown_links(text: &str) -> Vec<String> {
    let mut found = Vec::new();
    let mut fenced = false;
    for line in text.lines() {
        let opener = line.trim_start();
        if opener.starts_with("```") || opener.starts_with("~~~") {
            fenced = !fenced;
            continue;
        }
        if fenced {
            continue;
        }
        let mut outside = String::new();
        let mut spanned = false;
        for character in line.chars() {
            match character {
                '`' => spanned = !spanned,
                _ if !spanned => outside.push(character),
                _ => {}
            }
        }
        let characters: Vec<char> = outside.chars().collect();
        let mut at = 0;
        while at < characters.len() {
            if characters[at] != '[' {
                at += 1;
                continue;
            }
            let Some(close) = (at..characters.len()).find(|index| characters[*index] == ']') else {
                break;
            };
            if characters.get(close + 1) != Some(&'(') {
                at = close + 1;
                continue;
            }
            let Some(end) = (close + 2..characters.len()).find(|index| characters[*index] == ')')
            else {
                break;
            };
            let destination: String = characters[close + 2..end].iter().collect();
            let destination = destination
                .split_whitespace()
                .next()
                .unwrap_or_default()
                .trim_start_matches('<')
                .trim_end_matches('>');
            if !destination.is_empty() {
                found.push(destination.to_string());
            }
            at = end + 1;
        }
    }
    found
}

/// Where a relative link written in `directory` lands inside the artifact, or
/// `None` where it climbs out of it.
///
/// The resolution is lexical, because the artifact carries no symlink a publish
/// left dereferenced and the question is where the text points.
fn inside_the_artifact(directory: &Path, target: &str) -> Option<PathBuf> {
    let mut at = PathBuf::new();
    for part in directory.join(target).components() {
        match part {
            std::path::Component::ParentDir => {
                if !at.pop() {
                    return None;
                }
            }
            std::path::Component::CurDir => {}
            std::path::Component::Normal(name) => at.push(name),
            _ => return None,
        }
    }
    Some(at)
}

/// Every regular file under `root`, as a path relative to it, in no
/// particular order.
/// #353: the digest a publisher hands on is readable without a text search.
///
/// The prose run prints it inside a paragraph. `--json` writes one document
/// whose `digest` member is the same number, and the number both are held to is
/// the one in the record on disk, so this holds the document to the artifact
/// and not only to the other rendering. The member list is held to the record
/// the same way, and `version` names the document's own shape rather than the
/// engine, which is what `json.rs` asks of every document this binary writes.
#[test]
fn a_json_publish_carries_the_digest_a_consumer_pins() {
    let base = Path::new(env!("CARGO_TARGET_TMPDIR")).join("publish-json");
    let _ = std::fs::remove_dir_all(&base);
    let prose_out = base.join("prose");
    let json_out = base.join("json");

    let (code, prose, stderr) = publish_real_source(&prose_out, false);
    assert_eq!(code, Some(0), "{stderr}");
    let (code, document, stderr) = publish_real_source(&json_out, true);
    assert_eq!(code, Some(0), "{stderr}");
    // #619 put one account on this stream that a successful run makes, and
    // `dropped` above it has had the same shape since #580: both are things the
    // publisher asked for that the artifact represents differently, and both are
    // printed in either output mode so a `--json` caller is not the one reader
    // who never hears them. So the guard subtracts the account it expects rather
    // than being dropped — anything else here on a run that succeeded is still a
    // defect, and standard output is still one document.
    let unaccounted: Vec<&str> = stderr
        .lines()
        .filter(|line| !line.contains("references that resolve nowhere inside it"))
        .filter(|line| !line.contains(headwater_resolve::package::RECORDED_REFERENCES))
        .filter(|line| !line.trim().is_empty())
        .collect();
    assert!(
        unaccounted.is_empty(),
        "a JSON run that succeeded accounts for nothing on standard error beyond the population \
         the artifact records: {unaccounted:#?}"
    );

    let record = std::fs::read_to_string(json_out.join("release.yml")).expect("the record reads");
    let record = headwater_resolve::release::read(&record).expect("the record parses");

    let value = headwater_yaml::load(&document)
        .unwrap_or_else(|errors| panic!("the document does not parse: {errors:?}\n{document}"))
        .value;
    let map = value.as_map().expect("the document is an object");
    let text = |key: &str| -> Option<String> {
        map.get(key)
            .and_then(|spanned| spanned.value.as_scalar())
            .map(headwater_yaml::core_schema::as_str)
            .map(str::to_string)
    };

    assert_eq!(
        text("version").as_deref(),
        Some(headwater_resolve::release::DOCUMENT),
        "the document names its own shape"
    );
    assert_eq!(text("digest").as_deref(), Some(record.digest.as_str()));
    assert_eq!(text("out").as_deref(), json_out.to_str());

    let package = map
        .get("package")
        .and_then(|spanned| spanned.value.as_map())
        .expect("a `package` member");
    let identity = |key: &str| -> Option<String> {
        package
            .get(key)
            .and_then(|spanned| spanned.value.as_scalar())
            .map(headwater_yaml::core_schema::as_str)
            .map(str::to_string)
    };
    assert_eq!(identity("name").as_deref(), Some(record.package.as_str()));
    assert_eq!(
        identity("version").as_deref(),
        Some(record.version.as_str())
    );
    assert_eq!(identity("requires_engine"), record.requires_engine);

    let members = map
        .get("members")
        .and_then(|spanned| spanned.value.as_seq())
        .expect("a `members` member");
    assert_eq!(members.len(), record.members.len());
    for (written, recorded) in members.iter().zip(&record.members) {
        let member = written.value.as_map().expect("a member is an object");
        let field = |key: &str| -> Option<&str> {
            member
                .get(key)
                .and_then(|spanned| spanned.value.as_scalar())
                .map(headwater_yaml::core_schema::as_str)
        };
        assert_eq!(field("path"), Some(recorded.path.as_str()));
        assert_eq!(field("digest"), Some(recorded.digest.as_str()));
    }

    // The prose run and the JSON run published one artifact twice, and the
    // paragraph a person reads carries the number the document carries.
    assert!(prose.contains(&record.digest), "{prose}");
}

fn relative_files(root: &Path) -> Vec<String> {
    fn walk(base: &Path, dir: &Path, into: &mut Vec<String>) {
        for entry in std::fs::read_dir(dir).expect("the directory reads") {
            let entry = entry.expect("the entry reads").path();
            if entry.is_dir() {
                walk(base, &entry, into);
            } else {
                into.push(
                    entry
                        .strip_prefix(base)
                        .expect("every entry is under base")
                        .to_string_lossy()
                        .into_owned(),
                );
            }
        }
    }
    let mut into = Vec::new();
    walk(root, root, &mut into);
    into
}

// ---------------------------------------------------------------------------
// `--clear-killed`. #485.
// ---------------------------------------------------------------------------

/// `taxonomy publish --clear-killed`, as a person types it, over a root the
/// caller names.
fn publish_clearing_killed(root: &Path, out: &Path) -> (Option<i32>, String) {
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(["taxonomy", "publish", "--package", "headwater/standard"])
        .arg("--clear-killed")
        .arg("--out")
        .arg(out)
        .arg("--root")
        .arg(root)
        .output()
        .expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// **The decisive case.** The flag over a non-empty `--out` with no staging
/// directory beside it exits 1 with the refusal a run without the flag gives,
/// and the file that was there is still there byte for byte.
///
/// The exit status is asserted as 1 and not merely as non-zero, because clap
/// exits 2 on an argument it does not know: a case that took non-zero for a
/// refusal would pass against a binary that never grew the flag at all. That is
/// the shape this whole target exists for.
#[test]
fn the_flag_over_an_unrelated_directory_refuses_and_every_file_survives() {
    let root = Root::copied("clear-killed-unrelated");
    let out = root.path().join("artifact");
    std::fs::create_dir_all(&out).expect("the caller's directory is made");
    std::fs::write(out.join("theirs.txt"), "the caller's own file").expect("their file is written");

    let (status, message) = publish_clearing_killed(root.path(), &out);
    assert_eq!(status, Some(1), "the flag did not refuse: {message}");
    assert!(
        message.contains("nothing was published"),
        "the refusal is not the publish's own: {message}"
    );
    assert_eq!(
        std::fs::read_to_string(out.join("theirs.txt")).expect("their file reads"),
        "the caller's own file"
    );
    assert_eq!(
        relative_files(&out),
        vec!["theirs.txt".to_string()],
        "the flag wrote or removed something under the caller's directory"
    );
}

/// The flag over the residue of a killed direct write clears both paths and
/// publishes the real artifact in the same run, exit 0.
///
/// It publishes this repository's own maintained source with `--from`, which is
/// the one invocation in this target that reaches exit 0, so the case measures
/// the whole run rather than a clear followed by a refusal for another reason.
#[test]
fn the_flag_over_a_killed_runs_residue_clears_it_and_publishes() {
    let root = Root::scratch("clear-killed-residue");
    let out = root.path().join("artifact");
    let mut name = out.file_name().expect("it has a name").to_os_string();
    name.push("~staging");
    let staging = out.with_file_name(name);
    std::fs::create_dir_all(&staging).expect("the staging directory is made");
    std::fs::write(
        staging.join(".headwater-publish-staging"),
        "an earlier run claimed this directory\n",
    )
    .expect("the marker is written");
    std::fs::write(
        staging.join(".headwater-publish-direct"),
        format!("an earlier run\nThe output path is: {}\n", out.display()),
    )
    .expect("the note is written");
    std::fs::create_dir_all(&out).expect("the output directory is made");
    std::fs::write(out.join("taxonomy.yml"), "half of an artifact\n")
        .expect("the residue is written");

    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .arg("taxonomy")
        .arg("publish")
        .arg("--clear-killed")
        .arg("--from")
        .arg(repository().join("taxonomy-source/headwater-standard"))
        .arg("--out")
        .arg(&out)
        .arg("--root")
        .arg(repository())
        .output()
        .expect("the binary runs");
    let message = String::from_utf8_lossy(&output.stderr).into_owned();
    assert_eq!(
        output.status.code(),
        Some(0),
        "the clear and the publish did not land in one run: {message}"
    );
    assert!(
        !staging.exists(),
        "the killed run's staging directory outlived the clear: {message}"
    );
    assert!(
        headwater_resolve::release::at(&out).is_ok(),
        "the publish after the clear left no record: {message}"
    );
    assert!(
        message.contains("~staging"),
        "the run does not say what it removed: {message}"
    );
}

/// One step of the maintenance loop the shipped manifest instructs.
#[derive(Debug, PartialEq, Eq)]
enum Step {
    /// A `headwater …` command line, `<scratch-dir>` still unsubstituted.
    Run(Vec<String>),
    /// The hand edit that no verb performs: write the digest `publish` printed
    /// into `.headwater/taxonomy.yml` as `taxonomy.digest`. Spec 7 keeps this
    /// step out of the engine deliberately, so an instruction block that omits
    /// it omits the one step a reader cannot infer from a verb.
    Pin,
}

/// The steps `taxonomy-source/headwater-standard/package.yml` instructs, taken
/// out of its header comment in the order it states them.
///
/// The indented block is the whole grammar: a line under `#` and four spaces is
/// a step, a step that opens `headwater ` is a command, and any other step is
/// the hand-written pin. Nothing else in that file is indented, and a step this
/// function cannot classify fails the case rather than being skipped — a parser
/// that quietly dropped a step would report a loop shorter than the one that
/// ships.
fn maintenance_loop(manifest: &str) -> Vec<Step> {
    manifest
        .lines()
        .filter_map(|line| line.strip_prefix("#    "))
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(|line| match line.strip_prefix("headwater ") {
            Some(rest) => Step::Run(rest.split_whitespace().map(str::to_string).collect()),
            None => {
                assert!(
                    line.contains("taxonomy.digest"),
                    "the instruction block carries a step this case cannot run: {line}"
                );
                Step::Pin
            }
        })
        .collect()
}

/// The binary, run from a directory, with the arguments exactly as a person
/// reading the instruction block would type them.
///
/// No `--root`, because the block states none. The working directory is what
/// makes `--from taxonomy-source/headwater-standard` mean what the block says
/// it means, and a case that passed `--root` would be testing its own
/// substitution rather than the sentence.
fn run_at(cwd: &Path, arguments: &[String]) -> (Option<i32>, String, String) {
    let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
        .args(arguments)
        .current_dir(cwd)
        .output()
        .expect("the binary runs");
    (
        output.status.code(),
        String::from_utf8_lossy(&output.stdout).into_owned(),
        String::from_utf8_lossy(&output.stderr).into_owned(),
    )
}

/// The digest a `publish` run printed, off its own standard output.
fn printed_digest(stdout: &str) -> String {
    stdout
        .lines()
        .find_map(|line| line.trim().strip_prefix("digest "))
        .unwrap_or_else(|| panic!("the publish printed no digest: {stdout}"))
        .trim()
        .to_string()
}

/// The version the shipped manifest declares, read rather than written down.
///
/// The case below copies this repository's real `taxonomy-source/` into its
/// scratch consumer, so a version literal here would be a second copy of a
/// number that moves whenever the package is republished. It was one, and a
/// republish to 4.2.1 reddened this case over a pin that named 4.2.0 against a
/// source that declared 4.2.1.
fn declared_version(manifest: &str) -> String {
    manifest
        .lines()
        .find_map(|line| line.strip_prefix("version:"))
        .unwrap_or_else(|| panic!("the shipped manifest declares no version: {manifest}"))
        .trim()
        .to_string()
}

/// Rewrite `taxonomy.digest` in a consumer declaration. This is the hand edit,
/// performed by the case because no verb performs it.
fn pin_digest(consumer: &Path, digest: &str) {
    let at = consumer.join(".headwater/taxonomy.yml");
    let declaration = std::fs::read_to_string(&at).expect("the consumer declaration reads");
    let rewritten = declaration
        .lines()
        .map(|line| match line.trim_start().starts_with("digest:") {
            true => format!("  digest: {digest}"),
            false => line.to_string(),
        })
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(&at, format!("{rewritten}\n")).expect("the pin is written");
}

/// **The instruction block that ships inside the published artifact, executed.**
///
/// `the_shipped_starter_recipe_publishes_vendors_and_resolves` and
/// `a_pin_that_no_longer_names_the_installed_bytes_is_refused_by_conformance_and_not_by_resolve`
/// both run the publish/pin/vendor/resolve order, and both hardcode it. So both
/// stay green while the document that instructs a maintainer states a different
/// order. This case takes the order out of the document.
///
/// [#516](https://github.com/headwater-ai/headwater/issues/516) is why it
/// exists. On the order `publish → pin → vendor → resolve` the digest is typed
/// once. That is only true if the shipped instructions state that order, and
/// until this case ran nothing had ever executed them. Since #1063,
/// `vendor --expect` records a caller-supplied digest where no pin is declared,
/// and it never replaces a declared one, so this order is unchanged by it.
///
/// **The provocation is a source that actually changed**, because that is the
/// only state in which the two orders differ. On an unchanged source the
/// artifact carries the digest already pinned, and `vendor` exits 0 wherever
/// the pin step sits. A maintainer opens this block only after editing the
/// source, which is exactly the state that makes the block wrong.
///
/// Green only if every step of the block exits 0, in the block's own order.
/// Against a block that puts the pin after `vendor`, or leaves it to a sentence
/// underneath, the `vendor` step exits 1 against the stale pin.
///
/// `taxonomy-source/headwater-standard/package.yml` ships inside the published
/// artifact, so an adopter of `headwater/standard` reads this same block.
#[test]
fn the_shipped_maintenance_loop_runs_as_written_over_a_source_that_changed() {
    let root = Root::scratch("shipped-maintenance-loop");
    let consumer = root.path().join("consumer");

    // A consumer laid out the way this repository is, because the block names
    // `taxonomy-source/headwater-standard` by that relative path and the
    // manifest reaches its bundle library with `../../docs/taxonomies`.
    copy(
        &repository().join("taxonomy-source/headwater-standard"),
        &consumer.join("taxonomy-source/headwater-standard"),
    );
    copy(
        &repository().join("docs/taxonomies"),
        &consumer.join("docs/taxonomies"),
    );
    std::fs::create_dir_all(consumer.join(".headwater")).expect("the block directory is made");
    std::fs::copy(
        repository().join(".headwater/overlay.yml"),
        consumer.join(".headwater/overlay.yml"),
    )
    .expect("the overlay copies");

    let manifest = std::fs::read_to_string(
        repository().join("taxonomy-source/headwater-standard/package.yml"),
    )
    .expect("the shipped manifest reads");
    let steps = maintenance_loop(&manifest);

    // ---- The state a maintainer is in before they edit anything. ---------
    //
    // Published, pinned, vendored and resolved once by hand, off the source as
    // it stands. Every assertion below is about the second pass, so this pass
    // has to be sound or the case would prove nothing.
    let before = root.path().join("release-before");
    let (code, stdout, stderr) = run_at(
        &consumer,
        &[
            "taxonomy".to_string(),
            "publish".to_string(),
            "--from".to_string(),
            "taxonomy-source/headwater-standard".to_string(),
            "--out".to_string(),
            before.to_str().expect("the path is UTF-8").to_string(),
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");
    write(
        &consumer.join(".headwater/taxonomy.yml"),
        &format!(
            "taxonomy:\n  package: headwater/standard\n  version: {}\n  digest: {}\n  bundles: [design-spec, evidence-and-obligation, decision-record]\n  overlay: .headwater/overlay.yml\ncorpus:\n  root: docs\n",
            declared_version(&manifest),
            printed_digest(&stdout)
        ),
    );
    for arguments in [
        vec![
            "taxonomy".to_string(),
            "vendor".to_string(),
            before.to_str().expect("the path is UTF-8").to_string(),
        ],
        vec!["taxonomy".to_string(), "resolve".to_string()],
    ] {
        let (code, _stdout, stderr) = run_at(&consumer, &arguments);
        assert_eq!(code, Some(0), "the settled state is not sound: {stderr}");
    }

    // ---- The edit that sends a maintainer to the instruction block. ------
    //
    // A comment appended to the authored taxonomy source. It moves the bytes of
    // a member file and nothing else, so the published digest moves and the
    // package still resolves.
    let source = consumer.join("taxonomy-source/headwater-standard/taxonomy.yml");
    let authored = std::fs::read_to_string(&source).expect("the authored source reads");
    std::fs::write(
        &source,
        format!("{authored}\n# an edit to the authored source, which moves the digest\n"),
    )
    .expect("the edit writes");

    // ---- The block, run as written. --------------------------------------
    let scratch = root.path().join("release-after");
    let mut printed = String::new();
    for step in &steps {
        match step {
            Step::Pin => pin_digest(&consumer, &printed_digest(&printed)),
            Step::Run(arguments) => {
                let arguments: Vec<String> = arguments
                    .iter()
                    .map(|argument| match argument.as_str() {
                        "<scratch-dir>" => scratch.to_str().expect("the path is UTF-8").to_string(),
                        other => other.to_string(),
                    })
                    .collect();
                let (code, stdout, stderr) = run_at(&consumer, &arguments);
                assert_eq!(
                    code,
                    Some(0),
                    "the shipped instruction block does not run as written. `headwater {}` \
                     refused after the source changed:\n{stderr}",
                    arguments.join(" ")
                );
                printed = stdout;
            }
        }
    }

    // Read after the run and not before it, so that a block missing the pin
    // step fails at the step that refuses rather than at a guard: the account a
    // maintainer needs is `vendor`'s own message about the digest it was given.
    assert!(
        steps.contains(&Step::Pin),
        "the instruction block ran green without stating a pin step, so this case no longer \
         holds the order it exists for: {steps:?}"
    );

    // The loop ended somewhere real: the vendored bytes are the ones the second
    // publish wrote, and the pin names them. `pin.current` is the reading that
    // says so, and `--level L0` is what turns a gap in it into an exit status.
    let (code, stdout, stderr) = run_at(
        &consumer,
        &[
            "conformance".to_string(),
            "--level".to_string(),
            "L0".to_string(),
        ],
    );
    assert_eq!(
        code,
        Some(0),
        "the loop ran to the end and left a pin that does not name the installed bytes: \
         {stdout}\n{stderr}"
    );
}

/// The divergence report an adopter reads, out of the built binary.
///
/// **The library half of this is held one crate down and that is not enough.**
/// `headwater-resolve/tests/publish.rs` asserts
/// `Vendored::divergence` over a package built in process. Every one of those
/// assertions stays green with the `if let Some(divergence)` block in
/// `main.rs` deleted, because the value would still be computed and simply
/// never printed. The contract clause of `docs/interfaces/headwater-taxonomy.md`
/// and the paragraph in spec 7 both promise what a person *sees*, so this runs
/// the binary and reads standard output. It is the same separation the module
/// comment above states for `nothing was published`: a correctness root can be
/// completely right and the visible result still be missing.
///
/// **Both counts are read off the two release records rather than typed here.**
/// A literal `3 files` and `4 files` would pass against a report that printed
/// one artifact's count twice, which is the defect most worth catching in a
/// line that exists to tell two artifacts apart.
///
/// The silence of the first install is asserted too. Without it the case passes
/// against a report that fires on every vendor.
#[test]
fn the_vendor_report_names_both_artifacts_of_one_version() {
    let root = Root::scratch("one-version-two-artifacts");
    let publisher = root.path().join("publisher");
    write(
        &publisher.join(".headwater/packages/acme-fixture/package.yml"),
        "package: acme/fixture\nversion: 4.2.0\ncontents:\n  taxonomy: taxonomy.yml\n  doctrine: doctrine/\n",
    );
    write(
        &publisher.join(".headwater/packages/acme-fixture/taxonomy.yml"),
        "taxonomy: acme/fixture\nversion: 4.2.0\npurposes:\n  rationale: {intent: explain why a choice was made and what it forecloses}\n",
    );
    write(
        &publisher.join(".headwater/packages/acme-fixture/doctrine/method.md"),
        "# Method\n\nWhy this taxonomy shelves what it shelves.\n",
    );

    let first_out = root.path().join("artifact-1");
    let (code, _stdout, stderr) = consumer_run(
        &publisher,
        &[
            "taxonomy",
            "publish",
            "--package",
            "acme/fixture",
            "--out",
            first_out.to_str().expect("the path is UTF-8"),
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");
    let first = record_at(&first_out);

    let adopter = root.path().join("adopter");
    std::fs::create_dir_all(&adopter).expect("the adopter root is made");
    let (code, stdout, stderr) = consumer_run(
        &adopter,
        &[
            "taxonomy",
            "vendor",
            first_out.to_str().expect("the path is UTF-8"),
            "--expect",
            &first.digest,
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");
    assert!(
        !stdout.contains("two sets of bytes"),
        "a first install has no record to diverge from, and the report fired anyway:\n{stdout}"
    );

    // One more member of the maintained source. Neither version key moves: a
    // package that states two versions of itself is refused at publish.
    write(
        &publisher.join(".headwater/packages/acme-fixture/doctrine/second.md"),
        "# Second\n\nOne more file, and the version stays where it is.\n",
    );
    let second_out = root.path().join("artifact-2");
    let (code, _stdout, stderr) = consumer_run(
        &publisher,
        &[
            "taxonomy",
            "publish",
            "--package",
            "acme/fixture",
            "--out",
            second_out.to_str().expect("the path is UTF-8"),
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");
    let second = record_at(&second_out);
    assert_eq!(
        first.version, second.version,
        "this is an upgrade, not the pair under test"
    );
    assert_ne!(
        first.digest, second.digest,
        "the two artifacts are one set of bytes"
    );
    assert_ne!(
        first.members.len(),
        second.members.len(),
        "the two counts are equal, so a report that printed one of them twice would pass"
    );

    let (code, stdout, stderr) = consumer_run(
        &adopter,
        &[
            "taxonomy",
            "vendor",
            second_out.to_str().expect("the path is UTF-8"),
            "--expect",
            &second.digest,
        ],
    );

    assert_eq!(
        code,
        Some(0),
        "this reports and it does not refuse: {stderr}"
    );
    assert!(
        stdout.contains("two sets of bytes"),
        "the adopter was told nothing about the second artifact:\n{stdout}"
    );
    assert!(
        stdout.contains(&format!("{}  {} files", first.digest, first.members.len())),
        "the installed artifact is not named with its own member count:\n{stdout}"
    );
    assert!(
        stdout.contains(&format!(
            "{}  {} files",
            second.digest,
            second.members.len()
        )),
        "the arriving artifact is not named with its own member count:\n{stdout}"
    );
    assert_eq!(
        package::find_version(&adopter, "acme/fixture"),
        Some(second.version.clone()),
        "the report replaced the install rather than accompanying it"
    );
}

/// The release record a publish wrote, read back off `--out`.
fn record_at(out: &Path) -> headwater_resolve::release::Release {
    headwater_resolve::release::read(
        &std::fs::read_to_string(out.join("release.yml")).expect("the release reads"),
    )
    .expect("the published record reads")
}

/// Every file under `dir`, by its path relative to `dir`, with its bytes.
fn tree(dir: &Path) -> std::collections::BTreeMap<PathBuf, Vec<u8>> {
    let mut files = std::collections::BTreeMap::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(at) = stack.pop() {
        for entry in std::fs::read_dir(&at).expect("the directory reads") {
            let path = entry.expect("the entry reads").path();
            if path.is_dir() {
                stack.push(path);
            } else {
                let bytes = std::fs::read(&path).expect("the file reads");
                files.insert(
                    path.strip_prefix(dir).expect("under dir").to_path_buf(),
                    bytes,
                );
            }
        }
    }
    files
}

/// Pack a published artifact directory into the zip `release-taxonomy.yml`
/// uploads: every member at the root of the archive, deflated.
fn zipped(artifact: &Path) -> Vec<u8> {
    use std::io::Write;
    let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
    let options = zip::write::SimpleFileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated);
    for (path, bytes) in tree(artifact) {
        let name = path.to_str().expect("the path is UTF-8").replace('\\', "/");
        writer.start_file(name, options).expect("the member starts");
        writer.write_all(&bytes).expect("the member writes");
    }
    writer.finish().expect("the archive closes").into_inner()
}

/// Serve `body` at `/x.zip` on 127.0.0.1, with `/moved` answering 302 to it,
/// for as long as the test process lives. Returns the base URL.
fn serve_artifact(body: Vec<u8>) -> String {
    use std::io::{Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a loopback port binds");
    let base = format!("http://{}", listener.local_addr().expect("the port reads"));
    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(mut stream) = stream else { continue };
            let mut request = [0_u8; 4096];
            let read = stream.read(&mut request).unwrap_or(0);
            let line = String::from_utf8_lossy(&request[..read]).to_string();
            let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
            let (head, payload): (String, &[u8]) = match path.as_str() {
                "/moved" => (
                    "HTTP/1.1 302 Found\r\nLocation: /x.zip\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                        .to_string(),
                    &[],
                ),
                "/x.zip" => (
                    format!(
                        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                        body.len()
                    ),
                    &body,
                ),
                _ => (
                    "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                        .to_string(),
                    &[],
                ),
            };
            let _ = stream.write_all(head.as_bytes());
            let _ = stream.write_all(payload);
        }
    });
    base
}

/// Publish `acme/fixture` 4.2.0 under `root` and return the artifact
/// directory with its record.
#[cfg(feature = "fetch")]
fn published_fixture(root: &Root) -> (PathBuf, headwater_resolve::release::Release) {
    let publisher = root.path().join("publisher");
    write(
        &publisher.join(".headwater/packages/acme-fixture/package.yml"),
        "package: acme/fixture\nversion: 4.2.0\ncontents:\n  taxonomy: taxonomy.yml\n  doctrine: doctrine/\n",
    );
    write(
        &publisher.join(".headwater/packages/acme-fixture/taxonomy.yml"),
        "taxonomy: acme/fixture\nversion: 4.2.0\npurposes:\n  rationale: {intent: explain why a choice was made and what it forecloses}\n",
    );
    write(
        &publisher.join(".headwater/packages/acme-fixture/doctrine/method.md"),
        "# Method\n\nWhy this taxonomy shelves what it shelves.\n",
    );
    let artifact = root.path().join("artifact");
    let (code, _stdout, stderr) = consumer_run(
        &publisher,
        &[
            "taxonomy",
            "publish",
            "--package",
            "acme/fixture",
            "--out",
            artifact.to_str().expect("the path is UTF-8"),
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");
    let record = record_at(&artifact);
    (artifact, record)
}

/// #959: `vendor <location>` installs what `vendor <dir>` installs.
///
/// HW-DR-0075 lets the verb take a location on the condition that the fetch
/// changes nothing but where the bytes come from. So the same published
/// artifact is vendored twice, once by path and once from a zip served on
/// 127.0.0.1 behind a 302, and the two installed trees are compared byte for
/// byte. A wrong digest refuses after the fetch and leaves the package area
/// as it found it. The suite reaches no host but this one.
#[cfg(feature = "fetch")]
#[test]
fn a_location_vendors_the_bytes_the_same_artifact_vendors_by_path() {
    let root = Root::scratch("vendor-location");
    let (artifact, record) = published_fixture(&root);
    let base = serve_artifact(zipped(&artifact));

    let refused = root.path().join("refused");
    std::fs::create_dir_all(&refused).expect("the adopter root is made");
    let wrong = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
    let location = format!("{base}/x.zip");
    let (code, _stdout, stderr) = consumer_run(
        &refused,
        &["taxonomy", "vendor", &location, "--expect", wrong],
    );
    assert_eq!(code, Some(1), "a wrong digest was accepted:\n{stderr}");
    assert!(
        stderr.contains(&location) && !stderr.contains("headwater-fetch-"),
        "the refusal names the temporary directory rather than the location:\n{stderr}"
    );
    assert!(
        !refused.join(package::PACKAGES).exists(),
        "a refused vendor wrote into the package area"
    );

    let by_path = root.path().join("by-path");
    std::fs::create_dir_all(&by_path).expect("the adopter root is made");
    let (code, _stdout, stderr) = consumer_run(
        &by_path,
        &[
            "taxonomy",
            "vendor",
            artifact.to_str().expect("the path is UTF-8"),
            "--expect",
            &record.digest,
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");

    let by_location = root.path().join("by-location");
    std::fs::create_dir_all(&by_location).expect("the adopter root is made");
    let moved = format!("{base}/moved");
    let (code, stdout, stderr) = consumer_run(
        &by_location,
        &["taxonomy", "vendor", &moved, "--expect", &record.digest],
    );
    assert_eq!(code, Some(0), "{stderr}");
    assert!(
        stdout.contains(&moved),
        "the report does not name the location it fetched:\n{stdout}"
    );

    let installed_by_path = tree(&by_path.join(package::PACKAGES));
    assert!(
        !installed_by_path.is_empty(),
        "the path form installed nothing"
    );
    assert_eq!(
        installed_by_path,
        tree(&by_location.join(package::PACKAGES)),
        "a location installed other bytes than the same artifact by path"
    );
}

/// #1113: a plain-http location reaches this machine even when the
/// environment names a proxy.
///
/// `headwater-fetch` admits plain http for a loopback host alone, because
/// nothing authenticates the bytes in transit. A proxy taken from
/// `HTTP_PROXY` or `ALL_PROXY` would decide for itself what `127.0.0.1`
/// means, so the gate would hold only in the code and not on the wire. A
/// second listener stands in for the proxy, counts every connection and
/// answers 502. The vendor must install the artifact and the proxy must see
/// no connection. The CLI runs as a subprocess so that no test thread sets a
/// variable another one reads.
#[cfg(feature = "fetch")]
#[test]
fn a_loopback_location_is_fetched_directly_under_a_proxy_environment() {
    use std::io::{Read, Write};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    let root = Root::scratch("vendor-proxy");
    let (artifact, record) = published_fixture(&root);
    let base = serve_artifact(zipped(&artifact));

    let proxy_listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a loopback port binds");
    let proxy = format!(
        "http://{}",
        proxy_listener.local_addr().expect("the port reads")
    );
    let connections = Arc::new(AtomicUsize::new(0));
    let seen = Arc::clone(&connections);
    std::thread::spawn(move || {
        for stream in proxy_listener.incoming() {
            let Ok(mut stream) = stream else { continue };
            seen.fetch_add(1, Ordering::SeqCst);
            let mut request = [0_u8; 4096];
            let _ = stream.read(&mut request);
            let _ = stream.write_all(
                b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            );
        }
    });

    let by_path = root.path().join("by-path");
    std::fs::create_dir_all(&by_path).expect("the adopter root is made");
    let (code, _stdout, stderr) = consumer_run(
        &by_path,
        &[
            "taxonomy",
            "vendor",
            artifact.to_str().expect("the path is UTF-8"),
            "--expect",
            &record.digest,
        ],
    );
    assert_eq!(code, Some(0), "{stderr}");

    // A scheme is case-insensitive, so `HTTP://` is the same plain-http
    // location and must skip the proxy in the same way.
    let upper = base.replacen("http://", "HTTP://", 1);
    for (case, location) in [
        ("lower", format!("{base}/x.zip")),
        ("upper", format!("{upper}/x.zip")),
    ] {
        let adopter = root.path().join(format!("adopter-{case}"));
        std::fs::create_dir_all(&adopter).expect("the adopter root is made");
        let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
            .args(["taxonomy", "vendor", &location, "--expect", &record.digest])
            .arg("--root")
            .arg(&adopter)
            .env("HTTP_PROXY", &proxy)
            .env("http_proxy", &proxy)
            .env("ALL_PROXY", &proxy)
            .env("all_proxy", &proxy)
            .env_remove("NO_PROXY")
            .env_remove("no_proxy")
            .output()
            .expect("the binary runs");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert_eq!(
            connections.load(Ordering::SeqCst),
            0,
            "the plain-http loopback request {location} went through the proxy:\n{stderr}"
        );
        assert_eq!(output.status.code(), Some(0), "{location}: {stderr}");
        assert_eq!(
            tree(&by_path.join(package::PACKAGES)),
            tree(&adopter.join(package::PACKAGES)),
            "{location} under a proxy environment installed other bytes than the artifact by path"
        );
    }
}