headwater-cli 0.2.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
// SPDX-License-Identifier: Apache-2.0
//! The migration payload, from the manifest key that declares it to the report
//! that accounts it against a measured corpus.
//!
//! # The defect this target exists for
//!
//! A format with no caller is a schema that nobody has been forced to satisfy.
//! Before this target `contents.migrations` was a key that `taxonomy publish`
//! read and dropped: seven hand-written wrong payloads all published with exit
//! 0, digest and all, and a consumer would have fetched every one of them. So
//! the cases below are a caller. `fixtures/migration/1-to-2.yml` is a committed
//! payload that a run reads, and a change to the format that nothing else
//! notices fails here.
//!
//! # Why the accounting is the case that matters
//!
//! A step declares which of spec 2's six dimensions it remedies by the subject
//! it names, and a claim of that shape is worth nothing until something
//! measures it. So the first case publishes a candidate that moves three
//! lifecycle values, runs `taxonomy diff` over a corpus that carries all three,
//! and asserts that the documents the payload names are exactly the documents
//! that moved. The second case removes one step and asserts that the
//! document it covered is now named as covered by nothing, which is what stops
//! the first case from passing against an accounting that says "all of them"
//! whatever it is handed.
//!
//! # The root each case runs over
//!
//! This repository's own package, overlay and consumer declaration, over the
//! three documents of `fixtures/migration/docs`. Copied rather than committed a
//! second time, for the reason `diff.rs` gives: a taxonomy under `fixtures/` is
//! a schema that no gate holds current, and it would go stale in silence.

use std::path::{Path, PathBuf};
use std::process::Command;

mod common;
use common::pin;

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

fn fixtures() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/migration")
}

/// The candidate taxonomy every case publishes as 2.0.0.
///
/// One value splits in two, one is renamed, and one is removed. The three are
/// the three applications a step can have, and the committed payload carries one
/// step of each.
const CANDIDATE: [(&[&str], &[&str]); 3] = [
    (
        &[
            "    - {value: draft,      role: initial}",
            "    - {value: current,    role: live}",
            "    - {value: superseded, role: terminal-retained}",
            "    - {value: deprecated, role: terminal-retained}",
            "    - {value: discharged, role: terminal-retained}",
        ],
        &[
            "    - {value: outline,    role: initial}",
            "    - {value: settled,    role: live}",
            "    - {value: provisional}",
            "    - {value: superseded, role: terminal-retained}",
            "    - {value: discharged, role: terminal-retained}",
        ],
    ),
    (
        &[
            "      draft: the document is being written or argued over, and nothing may rely on it",
            "      current: the document states what holds now, and a reader may rely on it",
            "      superseded: a later document replaced this one, and the succession edge names it",
            "      deprecated: the document is no longer to be relied on, and nothing replaced it",
            "      discharged: the document recorded something the corpus owed, the corpus paid it, and the record is kept as the receipt",
        ],
        &[
            "      outline: the document is being written or argued over, and nothing may rely on it",
            "      settled: the document states what holds now and nobody is arguing with it",
            "      provisional: the document states what holds now and the argument is not closed",
            "      superseded: a later document replaced this one, and the succession edge names it",
            "      discharged: the document recorded something the corpus owed, the corpus paid it, and the record is kept as the receipt",
        ],
    ),
    (
        &[
            "      initial: draft",
            "      transitions: {draft: [current, deprecated], current: [superseded, deprecated, discharged]}",
        ],
        &[
            "      initial: outline",
            "      transitions: {outline: [provisional, settled], provisional: [settled, superseded], settled: [superseded, discharged]}",
        ],
    ),
];

/// The candidate that renames a kind and moves no facet value.
///
/// The bundle of this package addresses `kinds.decision.facets`, and that
/// address survives the rename: an overlay entry over a kind the base no longer
/// declares adds the kind back rather than failing to address anything. So
/// `addressability` stays preserved, the candidate resolves, and
/// `classification` is the one dimension that reports a document. That was
/// measured rather than assumed, and the opposite was written down first.
///
/// The second edit names the kind the shelf carries and nothing else on that
/// line, for the reason [`address`] gives: an edit that quotes a whole shelf
/// declaration breaks on a member added to it that the case is not about.
const KIND: [(&[&str], &[&str]); 2] = [
    (&["  decision:"], &["  ruling:"]),
    (&["kind: decision,"], &["kind: ruling,"]),
];

/// The candidate that renames a kind one of the package's *bundles* declares.
///
/// `decision_register` is declared by `docs/taxonomies/design-spec/bundle.yml`
/// and by no other source of this package, so neither end of the rename is
/// visible in the base taxonomy: the base declares no `decision_register` to
/// move and no `ruling_register` to move it to. The rename is performed here in
/// the bundle, so the artifact the publish writes really does carry the new name
/// and really does not carry the old one.
///
/// Three edits and not one. The declaration is what a `kind` step names, and
/// `shelves.spec_series.kinds` and `relations.cites_evidence.from` are the two
/// other places in the bundle that name the kind rather than the facet value of
/// the same spelling.
///
/// **It was two edits until #582.** `relations.cites_evidence.from` was left
/// reading the old name, so the fixture's own package declared no
/// `decision_register` and still read one, and a consumer who selected this
/// bundle would have been refused for it. Nothing measured that: the publish
/// asked whether the shipped set merges and whether it commutes, and never
/// whether every name it reads is declared. The rule that now asks is what
/// found this, over a fixture whose doc comment already claimed the rename was
/// complete.
const BUNDLE_KIND: [(&str, &str); 3] = [
    ("  kinds.decision_register:", "  kinds.ruling_register:"),
    (
        "    kinds: [design_spec, decision_register, obligation_register]",
        "    kinds: [design_spec, ruling_register, obligation_register]",
    ),
    (
        "    from: [design_spec, decision_register, obligation_register]",
        "    from: [design_spec, ruling_register, obligation_register]",
    ),
];

/// A payload whose one `kind` step moves the bundle-declared `decision_register`
/// to whatever target the case names.
fn register_payload(target: &str) -> String {
    format!(
        "# SPDX-License-Identifier: Apache-2.0\n\nmigration:\n  format: 1\n  from: \">=1 <2\"\n  \
         to: \">=2 <3\"\n\nsteps:\n  - subject: kind\n    from: decision_register\n    to: \
         [{target}]\n    because: >-\n      The register of settled decisions and the decisions \
         themselves were one\n      kind, and a reader of the shelf could not tell which one a \
         document was.\n"
    )
}

/// The candidate whose only break is a facet that became required.
///
/// The base gains an `audience` facet that nothing requires, and the
/// decision-record bundle adds it to `kinds.decision.facets.require`. That is
/// the class [#427](https://github.com/headwater-ai/headwater/issues/427)
/// names: the facet exists and is optional in the base, a bundle kind starts
/// requiring it, and every document of that kind stops validating. The three
/// documents of this fixture are decisions, so all three move.
///
/// No step of the migration vocabulary reaches this. `Subject` names a facet
/// value, a kind and an overlay address, and a facet that became required has
/// no old value for a `facet_value` step to move. Spec 7 (*The migration
/// payload*) states that absence and names what an adopter does instead, which
/// is what [`an_apply_leaves_an_adoption_block_that_infer_can_add_to`]
/// measures.
const FACET: [(&[&str], &[&str]); 1] = [(
    &[
        "  title:",
        "    role: name",
        "    type: string",
        "    required: false",
        "    volatility: stable",
    ],
    &[
        "  title:",
        "    role: name",
        "    type: string",
        "    required: false",
        "    volatility: stable",
        "  audience:",
        "    type: string",
        "    required: false",
        "    volatility: stable",
    ],
)];

/// The one edit that makes `audience` required of every decision.
const REQUIRES_AUDIENCE: [(&str, &str); 1] = [(
    "  kinds.decision.facets:\n    require: [title]",
    "  kinds.decision.facets:\n    require: [title, audience]",
)];

/// A payload that covers the transition and migrates nothing.
///
/// The one step this vocabulary can express over a facet nobody carried is a
/// re-statement: `to: []` reads as "nothing replaces the old value". Every
/// document of the corpus lies outside it, which `taxonomy diff` reports. The
/// payload is here so that `taxonomy migrate --apply` runs at all — an
/// artifact with no payload for the transition is refused, and the case below
/// is about the lock that a run which reaches the end leaves behind.
fn inert_payload() -> String {
    "# SPDX-License-Identifier: Apache-2.0\n\nmigration:\n  format: 1\n  from: \">=1 <2\"\n  to: \
     \">=2 <3\"\n\nsteps:\n  - subject: facet_value\n    facet: audience\n    from: audience\n    \
     to: []\n    task: >-\n      Say who each decision is written for.\n    because: >-\n      A \
     reader could not tell which decisions were written for them.\n"
        .to_string()
}

/// The candidate that renames a kind the adopter's overlay addresses.
///
/// The three `CANDIDATE` edits, and two more that rename the `specification`
/// kind and the shelf that carries it. Every value the corpus reads still
/// moves, so a run over this candidate writes a document and an overlay entry
/// in one set.
///
/// The new name is `norm` and not `standard`, which is what it was until the
/// publish began holding the payload against the package with every bundle it
/// ships. `docs/taxonomies/standards-spec/bundle.yml` declares
/// `add.kinds.standard`, and an `add` over a key the base declares is refused at
/// merge, so a base that renamed `specification` to `standard` would be a
/// package no consumer of that bundle could resolve. Spec 7 makes every subset
/// resolvable a property of the release, so the refusal is right and the
/// candidate was quietly wrong while nothing read a bundle here.
fn address() -> Vec<(&'static [&'static str], &'static [&'static str])> {
    let mut edits: Vec<(&[&str], &[&str])> = CANDIDATE.to_vec();
    edits.push((&["  specification:"], &["  norm:"]));
    // The kind the shelf names, and nothing else on that line. An edit that
    // quoted the whole `shelves.specifications` declaration is an edit that an
    // unrelated member added to it breaks, with a failure that says nothing
    // about why — #538 declaring a display name on every shelf broke exactly
    // that, on eight cases at once. `kind: specification` appears once in the
    // base and the edit above has already renamed the kind's own key.
    edits.push((&["kind: specification"], &["kind: norm"]));
    edits
}

/// The overlay entry every case in this file's last section is about.
///
/// This repository's own overlay addresses exactly one kind that the base
/// declares. It is `kinds.decision.language`, which
/// [Q27](../../../../docs/spec/09-decisions.md#q27--whether-a-decision-record-is-governed-prose)
/// added, and `specification` is the base kind it does not reach. This section
/// needs an entry over a base kind that the candidate renames, and the overlay's
/// one entry is over the wrong member: [`Root::without`] explains that renaming
/// `decision` takes three document rules off three documents and makes two
/// dimensions report the same set. The copied overlay therefore gains this one,
/// and it is an ordinary entry — a base kind with no identifier scheme, given
/// the scheme the same overlay declares two blocks above.
const ENTRY: &str = "\n  kinds.specification.identifier: {scheme: spec_id}\n";

/// A repository root that removes itself.
///
/// `label` names the case and not the target. Cargo runs the cases of one
/// target as threads of one process, so a directory keyed on the process
/// identifier alone is one that a second case removes while the first is
/// reading it.
struct Root {
    at: PathBuf,
}

impl Root {
    fn new(label: &str) -> Root {
        let at = std::env::temp_dir().join(format!(
            "headwater-cli-migration-{}-{label}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&at);
        std::fs::create_dir_all(&at).expect("the root is made");

        let repository = repository();
        // `.headwater/packages/headwater-standard/` is a vendored artifact since #366
        // (a real `release.yml`), and `taxonomy publish` now refuses to
        // publish a directory in that state — every case here calls it by
        // name, with no `--from`. The maintained source is
        // `taxonomy-source/headwater-standard/`, copied here to the path the
        // by-name lookup expects.
        copy(
            &repository.join("taxonomy-source/headwater-standard"),
            &at.join(".headwater/packages/headwater-standard"),
        );
        repoint_bundles(&at.join(".headwater/packages/headwater-standard"));
        copy(
            &repository.join("docs/taxonomies"),
            &at.join("docs/taxonomies"),
        );
        without_doctrine(&at.join("docs/taxonomies"));
        // The scratch package ships no template, and the reason is what every
        // case below does to it. `taxonomy publish` holds each template a
        // package ships against the taxonomy that package resolves to
        // ([#378](https://github.com/headwater-ai/headwater/issues/378)). These
        // cases rename a lifecycle value or a kind in the base and leave the
        // templates alone, which is a disagreement the reader is right to
        // report: a publisher who renames `draft` to `outline` moves the
        // thirteen templates with it. That is not what any case here measures,
        // so the copy drops them and the reader has nothing to say. What the
        // library's own templates are held to is
        // `resolve/tests/templates.rs::the_library_this_repository_ships_passes_its_own_reader`.
        without_templates(&at.join("docs/taxonomies"));
        copy(&fixtures().join("docs"), &at.join("docs"));
        for name in ["taxonomy.yml", "overlay.yml"] {
            let to = at.join(".headwater").join(name);
            std::fs::create_dir_all(to.parent().expect("it has a parent"))
                .expect("the declaration directory is there");
            std::fs::copy(repository.join(".headwater").join(name), to)
                .expect("the declaration copies");
        }

        pin(&at, "1.0.0");

        let root = Root { at };
        let resolved = root.run(&["taxonomy", "resolve"]);
        assert_eq!(resolved.code, Some(0), "the fixture resolves: {resolved:?}");
        root
    }

    fn run(&self, arguments: &[&str]) -> Ran {
        let output = Command::new(env!("CARGO_BIN_EXE_headwater"))
            .args(arguments)
            .arg("--root")
            .arg(&self.at)
            .output()
            .expect("the binary runs");
        Ran {
            code: output.status.code(),
            out: String::from_utf8_lossy(&output.stdout).into_owned(),
            err: String::from_utf8_lossy(&output.stderr).into_owned(),
        }
    }

    fn publish(&self, name: &str) -> Ran {
        let out = self.at.join("released").join(name);
        self.run(&["taxonomy", "publish", "--out", out.to_str().expect("utf-8")])
    }

    fn released(&self, name: &str) -> PathBuf {
        self.at.join("released").join(name)
    }

    /// Rewrite the package source into the candidate 2.0.0, with `payload` in
    /// `migrations/` and `contents.migrations` declaring it.
    ///
    /// The lock is not re-resolved afterwards, which is the state a real
    /// consumer is in: the lock names the version this repository took, and the
    /// artifact names the version somebody is proposing.
    fn candidate(&self, payload: Option<&str>) {
        self.candidate_of(&CANDIDATE, payload);
    }

    fn candidate_of(&self, edits: &[(&[&str], &[&str])], payload: Option<&str>) {
        let taxonomy = self
            .at
            .join(".headwater/packages/headwater-standard/taxonomy.yml");
        let mut text = std::fs::read_to_string(&taxonomy).expect("the taxonomy reads");
        for (from, to) in edits {
            let (from, to) = (from.join("\n"), to.join("\n"));
            assert!(text.contains(&from), "the base still carries `{from}`");
            text = text.replacen(&from, &to, 1);
        }
        assert!(text.contains("version: 1.0.0"), "the base is at 1.0.0");
        std::fs::write(
            &taxonomy,
            text.replacen("version: 1.0.0", "version: 2.0.0", 1),
        )
        .expect("the taxonomy writes");

        let manifest = self
            .at
            .join(".headwater/packages/headwater-standard/package.yml");
        let mut text = std::fs::read_to_string(&manifest).expect("the manifest reads");
        text = text.replacen("version: 1.0.0", "version: 2.0.0", 1);
        if let Some(payload) = payload {
            let bundles = bundles_line();
            assert!(
                text.contains(&bundles),
                "the scratch manifest states `{bundles}`, which `repoint_bundles` wrote"
            );
            text = text.replacen(&bundles, &format!("{bundles}\n  migrations: migrations"), 1);
            let directory = self
                .at
                .join(".headwater/packages/headwater-standard/migrations");
            std::fs::create_dir_all(&directory).expect("the payload directory is there");
            std::fs::write(directory.join("1-to-2.yml"), payload).expect("the payload writes");
        }
        std::fs::write(&manifest, text).expect("the manifest writes");
    }

    /// Rewrite one bundle of the package in place.
    ///
    /// [`Root::candidate_of`] rewrites the base taxonomy, and the cases about
    /// bundle-declared content need the other file. The authored package
    /// declares `contents.bundles: ../../docs/taxonomies` and
    /// [`repoint_bundles`] climbs it one further for the root #792 moved it
    /// to, so the bundles of this scratch root are the copied
    /// `docs/taxonomies` tree either way.
    fn in_bundle(&self, bundle: &str, edits: &[(&str, &str)]) {
        let at = self
            .at
            .join("docs/taxonomies")
            .join(bundle)
            .join("bundle.yml");
        let mut text = std::fs::read_to_string(&at).expect("the bundle reads");
        for (from, to) in edits {
            assert!(text.contains(from), "the bundle still carries `{from}`");
            text = text.replacen(from, to, 1);
        }
        std::fs::write(&at, text).expect("the bundle writes");
    }

    fn diff(&self, name: &str) -> Ran {
        let at = self.released(name);
        self.run(&[
            "taxonomy",
            "diff",
            at.to_str().expect("utf-8"),
            "--now",
            "2026-08-01",
        ])
    }

    fn migrate(&self, name: &str, flags: &[&str]) -> Ran {
        let at = self.released(name);
        let mut arguments = vec![
            "taxonomy",
            "migrate",
            at.to_str().expect("utf-8"),
            "--now",
            "2026-08-01",
        ];
        arguments.extend_from_slice(flags);
        self.run(&arguments)
    }

    fn read(&self, path: &str) -> String {
        std::fs::read_to_string(self.at.join(path)).expect("the document reads")
    }

    /// Write one document that takes the bundle-declared `decision_register`,
    /// and return the path it was written to.
    ///
    /// The three committed fixture documents are `decision`, which the base
    /// declares, so no case built on them alone reaches a document whose kind
    /// only a bundle declares. `shelves.spec_series` is heterogeneous and
    /// discriminated by `doc_type`, so this document holds its kind in a
    /// front-matter key — which is the byte a mechanical `kind` step rewrites.
    fn register(&self) -> &'static str {
        let path = "docs/spec/09-the-register.md";
        let at = self.at.join(path);
        std::fs::create_dir_all(at.parent().expect("it has a parent"))
            .expect("the shelf directory is there");
        std::fs::write(&at, REGISTER).expect("the document writes");
        path
    }

    /// Move the consumer declaration onto `version` and re-resolve.
    ///
    /// `taxonomy migrate` writes documents, the overlay and the lock's
    /// migration state, and it moves no pin. So an adopter takes the new
    /// version themselves and resolves, and every verb after that reads a lock
    /// built from the taxonomy they now take.
    fn takes(&self, version: &str) {
        let at = self.at.join(".headwater/taxonomy.yml");
        let text = std::fs::read_to_string(&at).expect("the consumer declaration reads");
        assert!(
            text.contains("\n  version: 1.0.0\n"),
            "the declaration pins 1.0.0 to start with:\n{text}"
        );
        std::fs::write(
            &at,
            text.replacen(
                "\n  version: 1.0.0\n",
                &format!("\n  version: {version}\n"),
                1,
            ),
        )
        .expect("the consumer declaration writes");
        let resolved = self.run(&["taxonomy", "resolve"]);
        assert_eq!(
            resolved.code,
            Some(0),
            "the corpus resolves against the version it now takes: {resolved:?}"
        );
    }

    /// Rewrite the lock header's `version:` and nothing else.
    ///
    /// Legal, and that is the point of it. The header sits outside the digest
    /// over the `resolved` block, so a lock edited this way reads clean through
    /// `headwater_lock::read` and reaches the verb with a version pair nobody
    /// held. A real consumer arrives at the same state by re-running a
    /// migration that already succeeded and was resolved.
    ///
    /// The anchor takes `sources:` with it because the `resolved` block below
    /// carries a `version:` of its own at the same indent.
    fn heads(&self, version: &str) {
        let at = self.at.join(".headwater/taxonomy.lock");
        let text = std::fs::read_to_string(&at).expect("the lock reads");
        let was = "\n  version: 1.0.0\n  sources:\n";
        assert!(text.contains(was), "the lock header names 1.0.0:\n{text}");
        std::fs::write(
            &at,
            text.replacen(was, &format!("\n  version: {version}\n  sources:\n"), 1),
        )
        .expect("the lock writes");
    }

    /// Add one `add` entry to the copied overlay, under the `add:` block it
    /// already declares.
    fn addresses(&self, entry: &str) {
        let at = self.at.join(".headwater/overlay.yml");
        let text = std::fs::read_to_string(&at).expect("the overlay reads");
        assert!(text.starts_with("# SPDX"), "the overlay is the copied one");
        let (before, after) = text
            .split_once("\nadd:\n")
            .expect("it declares an `add` block");
        std::fs::write(&at, format!("{before}\nadd:\n{entry}{after}")).expect("the overlay writes");
        let resolved = self.run(&["taxonomy", "resolve"]);
        assert_eq!(
            resolved.code,
            Some(0),
            "the overlay with the entry resolves against the base: {resolved:?}"
        );
    }

    /// Drop one line from the copied overlay, and re-resolve.
    ///
    /// The one case that needs this is the kind rename. This repository's
    /// overlay binds a language regime to `decision`, and the base is what
    /// declares that kind, so a rename of it takes three document rules off
    /// three documents. `instance_validity` then reports the same documents
    /// that `classification` does, and a case meant to reach one half reaches
    /// both. The assertion fails loudly if the line ever goes away.
    fn without(&self, line: &str) {
        let at = self.at.join(".headwater/overlay.yml");
        let text = std::fs::read_to_string(&at).expect("the overlay reads");
        assert!(text.contains(line), "the overlay still carries `{line}`");
        std::fs::write(&at, text.replacen(line, "", 1)).expect("the overlay writes");
        let resolved = self.run(&["taxonomy", "resolve"]);
        assert_eq!(
            resolved.code,
            Some(0),
            "the overlay without the line resolves: {resolved:?}"
        );
    }

    /// Make one document of the corpus unwritable.
    ///
    /// A read-only file rather than a missing one, because a missing file is
    /// also a corpus a census never walked, and the case worth testing is the
    /// document a run named and then could not write.
    fn read_only(&self, path: &str) {
        let at = self.at.join(path);
        let mut permissions = std::fs::metadata(&at)
            .expect("the document is there")
            .permissions();
        permissions.set_readonly(true);
        std::fs::set_permissions(&at, permissions).expect("the document locks");
    }
}

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

#[derive(Debug)]
struct Ran {
    code: Option<i32>,
    out: String,
    err: String,
}

impl Ran {
    fn dimension(&self, name: &str) -> String {
        self.out
            .lines()
            .find_map(|line| line.trim_start().strip_prefix(name))
            .map(|rest| rest.trim().to_string())
            .unwrap_or_else(|| panic!("the report names `{name}`: {self:?}"))
    }
}

/// Remove the `templates/` directory of every bundle under a copied library
/// tree. See the comment at the one call site for why.
fn without_templates(at: &Path) {
    for entry in std::fs::read_dir(at).expect("the copied library reads") {
        let entry = entry.expect("the entry reads");
        let templates = entry.path().join("templates");
        if templates.is_dir() {
            std::fs::remove_dir_all(&templates).expect("the templates directory is removed");
        }
    }
}

/// Drop the library's doctrine prose from a scratch copy of `docs/taxonomies`.
///
/// Since [#350](https://github.com/headwater-ai/headwater/issues/350) this
/// repository's overlay types each `doctrine.md` and the library index as
/// `library_doctrine`, so a scratch root that copies the library and the
/// overlay would add eight documents to every count its cases read. The cases
/// here measure the fixture corpus and not the doctrine, and nothing a case
/// runs reads a doctrine page, so the copy leaves them out.
fn without_doctrine(library: &Path) {
    let index = library.join("README.md");
    if index.is_file() {
        std::fs::remove_file(&index).expect("the library index is removed");
    }
    for entry in std::fs::read_dir(library).expect("the copied library reads") {
        let doctrine = entry.expect("the entry reads").path().join("doctrine.md");
        if doctrine.is_file() {
            std::fs::remove_file(&doctrine).expect("the doctrine page is removed");
        }
    }
}

fn copy(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).expect("the directory is there");
    for entry in std::fs::read_dir(from).expect("the fixture directory reads") {
        let entry = entry.expect("the entry reads");
        let target = to.join(entry.file_name());
        match entry.file_type().expect("the file type reads").is_dir() {
            true => copy(&entry.path(), &target),
            false => {
                std::fs::copy(entry.path(), &target).expect("the fixture copies");
            }
        }
    }
}

/// The committed payload, which is the artifact that pays the cost of the
/// format.
fn payload() -> String {
    std::fs::read_to_string(fixtures().join("1-to-2.yml")).expect("the committed payload reads")
}

/// The committed payload that carries a step over an overlay address.
fn addresses() -> String {
    std::fs::read_to_string(fixtures().join("addresses-1-to-2.yml"))
        .expect("the committed payload reads")
}

/// The one case the whole issue is about.
///
/// A step's remedy is fixed by its subject, and that is a claim until something
/// measures it. Here the candidate moves three lifecycle values, the corpus
/// carries two of them, `instance_validity` reports three documents, and the
/// payload names those three and no others.
///
/// The `BROKEN, 3 failed / 3 skipped` assertion is deliberately the loose
/// half. A payload that named nothing would still meet it, and the
/// accounting line below is where this case fails.
///
/// Six instances and three documents. Three are `facet.value.not_permitted`
/// going from passed to failed, which is what "stopped validating" means. The
/// other three are `lifecycle.state.not_admitted` going from passed to
/// *skipped*, because the value the document carries is outside the
/// candidate's vocabulary and that rule defers to the one above it. A skip is
/// a rule that declined to decide rather than a document that broke, and the
/// two are counted apart in the printed word for that reason.
/// [#221](https://github.com/headwater-ai/headwater/issues/221) held the
/// conflation this pins the fix for.
#[test]
fn the_payload_names_every_document_whose_validity_moved() {
    let root = Root::new("names-every-document");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    let published = root.publish("2.0.0");
    assert_eq!(published.code, Some(0), "{published:?}");

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert_eq!(
        ran.dimension("instance_validity"),
        "BROKEN, 3 failed / 3 skipped"
    );
    // The same six breaks, read by the dimension that is a superset of the one
    // above, and the two lines are adjacent in the report. `consequence` said
    // `BROKEN, 6 of them` here until #396: one number over three failures and
    // three hand-offs, printed directly under a line that had already told
    // them apart.
    assert_eq!(
        ran.dimension("consequence"),
        "BROKEN, 3 failed / 3 skipped",
        "the superset dimension tells the same six apart: {ran:?}"
    );
    assert!(
        ran.out.contains(
            "3 of the 3 documents a dimension reports as moved lie under a step of this payload"
        ),
        "{ran:?}"
    );

    // Every application arm, and the subject count each one reaches in this
    // corpus. Three counts rather than one, because a reading that answered the
    // same number for every step would satisfy a single assertion.
    for line in [
        "a closed choice the author settles, among `settled`, `provisional`",
        "2 documents of this corpus carry the old value",
        "mechanical, and it becomes `outline`",
        "1 document of this corpus carries the old value",
        "a re-statement, and nothing replaces the old value",
        "no document of this corpus carries the old value, so this step is a no-op here",
        "3 steps, 1 mechanical and 2 judgment-bearing",
        "remedies instance_validity, consequence",
    ] {
        assert!(
            ran.out.contains(line),
            "the report states `{line}`: {ran:?}"
        );
    }
}

/// The direction that stops the case above from being a green light for any
/// accounting at all.
///
/// One step is removed from the payload. The measurement is identical — the
/// same candidate, the same three documents — and the one document that step
/// covered is now covered by nothing, by name.
#[test]
fn a_document_no_step_names_is_named() {
    let root = Root::new("names-what-is-uncovered");
    assert_eq!(root.publish("1.0.0").code, Some(0));

    let full = payload();
    let step = [
        "  - subject: facet_value",
        "    facet: status",
        "    from: draft",
        "    to: [outline]",
    ]
    .join("\n");
    assert!(full.contains(&step), "the committed payload carries it");
    let (before, rest) = full.split_once(&step).expect("the step is there");
    let after = rest
        .split_once("  # A re-statement")
        .expect("the step after it is there")
        .1;
    root.candidate(Some(&format!("{before}  # A re-statement{after}")));

    let published = root.publish("2.0.0");
    assert_eq!(published.code, Some(0), "{published:?}");
    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert_eq!(
        ran.dimension("instance_validity"),
        "BROKEN, 3 failed / 3 skipped",
        "the corpus and the candidate are the ones the case above measured: {ran:?}"
    );
    assert!(
        ran.out.contains(
            "1 of the 3 documents a dimension reports as moved lie under no step of this payload"
        ),
        "{ran:?}"
    );
    assert!(
        ran.out
            .contains("docs/decisions/0003-the-document-still-being-written.md"),
        "the uncovered document is named: {ran:?}"
    );
}

/// A closed choice with nothing that settles it stops the publish.
///
/// Spec 2 emits the judgment half "as a task list with the affected documents
/// attached". A step that leaves a choice and names no task is a question that
/// list would never carry.
#[test]
fn a_closed_choice_with_no_task_stops_the_publish() {
    let root = Root::new("choice-with-no-task");
    let full = payload();
    let task = [
        "    task: >-",
        "      Say whether the argument this document makes is closed. A document that a",
        "      reader may rely on and still argue with is `provisional`. One that nobody",
        "      is arguing with is `settled`.",
        "",
    ]
    .join("\n");
    assert!(full.contains(&task), "the committed payload carries it");
    root.candidate(Some(&full.replacen(&task, "", 1)));

    let ran = root.publish("2.0.0");
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(ran.err.contains("nothing was published"), "{ran:?}");
    assert!(
        ran.err
            .contains("a choice with no `task` beside it is a question nobody was asked"),
        "{ran:?}"
    );
    assert!(
        !root.released("2.0.0").exists(),
        "a refused publish writes no artifact"
    );
}

/// A step whose source is still declared in the taxonomy being published
/// renames something that did not move.
///
/// This is the half a publisher can check and a consumer cannot. It runs
/// against the candidate that keeps `draft`, so the step is the only route to
/// the refusal.
#[test]
fn a_source_the_taxonomy_still_declares_stops_the_publish() {
    let root = Root::new("source-still-stands");
    let full = payload();
    let step = ["from: draft", "    to: [outline]"].join("\n");
    assert!(full.contains(&step), "the committed payload carries it");
    root.candidate(Some(&full.replacen(
        &step,
        &["from: superseded", "    to: [outline]"].join("\n"),
        1,
    )));

    let ran = root.publish("2.0.0");
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(
        ran.err.contains(
            "still declares that facet_value, so the step renames something that did \
                      not move"
        ),
        "{ran:?}"
    );
}

/// The digest covers the payload, so the migration a consumer applies is the
/// one the publisher took the digest over.
#[test]
fn the_release_record_covers_the_payload() {
    let root = Root::new("record-covers-it");
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let at = root.released("2.0.0");
    assert!(at.join("migrations/1-to-2.yml").is_file(), "it is carried");
    let record = std::fs::read_to_string(at.join("release.yml")).expect("the record reads");
    assert!(
        record.contains("path: migrations/1-to-2.yml"),
        "the record names it: {record}"
    );

    // The check that makes the record more than a listing: an edited payload is
    // an artifact that is not what its own record says it is, and `diff` refuses
    // to measure against one.
    std::fs::write(at.join("migrations/1-to-2.yml"), "migration: {}\n").expect("the edit writes");
    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(
        ran.err
            .contains("the artifact is not what its own release record says it is"),
        "{ran:?}"
    );
}

/// A major upgrade that ships no payload says so, with the number of documents
/// it left the consumer.
#[test]
fn a_major_upgrade_with_no_payload_is_reported() {
    let root = Root::new("no-payload-at-all");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(None);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains(
            "the artifact ships no migration payload for 1.0.0 to 2.0.0, and 3 documents stopped \
             validating"
        ),
        "{ran:?}"
    );
}

/// The other subject a step can name, over the dimension it is a remedy for.
///
/// This candidate renames a kind and moves no facet value, so
/// `instance_validity` is preserved and `classification` is the only dimension
/// that reports a document. The accounting therefore comes from the
/// classification half alone, which no other case reaches.
///
/// The isolation is built rather than assumed. [Q27](../../../../docs/spec/09-decisions.md#q27--whether-a-decision-record-is-governed-prose)
/// binds the house language regime to `decision`, and that kind comes from the
/// base, so the copied overlay is what takes three rules off three documents
/// when the rename lands. [`Root::without`] removes the line first.
#[test]
fn a_kind_step_is_accounted_against_classification() {
    let root = Root::new("kind-step");
    root.without("  kinds.decision.language:            ste_house\n");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    let payload =
        std::fs::read_to_string(fixtures().join("kinds-1-to-2.yml")).expect("the payload reads");
    root.candidate_of(&KIND, Some(&payload));
    let published = root.publish("2.0.0");
    assert_eq!(published.code, Some(0), "{published:?}");

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert_eq!(ran.dimension("classification"), "BROKEN, 3 of them");
    assert_eq!(
        ran.dimension("instance_validity"),
        "preserved",
        "the other half contributes nothing here, or this case proves neither: {ran:?}"
    );
    for line in [
        "kind decision",
        "mechanical, and it becomes `ruling`",
        "remedies classification",
        "3 documents of this corpus carry the old value",
        "3 of the 3 documents a dimension reports as moved lie under a step of this payload",
    ] {
        assert!(
            ran.out.contains(line),
            "the report states `{line}`: {ran:?}"
        );
    }
}

// ---------------------------------------------------------------------------
// Which taxonomy each half of a payload step is held against.
// ---------------------------------------------------------------------------

/// A rename a bundle declares both ends of publishes.
///
/// The publisher moved `decision_register` in `design-spec/bundle.yml`, so after
/// the edit no source of this package declares the old name and one source
/// declares the new one. The payload that states the move is correct and
/// complete, and it is the payload a publisher of an optional shelf writes.
///
/// Held against the base taxonomy alone the target end is invisible — the base
/// declares three kinds and neither of these is one of them — so before
/// [#194](https://github.com/headwater-ai/headwater/issues/194) this refused
/// with `the taxonomy this publishes declares no kind` and a publisher of a
/// bundle had no correct payload to write. The target is now held against the
/// base with every bundle the package ships, which is the most any consumer
/// selects.
#[test]
fn a_rename_of_a_kind_a_bundle_declares_publishes() {
    let root = Root::new("bundle-kind-renamed");
    root.in_bundle("design-spec", &BUNDLE_KIND);
    let payload = format!(
        "{}\n  - subject: overlay_address\n    from: kinds.decision_register\n    to: \
         [kinds.ruling_register]\n    because: >-\n      An overlay entry under the old address \
         adds the old kind back rather than\n      failing to address anything.\n",
        register_payload("ruling_register")
    );
    root.candidate_of(&[], Some(&payload));

    let ran = root.publish("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
}

/// The widening of the target half is a widening and not a deletion.
///
/// The same candidate, and a target that no source of the package declares —
/// not the base and not any of the six bundles. The publish refuses, and the
/// message says which set was asked. Without this case
/// [`a_rename_of_a_kind_a_bundle_declares_publishes`] is satisfied by removing
/// the target check outright.
#[test]
fn a_target_no_bundle_declares_stops_the_publish() {
    let root = Root::new("bundle-kind-no-target");
    root.in_bundle("design-spec", &BUNDLE_KIND);
    root.candidate_of(&[], Some(&register_payload("no_source_declares_this")));

    let ran = root.publish("2.0.0");
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(ran.err.contains("nothing was published"), "{ran:?}");
    assert!(
        ran.err.contains("nor any bundle it ships"),
        "the message names the set the target was held against: {ran:?}"
    );
    assert!(
        !root.released("2.0.0").exists(),
        "a refused publish writes no artifact"
    );
}

/// The two halves are held against two taxonomies, and this is the case that
/// says the asymmetry is deliberate.
///
/// The bundle is left declaring `decision_register`, and the payload says it
/// became `specification`. Nothing moved for the consumers who selected that
/// bundle, so the step is wrong for them — and the publish accepts it, because
/// the source half is held against the base alone.
///
/// The base alone is what a consumer who selects no bundle resolves, and a
/// bundle is add-only ([spec 2](../../../../docs/spec/02-taxonomy-model.md#customization-by-composition)),
/// so a value the base declares is declared under every selection. That is what
/// "renames something that did not move" means, and it is the only reading of it
/// a publisher can certify. A value only a bundle declares moved for the
/// consumers who selected that bundle and for no other, and a payload step
/// states no condition. Widening this half would refuse the migration spec 7
/// most expects instead: content moving out of the base and into a bundle, told
/// to base-only consumers as a re-statement.
///
/// `headwater taxonomy diff` is the end that holds both the consumer's taxonomy
/// and the artifact's and can decide it, and
/// [#388](https://github.com/headwater-ai/headwater/issues/388) is that work.
/// A later change that makes the two halves symmetric fails here.
#[test]
fn a_source_only_a_bundle_declares_is_not_the_publishers_to_refuse() {
    let root = Root::new("bundle-source-stands");
    root.candidate_of(&[], Some(&register_payload("specification")));

    let ran = root.publish("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        std::fs::read_to_string(
            root.released("2.0.0")
                .join("bundles/design-spec/bundle.yml")
        )
        .expect("the published bundle reads")
        .contains("kinds.decision_register:"),
        "the artifact still declares the kind the step says moved"
    );
}

// ---------------------------------------------------------------------------
// `taxonomy migrate --apply`: the half that writes.
// ---------------------------------------------------------------------------

/// The committed payload with its closed choice made mechanical.
///
/// The committed one has exactly one mechanical step and it reaches exactly one
/// document, so no case built on it can tell a run that writes one file from a
/// run that writes a set. `current` reaches two documents, and turning its
/// choice into a single target turns it into a step the engine applies.
fn two_document_payload() -> String {
    let full = payload();
    let choice = [
        "    to: [settled, provisional]",
        "    task: >-",
        "      Say whether the argument this document makes is closed. A document that a",
        "      reader may rely on and still argue with is `provisional`. One that nobody",
        "      is arguing with is `settled`.",
    ]
    .join("\n");
    assert!(full.contains(&choice), "the committed payload carries it");
    full.replacen(&choice, "    to: [settled]", 1)
}

/// The case the whole issue is about, and the one it would be worst to get
/// wrong in the other direction.
///
/// A mechanical step writes the documents it covers. A judgment step writes
/// nothing, and that is asserted against the *bytes* of the two documents the
/// closed choice names rather than against a line of the report.
#[test]
fn the_mechanical_step_writes_and_a_judgment_step_writes_nothing() {
    let root = Root::new("apply-writes-the-mechanical-half");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let live = root.read("docs/decisions/0001-the-live-document.md");
    let second = root.read("docs/decisions/0002-the-second-live-document.md");
    let written = root.read("docs/decisions/0003-the-document-still-being-written.md");
    assert!(written.contains("status: draft"), "the fixture is at draft");

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(ran.out.contains("wrote 1 value in 2 files"), "{ran:?}");

    assert!(
        root.read("docs/decisions/0003-the-document-still-being-written.md")
            .contains("status: outline"),
        "the mechanical step wrote its one target"
    );
    assert_eq!(
        root.read("docs/decisions/0001-the-live-document.md"),
        live,
        "a closed choice is settled by an author, and `--apply` wrote this document"
    );
    assert_eq!(
        root.read("docs/decisions/0002-the-second-live-document.md"),
        second,
        "a closed choice is settled by an author, and `--apply` wrote this document"
    );
    assert!(
        ran.out.contains("2 tasks for an author"),
        "the judgment half is emitted as a task list: {ran:?}"
    );
    assert!(
        ran.out
            .contains("Say whether the argument this document makes is closed"),
        "the task carries its own text: {ran:?}"
    );
}

/// A run without `--apply` reports the same thing and writes nothing.
#[test]
fn a_run_without_apply_writes_no_document() {
    let root = Root::new("apply-is-required");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let before = root.read("docs/decisions/0003-the-document-still-being-written.md");
    let ran = root.migrate("2.0.0", &[]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out
            .contains("1 value in 2 files would be written. Nothing was: pass `--apply`"),
        "{ran:?}"
    );
    assert_eq!(
        root.read("docs/decisions/0003-the-document-still-being-written.md"),
        before
    );
}

/// The bar the issue set, tested where it can fail.
///
/// Two documents lie under one mechanical step and one of them cannot be
/// written. The run refuses and names it, and the other document is byte for
/// byte what it was. A writer that wrote as it went would have written that
/// document before it reached the one it could not, and the tree would then be
/// half migrated with nothing recording which half.
#[test]
fn a_document_that_cannot_be_written_leaves_every_other_document_as_it_was() {
    let root = Root::new("half-written");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&two_document_payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    // Three documents lie under the two mechanical steps, which is what makes
    // the assertion below about a set rather than about one file. The
    // unwritable one is the middle of the three in path order, so one document
    // sits before it and one after: a writer that wrote as it went would have
    // written the first and not the third.
    let planned = root.migrate("2.0.0", &[]);
    assert_eq!(planned.code, Some(0), "{planned:?}");
    assert!(
        planned.out.contains("3 values in 4 files would be written"),
        "{planned:?}"
    );

    let first = "docs/decisions/0001-the-live-document.md";
    let second = "docs/decisions/0002-the-second-live-document.md";
    let third = "docs/decisions/0003-the-document-still-being-written.md";
    let before = root.read(first);
    let after = root.read(third);
    root.read_only(second);

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(
        ran.err.contains(second),
        "the refusal names the file it could not write: {ran:?}"
    );
    assert!(
        ran.err
            .contains("a file of this migration cannot be written, so none was"),
        "{ran:?}"
    );
    assert_eq!(
        root.read(first),
        before,
        "the document before the unwritable one is exactly what it was"
    );
    assert_eq!(root.read(third), after, "and so is the document after it");
    assert!(
        root.read(second).contains("status: current"),
        "the unwritable document did not move either"
    );
}

/// A kind a homogeneous shelf carries has no byte to rewrite, and the run says
/// which shelf carries it rather than reporting nothing.
#[test]
fn a_kind_the_shelf_carries_is_named_and_no_document_is_written() {
    let root = Root::new("kind-by-placement");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    let payload =
        std::fs::read_to_string(fixtures().join("kinds-1-to-2.yml")).expect("the payload reads");
    root.candidate_of(&KIND, Some(&payload));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let before = root.read("docs/decisions/0001-the-live-document.md");
    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains(
            "takes its kind from `decisions`, which is homogeneous, so the document declares \
             the kind nowhere. The remedy is to move the file"
        ),
        "{ran:?}"
    );
    assert!(
        ran.out.contains("wrote 0 values in 1 file"),
        "no document moved, and the lock still records the migration: {ran:?}"
    );
    assert_eq!(
        root.read("docs/decisions/0001-the-live-document.md"),
        before
    );
}

/// HW-DR-0046: `--apply` writes `adoption.from` as `{version, digest}` and
/// `adoption.to` as the target version, read off the pin `.headwater/
/// taxonomy.yml` still carries at the moment this run reads it.
#[test]
fn apply_records_the_migration_state_in_the_lock() {
    let root = Root::new("records-the-migration-state");
    let digest = root
        .read(".headwater/taxonomy.yml")
        .lines()
        .find_map(|line| line.trim().strip_prefix("digest: "))
        .expect("the fixture's consumer declaration pins a digest")
        .to_string();
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out
            .contains("the lock records this migration on `--apply`"),
        "the run states it: {ran:?}"
    );

    let lock =
        std::fs::read_to_string(root.at.join(".headwater/taxonomy.lock")).expect("the lock reads");
    assert!(
        lock.contains(&format!(
            "adoption:\n  from:\n    version: 1.0.0\n    digest: \"{digest}\"\n  to: 2.0.0\n"
        )),
        "the block states what this run measured: {lock}"
    );
}

/// The whole sentence `migrate` prints when nothing pins the artifact.
///
/// Asserted entire, and not as a prefix of itself. The clause this constant
/// replaced said `taxonomy vendor` pins the digest, and the assertion below
/// stopped one word before it, so a false remedy stood in the engine's own
/// output with a passing case over it. A prefix cannot see the end of a
/// sentence, so the end of the sentence is what the case now carries.
const NO_PIN_REMEDY: &str = "  `.headwater/taxonomy.yml` pins no digest, so this run cannot write \
                             a verifiable `adoption.from` (HW-DR-0046). The pin is authored: take \
                             the digest the publisher states and write it as `taxonomy.digest` in \
                             `.headwater/taxonomy.yml` by hand, and a later run of this verb \
                             records the migration. Every other file below is still written on \
                             `--apply`";

/// A run with no digest pinned writes every other file and leaves the lock
/// exactly as it was, rather than writing a `from` this run cannot verify.
///
/// It also holds the remedy that run prints, by performing both halves of it.
/// `taxonomy vendor --expect <digest>` is run first, on the artifact this case
/// published, and the declaration is read back byte for byte: the check passes,
/// the artifact installs, and no pin is recorded. Then the digest is written
/// into the declaration by hand and the same `migrate --apply` is run again,
/// and the lock records the `adoption.from` the first run could not write. So
/// the sentence is measured at both ends rather than quoted from the source
/// beside it.
#[test]
fn apply_with_no_pinned_digest_writes_no_migration_state() {
    let root = Root::new("no-digest-no-lock-write");
    let consumer = root.read(".headwater/taxonomy.yml");
    assert!(
        consumer.contains("digest: "),
        "the fixture pins one to start with"
    );
    let unpinned = consumer
        .lines()
        .filter(|line| !line.trim_start().starts_with("digest: "))
        .collect::<Vec<_>>()
        .join("\n")
        + "\n";
    std::fs::write(root.at.join(".headwater/taxonomy.yml"), unpinned)
        .expect("the consumer declaration writes");

    let published = root.publish("1.0.0");
    assert_eq!(published.code, Some(0));
    let at = published
        .out
        .find("sha256:")
        .expect("the publish prints the digest it wrote");
    let digest = published.out[at..at + "sha256:".len() + 64].to_string();
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    // The first half of the remedy, measured. A passing `--expect` check
    // installs the artifact and records nothing, which is what makes the
    // sentence below a measurement rather than a restatement of the source.
    //
    // The maintained source moves aside first and comes back after. `taxonomy
    // vendor` refuses to write over a `.headwater/packages/<name>` that carries no release
    // record — "a package somebody maintains rather than one that was
    // vendored" — and this fixture root is exactly that case. The move is the
    // remedy that verb names, and it moves out of `.headwater/packages/` entirely
    // because the refusal is by declared package name and not by directory
    // name. The restore leaves the tree the later assertions read byte for
    // byte what it was.
    let maintained = root.at.join(".headwater/packages/headwater-standard");
    let aside = root.at.join("maintained-source");
    std::fs::rename(&maintained, &aside).expect("the maintained source moves aside");
    let vendored = root.run(&[
        "taxonomy",
        "vendor",
        root.released("1.0.0").to_str().expect("utf-8"),
        "--expect",
        &digest,
    ]);
    assert_eq!(vendored.code, Some(0), "the check passes: {vendored:?}");
    assert!(
        vendored.out.contains(&digest),
        "over the digest this case published: {vendored:?}"
    );
    assert!(
        !root.read(".headwater/taxonomy.yml").contains("digest: "),
        "and it wrote no pin: {}",
        root.read(".headwater/taxonomy.yml")
    );
    std::fs::remove_dir_all(&maintained).expect("the vendored artifact goes");
    std::fs::rename(&aside, &maintained).expect("the maintained source comes back");

    let before =
        std::fs::read_to_string(root.at.join(".headwater/taxonomy.lock")).expect("the lock reads");
    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains(NO_PIN_REMEDY),
        "the run states why, and the whole sentence stands: {ran:?}"
    );
    assert!(
        !ran.out.contains("`taxonomy vendor` pins"),
        "and it names no verb that would refuse this adopter: {ran:?}"
    );
    assert!(
        ran.out.contains("wrote 1 value in 1 file"),
        "every other file is still written: {ran:?}"
    );
    assert_eq!(
        std::fs::read_to_string(root.at.join(".headwater/taxonomy.lock")).expect("the lock reads"),
        before,
        "and the lock is byte for byte what it was"
    );

    // The second half of the remedy, performed. The digest goes into the
    // declaration by hand, where the sentence says it goes, and the same run
    // then writes the migration state it refused to write above.
    let repinned = std::fs::read_to_string(root.at.join(".headwater/taxonomy.yml"))
        .expect("the consumer declaration reads")
        .replace(
            "\n  version: ",
            &format!("\n  digest: {digest}\n  version: "),
        );
    assert!(repinned.contains(&digest), "the pin is written by hand");
    std::fs::write(root.at.join(".headwater/taxonomy.yml"), repinned)
        .expect("the consumer declaration writes");
    let after = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(after.code, Some(0), "{after:?}");
    assert!(
        !after.out.contains("pins no digest"),
        "the run has a pin now: {after:?}"
    );
    let lock =
        std::fs::read_to_string(root.at.join(".headwater/taxonomy.lock")).expect("the lock reads");
    assert!(
        lock.contains(&digest),
        "and a later run of this verb records the migration, which is what the remedy \
         promises: {lock}"
    );
}

/// The lock `--apply` leaves is one `headwater infer --write` can add to.
///
/// Spec 7 makes `taxonomy migrate` the first verb of an upgrade and `infer` the
/// verb that records what the upgrade broke as debt. Between them stands
/// [`merged`](../src/main.rs), which refuses an adoption block that declares no
/// `tasks` key, because a payload written over an authored block would discard
/// an owner, an expiry and every pair. The block `--apply` writes is generated
/// rather than authored, and it declared `from` and `to` and nothing else, so
/// the second verb refused the first verb's own output on every adopter's first
/// migration, whatever the change class.
///
/// The class here is the one that has no other route: a facet that became
/// required, which no step of the migration vocabulary reaches. `infer` derives
/// the pair set from the corpus, `check` then reports it as migration-pending,
/// and that path is the whole of what an adopter gets for this class.
#[test]
fn an_apply_leaves_an_adoption_block_that_infer_can_add_to() {
    let root = Root::new("apply-then-infer");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&FACET, Some(&inert_payload()));
    root.in_bundle("decision-record", &REQUIRES_AUDIENCE);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    let written = root.read(".headwater/taxonomy.lock");
    assert!(
        written.contains("adoption:") && written.contains("  to: 2.0.0\n"),
        "the run wrote the migration state: {written}"
    );
    assert!(
        written.contains("  tasks: []\n"),
        "and it wrote the empty standing list the next verb adds to: {written}"
    );

    // The corpus now takes 2.0.0. `taxonomy migrate` moves no pin, so the two
    // lines a real adopter runs after it are here: the version they take, and
    // the resolve that puts it in the lock.
    root.takes("2.0.0");

    // Every reader of the block, and not `infer` alone. `taxonomy resolve`
    // carried it through above, which is what `takes` asserts, and the check
    // layer reads it as the adoption inventory. An empty sequence is zero
    // tasks holding zero pairs, which is what the block says.
    let checked = root.run(&["check", "--now", "2026-08-01"]);
    assert!(
        checked.out.contains("0 pairs open"),
        "the check layer reads the block as an empty inventory: {checked:?}"
    );

    let inferred = root.run(&[
        "infer",
        "--owner",
        "tester",
        "--until",
        "2026-12-06",
        "--now",
        "2026-08-01",
        "--write",
    ]);
    assert_eq!(
        inferred.code,
        Some(0),
        "the verb spec 7 names next can add to the block --apply left: {inferred:?}"
    );
    let lock = root.read(".headwater/taxonomy.lock");
    assert!(
        lock.contains("owner: tester"),
        "the pairs this run derived are in the lock: {lock}"
    );
    assert!(
        lock.contains("rule: facet.required.missing"),
        "and the rule they are held under is the one the upgrade broke: {lock}"
    );
}

/// A lock already carrying a `tasks`-less block is repaired rather than left.
///
/// The state an adopter is in who ran `--apply` under an engine that wrote no
/// `tasks` key: the block is there, it holds `from`, `to` and whatever else a
/// person put beside them, and `infer --write` refuses it. The next `--apply`
/// adds the empty sequence, and every other entry of the block survives —
/// including a key this engine knows nothing about, which is what [`migrated`]
/// carries entries through for.
///
/// A block with a standing task list is a different case and is untouched by
/// this: `apply_carries_a_standing_task_list_through` is that one.
#[test]
fn an_apply_repairs_a_block_that_declares_no_tasks() {
    let root = Root::new("repairs-a-tasks-less-block");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let lock = root.at.join(".headwater/taxonomy.lock");
    let before = std::fs::read_to_string(&lock).expect("the lock reads");
    assert!(
        !before.contains("\nadoption:\n"),
        "the fixture declares none to start with"
    );
    std::fs::write(
        &lock,
        before.replacen(
            "\n# The resolved taxonomy",
            "\nadoption:\n  note: a key this engine does not read\n\n# The resolved taxonomy",
            1,
        ),
    )
    .expect("the lock writes");

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    let after = std::fs::read_to_string(&lock).expect("the lock reads");
    assert!(
        after.contains("  tasks: []\n"),
        "the run added the empty sequence the next verb adds to: {after}"
    );
    assert!(
        after.contains("  note: \"a key this engine does not read\"\n"),
        "and it carried the key it does not read through: {after}"
    );
}

/// A standing task list is carried through and never rewritten.
///
/// The other side of the case above, and the one the guard exists for. A block
/// that already declares `tasks` gets `from` and `to` replaced and its list
/// left exactly as it was loaded.
#[test]
fn apply_carries_a_standing_task_list_through() {
    let root = Root::new("carries-a-standing-list");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let lock = root.at.join(".headwater/taxonomy.lock");
    let before = std::fs::read_to_string(&lock).expect("the lock reads");
    let standing = "\nadoption:\n  tasks:\n    - id: AD-1\n      owner: a person\n      until: \
                    2027-01-01\n      pairs: []\n\n# The resolved taxonomy";
    std::fs::write(
        &lock,
        before.replacen("\n# The resolved taxonomy", standing, 1),
    )
    .expect("the lock writes");

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    let after = std::fs::read_to_string(&lock).expect("the lock reads");
    assert!(
        after.contains(
            "  tasks:\n    - id: AD-1\n      owner: \"a person\"\n      until: 2027-01-01\n"
        ),
        "the standing task is exactly what it was: {after}"
    );
    assert!(
        !after.contains("tasks: []"),
        "and nothing wrote an empty list over it: {after}"
    );
}

/// The closing sentence of a diff names a route the adopter can take.
///
/// "Spec 2 makes a major version ship one" is true of every break a step can
/// express, and it is an instruction to write a file the format cannot hold
/// where the break is a facet that became required. So the sentence forks on
/// what broke: a break every rule of which is `facet.required.missing` names
/// `infer --write`, and every other break keeps the sentence spec 2 states.
#[test]
fn a_break_no_step_reaches_names_infer_rather_than_a_payload() {
    let root = Root::new("no-step-reaches-it");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&FACET, None);
    root.in_bundle("decision-record", &REQUIRES_AUDIENCE);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains(
            "the artifact ships no migration payload for 1.0.0 to 2.0.0, and 3 \
                          documents stopped validating. No step can express this break"
        ),
        "the sentence names what cannot be written: {ran:?}"
    );
    assert!(
        ran.out.contains(
            "`headwater infer --owner <name> --write` records the breakage as adoption \
                      debt, and `headwater check` then reports it as migration-pending"
        ),
        "and it names the route that is reachable: {ran:?}"
    );
    assert!(
        !ran.out.contains("Spec 2 makes a major version ship one"),
        "and it does not also ask for the file it just said cannot be written: {ran:?}"
    );
}

/// And the sentence a break a step *can* express still gets.
///
/// The paired half of the case above. `CANDIDATE` moves three lifecycle values,
/// which is exactly what a `facet_value` step is for, so an artifact that
/// shipped no payload for it is a publisher who owes one.
#[test]
fn a_break_a_step_reaches_still_asks_for_a_payload() {
    let root = Root::new("a-step-reaches-it");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(None);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains("Spec 2 makes a major version ship one"),
        "a break the vocabulary reaches is a payload the publisher owes: {ran:?}"
    );
    assert!(
        !ran.out.contains("No step can express this break"),
        "and the other sentence is not printed beside it: {ran:?}"
    );
}

/// And the half of the fork that answers on an *empty* rule set.
///
/// The two cases above both move a rule, so both of them exercise the `all()`
/// half of the guard and neither reaches the emptiness half. A rename of a kind
/// is the break that answers the empty set: `classification` is keyed by a
/// document path and names no rule, so the rules a payload is accounted against
/// are deliberately empty for it. `all()` answers `true` on an empty set, so
/// without the emptiness half of the guard this run tells a publisher that no
/// step reaches a break `kind` is one of the three subjects for.
///
/// The candidate is [`KIND`] with no payload, and [`Root::without`] takes the
/// house language regime off the kind first, for the reason
/// [`a_kind_step_is_accounted_against_classification`] states: the isolation of
/// the two dimensions is built here rather than assumed.
#[test]
fn a_classification_only_break_still_asks_for_a_payload() {
    let root = Root::new("classification-only-break");
    root.without("  kinds.decision.language:            ste_house\n");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&KIND, None);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert_eq!(
        ran.dimension("classification"),
        "BROKEN, 3 of them",
        "the break is the rename: {ran:?}"
    );
    assert_eq!(
        ran.dimension("instance_validity"),
        "preserved",
        "and no rule moved, or the empty set this case is about is not empty: {ran:?}"
    );
    assert!(
        ran.out.contains(
            "the artifact ships no migration payload for 1.0.0 to 2.0.0, and 3 documents \
             stopped validating. Spec 2 makes a major version ship one"
        ),
        "a kind step reaches this break, so the publisher owes the file: {ran:?}"
    );
    assert!(
        !ran.out.contains("No step can express this break"),
        "and nothing tells the publisher the vocabulary cannot reach a rename of a kind: {ran:?}"
    );
}

/// An artifact with no payload for this transition is a refusal rather than a
/// run that migrated nothing and said it was done.
#[test]
fn an_artifact_with_no_payload_for_the_transition_is_refused() {
    let root = Root::new("no-payload");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(None);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(
        ran.err
            .contains("the artifact ships no migration payload for 1.0.0 to 2.0.0"),
        "{ran:?}"
    );
    assert!(
        !ran.err.contains("headwater --help"),
        "the artifact is this repository's package and it ships no payload for the transition. \
         No command line reads a payload that is not there:\n{}",
        ran.err
    );
}

// ---------------------------------------------------------------------------
// The overlay address: the subject that names no document, and the state that
// nothing reported before it.
// ---------------------------------------------------------------------------

/// The case this whole issue is about, and the one that was silent.
///
/// A candidate renames a kind. This repository's overlay writes into that kind
/// at an address the new base no longer declares — and the `add` puts the kind
/// back. Every phase downstream reads a `kinds.specification` that no taxonomy
/// declares: the candidate resolves, `classification` reports nothing, and
/// before this measurement `addressability` said `preserved`.
///
/// The resolution assertion is deliberately the loose half. A candidate that
/// failed to resolve would satisfy no reading of this case at all, and the
/// dimension below it is where this case fails.
#[test]
fn an_add_over_a_path_the_new_base_dropped_is_named_with_the_entry_that_makes_it() {
    let root = Root::new("resurrection-is-named");
    root.addresses(ENTRY);
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&address(), None);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(
        ran.code,
        Some(0),
        "the candidate resolves, which is what makes the state quiet: {ran:?}"
    );
    assert_eq!(
        ran.dimension("addressability"),
        "BROKEN, 1 of them",
        "{ran:?}"
    );
    for line in [
        "add.kinds.specification.identifier in .headwater/overlay.yml",
        "makes `kinds.specification` rather than reaching into it",
        "an address into `kinds.specification`, which the taxonomy under it declared",
    ] {
        assert!(
            ran.out.contains(line),
            "the report states `{line}`: {ran:?}"
        );
    }
    assert!(
        ran.out.contains("this change requires a major version"),
        "spec 2: any dimension broken forces a major: {ran:?}"
    );
}

/// The direction that keeps the case above from passing against any reading.
///
/// The same overlay entry, the same corpus, and a candidate that renames
/// nothing the entry addresses. The address still reaches the declaration it
/// was written against, and the dimension says so.
#[test]
fn an_overlay_address_the_new_base_still_declares_is_preserved() {
    let root = Root::new("address-still-reaches");
    root.addresses(ENTRY);
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(None);
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert_eq!(
        ran.dimension("addressability"),
        "preserved",
        "the candidate moves three facet values and no address: {ran:?}"
    );
    assert_eq!(
        ran.dimension("instance_validity"),
        "BROKEN, 3 failed / 3 skipped",
        "and the run did measure something, or this case proves nothing: {ran:?}"
    );
}

/// A step over an address, accounted the way a step over a value is.
///
/// The reach line is the assertion. It counts entries of the overlay and not
/// documents of the corpus, and the noun is what says the subject reached a
/// file that no census walks.
#[test]
fn a_step_over_an_address_reports_the_overlay_entries_it_reaches() {
    let root = Root::new("address-step-reports");
    root.addresses(ENTRY);
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&address(), Some(&addresses()));
    let published = root.publish("2.0.0");
    assert_eq!(published.code, Some(0), "{published:?}");

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    for line in [
        "overlay_address kinds.specification",
        "mechanical, and it becomes `kinds.norm`",
        "remedies addressability",
        "1 entry of this repository's overlay is addressed at or under it",
    ] {
        assert!(
            ran.out.contains(line),
            "the report states `{line}`: {ran:?}"
        );
    }
}

/// A publisher that ships a step over an address it did not move.
///
/// The half of the payload check the publisher can make. `kinds.decision` is
/// still declared in the taxonomy being published, so a step that re-addresses
/// overlays away from it renames something that did not move, and the digest is
/// never taken.
#[test]
fn a_step_over_an_address_the_new_taxonomy_still_declares_stops_the_publish() {
    let root = Root::new("address-source-stands");
    root.addresses(ENTRY);
    assert_eq!(root.publish("1.0.0").code, Some(0));
    let payload = addresses().replacen(
        "    from: kinds.specification\n    to: [kinds.norm]",
        "    from: kinds.decision\n    to: [kinds.norm]",
        1,
    );
    root.candidate_of(&address(), Some(&payload));

    let published = root.publish("2.0.0");
    assert_eq!(published.code, Some(1), "{published:?}");
    assert!(
        published
            .err
            .contains("the taxonomy this publishes still declares that overlay_address"),
        "{published:?}"
    );
}

/// A `from` that is not an address at all.
///
/// The step is refused when the payload is read, before anything decides
/// whether it is mechanical, so no writer ever meets an address it cannot
/// parse.
#[test]
fn a_step_over_something_that_is_not_an_address_is_refused_when_the_payload_is_read() {
    let root = Root::new("address-unparseable");
    root.addresses(ENTRY);
    assert_eq!(root.publish("1.0.0").code, Some(0));
    let payload =
        addresses().replacen("from: kinds.specification", "from: kinds..specification", 1);
    root.candidate_of(&address(), Some(&payload));

    let published = root.publish("2.0.0");
    assert_eq!(published.code, Some(1), "{published:?}");
    assert!(
        published
            .err
            .contains("is not an address into a taxonomy, and an `overlay_address` step moves one"),
        "{published:?}"
    );
}

/// `--apply` over both subjects, and the write set that holds them together.
///
/// One step writes a document of the corpus and one writes the overlay beside
/// it. The assertion is on the bytes of both files, because a run that wrote
/// the document and reported the overlay would print the same two lines.
#[test]
fn apply_rewrites_the_overlay_address_beside_the_document() {
    let root = Root::new("address-apply");
    root.addresses(ENTRY);
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&address(), Some(&addresses()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    assert!(
        root.read(".headwater/overlay.yml")
            .contains("kinds.specification.identifier: {scheme: spec_id}"),
        "the entry is the one the fixture added"
    );

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(ran.out.contains("wrote 2 values in 3 files"), "{ran:?}");
    assert!(
        ran.out.contains(
            ".headwater/overlay.yml  add.kinds.specification.identifier  becomes \
                      `kinds.norm.identifier`"
        ),
        "{ran:?}"
    );

    let overlay = root.read(".headwater/overlay.yml");
    assert!(
        overlay.contains("kinds.norm.identifier: {scheme: spec_id}"),
        "the address moved and the value beside it did not: {overlay}"
    );
    assert!(
        !overlay.contains("kinds.specification"),
        "no old address survives: {overlay}"
    );
    assert!(
        overlay.contains("kinds.decision_register.identifier:"),
        "an address the step does not reach is untouched: {overlay}"
    );
    assert!(
        root.read("docs/decisions/0003-the-document-still-being-written.md")
            .contains("status: outline"),
        "the document half of the same write set landed"
    );
}

/// The property #186 built, over a set that holds an overlay and a document.
///
/// The overlay is read-only. `headwater_scaffold::tree::Reserved` opens every
/// target before a byte is written, so the run refuses there — and the
/// assertion is on the *document*, which a writer that took the corpus first
/// would already have written.
#[test]
fn an_unwritable_overlay_leaves_the_document_beside_it_untouched() {
    let root = Root::new("address-apply-refuses");
    root.addresses(ENTRY);
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&address(), Some(&addresses()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let document = root.read("docs/decisions/0003-the-document-still-being-written.md");
    let overlay = root.read(".headwater/overlay.yml");
    root.read_only(".headwater/overlay.yml");

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(
        ran.err
            .contains("a file of this migration cannot be written, so none was"),
        "{ran:?}"
    );
    assert!(ran.err.contains(".headwater/overlay.yml"), "{ran:?}");
    assert_eq!(
        root.read("docs/decisions/0003-the-document-still-being-written.md"),
        document,
        "the document is in the same write set as the overlay, so neither moved"
    );
    assert_eq!(root.read(".headwater/overlay.yml"), overlay);
}

// ---------------------------------------------------------------------------
// Which taxonomy the *source* half of a step is held against, for a consumer.
// ---------------------------------------------------------------------------

/// The one document of these cases that takes a kind only a bundle declares.
///
/// `doc_type` is the discriminator of `shelves.spec_series`, so the kind sits
/// in a front-matter key and a mechanical `kind` step rewrites it. Every
/// sentence of the body is one line and carries no contraction, so the house
/// language regime the copied overlay binds to this kind reports nothing.
const REGISTER: &str = "---\nid: HW-REG-the-register\ntitle: The register of settled \
                        decisions\nstatus: current\nstatus_since: 2026-08-01\nlast_verified: \
                        2026-08-01\nsummary: The one document of this scratch corpus that \
                        records what the corpus settled.\ndoc_type: \
                        decision_register\nsequence: 9\nprovenance:\n  warrant: asserted\n  \
                        agency: model\n  evidence_basis: unevidenced\n---\n\n# 9 — The register \
                        of settled decisions\n\nThis document takes its kind from the `doc_type` \
                        key above.\n\nA bundle of the package declares that kind, and the base \
                        package declares no such kind.\n";

/// The line a report prints for a step whose source the artifact still declares
/// for this repository.
const STANDS: &str = "the taxonomy this artifact gives this repository still declares the old \
                      value, so this step does not complete here";

/// The line a report prints for a step that really did move and reached nothing.
const NO_OP: &str = "no document of this corpus carries the old value, so this step is a no-op \
                     here";

/// The state [#388](https://github.com/headwater-ai/headwater/issues/388) is
/// about: a step the publisher may ship and this consumer must not apply.
///
/// The bundle is left declaring `decision_register` and the payload says it
/// became `specification`, which
/// [`a_source_only_a_bundle_declares_is_not_the_publishers_to_refuse`] measures
/// as a publish this end may not refuse. This repository selects that bundle,
/// so the taxonomy the artifact gives it still declares the old value: the step
/// did not happen here. Before this case the report said only that no document
/// of the corpus carried the value, which is true of the corpus and silent
/// about the step.
///
/// The absent line is asserted beside two present ones, so the case cannot pass
/// on a report that never reached the step, on a payload nothing selected, or
/// on a run that failed.
#[test]
fn a_step_whose_source_this_selection_still_declares_is_reported_by_diff() {
    let root = Root::new("bundle-source-stands-diff");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&[], Some(&register_payload("specification")));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains("kind decision_register"),
        "the report reached the step: {ran:?}"
    );
    assert!(
        ran.out.contains("remedies classification"),
        "the report accounted the step: {ran:?}"
    );
    assert!(ran.out.contains(STANDS), "{ran:?}");
    assert!(
        !ran.out.contains(NO_OP),
        "the no-op sentence is what this state was being told as: {ran:?}"
    );
}

/// The same payload subject, the same selection, and a rename the artifact
/// really performed.
///
/// One edit apart from the case above: the bundle moves the kind too, so the
/// taxonomy this repository would take declares no `decision_register` and the
/// step did happen here. This is the direction that must keep its old sentence,
/// and without it the case above is satisfied by printing the new sentence over
/// every step.
///
/// The issue asked for "a root that selects no bundle" here. This fixture has
/// none: its overlay founds five kinds under the shelves of `design-spec`, so
/// dropping the bundle leaves twelve validation refusals and dropping every
/// bundle leaves an identifier scheme with no pattern. One bundle edit reaches
/// the same opposite direction and needs no second consumer declaration.
#[test]
fn a_step_whose_source_this_selection_no_longer_declares_keeps_its_sentence() {
    let root = Root::new("bundle-source-moved-diff");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.in_bundle("design-spec", &BUNDLE_KIND);
    root.candidate_of(&[], Some(&register_payload("ruling_register")));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.diff("2.0.0");
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains("kind decision_register"),
        "the report reached the step: {ran:?}"
    );
    assert!(ran.out.contains(NO_OP), "{ran:?}");
    assert!(
        !ran.out.contains(STANDS),
        "the source moved for this selection: {ran:?}"
    );
}

/// The write the condition stops, measured against the bytes of a document.
///
/// The corpus carries one document that takes the bundle-declared kind, so the
/// step is mechanical and reaches a front-matter key. `--apply` counted it
/// mechanical, rewrote the key, moved the lock's `adoption` block and exited 0,
/// which is a corpus typed `specification` under a taxonomy that declares
/// `decision_register` and no `specification` on that shelf. The refusal is the
/// whole run rather than the one step, because a payload half of which does not
/// apply here leaves the corpus in neither version.
#[test]
fn an_apply_refuses_a_step_whose_source_this_selection_still_declares() {
    let root = Root::new("bundle-source-stands-apply");
    let path = root.register();
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate_of(&[], Some(&register_payload("specification")));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let before = root.read(path);
    assert!(
        before.contains("doc_type: decision_register"),
        "the document takes the bundle-declared kind"
    );

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(
        ran.out.contains("kind decision_register"),
        "the run reached the step: {ran:?}"
    );
    assert!(ran.out.contains(STANDS), "{ran:?}");
    assert!(
        ran.err.contains("would rewrite"),
        "the refusal says what it stopped: {ran:?}"
    );
    assert_eq!(root.read(path), before, "no byte of the document moved");
    assert!(
        !root.read(".headwater/taxonomy.lock").contains("adoption:"),
        "a refused run records no migration: {ran:?}"
    );
}

/// The same document, the same subject, and the rename the artifact performed.
///
/// This is the anchor that the refusal above is a condition rather than a
/// blanket. The bundle moves the kind, so the step did happen for this
/// selection, and `--apply` writes the one key it names.
#[test]
fn an_apply_writes_a_bundle_declared_kind_the_artifact_really_moved() {
    let root = Root::new("bundle-source-moved-apply");
    let path = root.register();
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.in_bundle("design-spec", &BUNDLE_KIND);
    root.candidate_of(&[], Some(&register_payload("ruling_register")));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.migrate("2.0.0", &["--apply"]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        root.read(path).contains("doc_type: ruling_register"),
        "the step wrote the one key it names: {ran:?}"
    );
    assert!(
        !ran.out.contains(STANDS),
        "the source moved for this selection: {ran:?}"
    );
}

/// A migration that is not forward, and the ordinary one beside it.
///
/// The lock header sits outside the digest `headwater_lock::read` verifies, so
/// a header that already names the artifact's own version reads clean and used
/// to reach payload selection. What it met there was the no-payload arm, whose
/// sentence accuses the publisher of shipping a non-conformant artifact and
/// offers `taxonomy diff`, which reports every dimension preserved, and
/// `headwater infer --owner <name> --write`, which records adoption debt in the
/// consumer's own lock for a break that does not exist. Every population of
/// that sentence is consumer-side
/// ([#649](https://github.com/headwater-ai/headwater/issues/649)).
///
/// The two negative assertions are the case. A regression to the old sentence
/// fails on them and on nothing else, because the old sentence also exits 1.
#[test]
fn a_lock_already_on_the_artifacts_version_is_refused() {
    let root = Root::new("lock-already-on-the-version");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));
    root.heads("2.0.0");

    for flags in [&[][..], &["--apply"][..]] {
        let ran = root.migrate("2.0.0", flags);
        assert_eq!(ran.code, Some(1), "{ran:?}");
        assert!(
            ran.err.contains("the lock already takes 2.0.0"),
            "the refusal names the lock and the version it holds: {ran:?}"
        );
        assert!(
            ran.err.contains("no earlier version to migrate from"),
            "and says what that leaves this run nothing to do: {ran:?}"
        );
        assert!(
            !ran.err.contains("Spec 2 makes a major version ship one"),
            "the publisher shipped a sound artifact: {ran:?}"
        );
        assert!(
            !ran.err.contains("headwater infer"),
            "and no remedy records debt for a break that does not exist: {ran:?}"
        );
    }
}

/// The ordinary correct upgrade, unchanged.
///
/// This case exists to be broken by the wrong fix rather than by a regression.
/// The refusal above is about the version pair alone, and any currency check
/// reached for in its place — `Lock::moved`, a `resolve --check`, a re-hash of
/// `sources[]` — refuses this run too. `taxonomy resolve --check` exits 1 on
/// **every** correct `taxonomy migrate`, because `migrate` is by construction
/// run in a tree where the vendored candidate has already replaced the source
/// the lock was built from. So a currency gate turns this case red, which is
/// the whole reason it is written down.
#[test]
fn the_ordinary_upgrade_is_not_refused() {
    let root = Root::new("ordinary-upgrade-still-runs");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));

    let ran = root.migrate("2.0.0", &[]);
    assert_eq!(ran.code, Some(0), "{ran:?}");
    assert!(
        ran.out.contains("from 1.0.0 to 2.0.0"),
        "the report still names the pair it read off the lock: {ran:?}"
    );
    assert!(
        ran.out.contains("1-to-2.yml"),
        "and the payload it selected: {ran:?}"
    );
}

/// An artifact below the version the lock names.
///
/// One arm and one sentence away from the case above it, and it reaches the
/// guard by the other side of the same comparison. A payload runs forward, so
/// there is nothing here for `covers` to select and no report to print.
#[test]
fn an_artifact_below_the_locked_version_is_refused() {
    let root = Root::new("artifact-below-the-lock");
    assert_eq!(root.publish("1.0.0").code, Some(0));
    root.candidate(Some(&payload()));
    assert_eq!(root.publish("2.0.0").code, Some(0));
    root.heads("3.0.0");

    let ran = root.migrate("2.0.0", &[]);
    assert_eq!(ran.code, Some(1), "{ran:?}");
    assert!(
        ran.err
            .contains("the lock takes 3.0.0 and this artifact publishes 2.0.0"),
        "the refusal names both sides: {ran:?}"
    );
    assert!(
        ran.err.contains("runs forward only"),
        "and why that is not a migration: {ran:?}"
    );
    assert!(!ran.err.contains("headwater infer"), "{ran:?}");
}

/// Repoint `contents.bundles` in a scratch copy of the authored manifest.
///
/// The scalar is relative to the package directory, and
/// [`package::PACKAGES`] put that directory one level deeper in #792. The
/// prefix is computed from the constant rather than written out, so a root
/// that moves again moves this with it. `taxonomy publish` rewrites this same
/// scalar on every artifact it writes, so a fixture that does it here is not
/// inventing a mechanism.
fn repoint_bundles(package: &std::path::Path) {
    let manifest = package.join(headwater_resolve::package::MANIFEST);
    let text = std::fs::read_to_string(&manifest).expect("the scratch manifest reads");
    let from = "  bundles: ../../docs/taxonomies";
    assert!(text.contains(from), "the authored manifest states `{from}`");
    std::fs::write(&manifest, text.replace(from, &bundles_line()))
        .expect("the scratch manifest writes");
}

/// The `contents.bundles` line a scratch manifest carries once
/// [`repoint_bundles`] has run.
fn bundles_line() -> String {
    let up = "../".repeat(headwater_resolve::package::PACKAGES.split('/').count() + 1);
    format!("  bundles: {up}docs/taxonomies")
}