tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
//! The single owner of hierarchy behaviour (mission
//! `parent-issues-subissues-01M3BXX3`, WP01).
//!
//! Everything about an issue's parent lives here: child derivation, parent
//! set/change/clear, validation, the rollup figures, and unresolved-parent
//! detection. Surfaces call this rather than re-deriving, because a second
//! implementation is exactly the divergence the mission's intake escalates.
//!
//! ## What this module deliberately does not do
//!
//! - **It touches no files.** It takes an in-memory issue set and a
//!   `done_column` the caller has already resolved, so the whole surface is
//!   testable with no `Store` and no `tempfile` (T005 step 4). Storage owns the
//!   write; this module owns the rule.
//! - **It does not know about the issue model.** [`HierarchyNode`] is the
//!   minimum an issue must expose, and WP02 implements it for `Issue`. WP01 is
//!   forbidden from touching `src/model.rs`, so the service is defined against
//!   the shape WP02 will provide rather than against `Issue` directly.
//! - **It stores no child list.** Child membership is derived by inverting the
//!   child's parent pointer, never persisted (C-003).
//!
//! ## Decisions taken here, and why
//!
//! **The frontmatter key is `parent`.** It has to be unambiguous against the
//! existing Spec Kitty pointer fields `mission` and `task`, which are
//! governance metadata and not a hierarchy (research R2, C-007). `parent` is
//! distinct from all three, and it is reused verbatim by `FilterField::key()` in
//! WP06 (research R4).
//!
//! **The stored reference is an issue number, not a selector.** A selector can be
//! a title fragment, and a title is not stable: retitling a parent would silently
//! break every child pointing at it. Selectors are the *input* to
//! [`set_parent`] and friends; the number is what lands in the file.
//!
//! **The completion basis is direct children only.** Both figure fields in
//! `data-model.md` §3 — `direct_children` and `completed_children` — are
//! direct-child counts, and a subtree rollup is `O(V)` per parent, which turns a
//! board render into `O(V²)`. The basis is carried on the value anyway
//! ([`CompletionBasis`]) so a consumer can never guess which figure it is looking
//! at, and so changing the basis later is a visible change rather than a silent
//! one.
//!
//! **History events are declared here, not in `model.rs`.** The mission requires
//! the `## History` section to record parent set/changed/cleared, but
//! `HistoryEventKind` is `model.rs`'s and WP01 may not edit it. The three kinds
//! are therefore declared as [`ParentEventKind`] and WP02 maps them onto
//! `HistoryEventKind` when it adds the field. Declaring them here keeps the
//! service complete and the boundary honest.

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

use crate::error::{TixError, render_diagnostics};
use crate::id::{AliasIndex, IdentityNode, IssueRef};
use crate::planning::Progress;
use crate::relationships::RelationshipGraph;

/// The frontmatter key carrying an issue's parent reference.
///
/// Chosen once here and reused verbatim by the search layer in WP06.
pub const PARENT_KEY: &str = "parent";

/// The minimum an issue must expose for hierarchy derivation.
///
/// WP02 implements this for [`crate::model::Issue`]. Keeping it a trait is what
/// lets this module be written and tested without `src/model.rs`, which WP02
/// owns.
pub trait HierarchyNode {
    /// The issue's number, which is its stable identity.
    fn number(&self) -> u32;
    /// The issue's title, used only for the derived display label.
    fn title(&self) -> &str;
    /// The issue's raw status, compared against the caller's completion column.
    fn status(&self) -> &str;
    /// The canonical issue id, when the record has one.
    fn canonical_id(&self) -> Option<&str> {
        None
    }
    /// The store-relative filename used by the shared alias index.
    fn filename(&self) -> Option<&str> {
        None
    }
    /// The stored canonical parent reference. `None` means no parent.
    fn parent_ref(&self) -> Option<&IssueRef> {
        None
    }
    /// Legacy numeric parent alias used by in-memory test nodes.
    fn parent_number(&self) -> Option<u32>;
}

// ---------------------------------------------------------------------------
// T001 — ParentReference and HierarchyIndex
// ---------------------------------------------------------------------------

/// A resolved reference to another issue, with its derived display label.
///
/// `data-model.md` §1. The label is computed on read and **never stored**: a
/// stored title goes stale the moment the referenced issue is retitled.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParentReference {
    /// The referenced issue's canonical graph identity.
    pub id: IssueRef,
    /// The referenced issue's number.
    pub number: u32,
    /// `#<number> <title>`, or just `#<number>` when the title is blank.
    pub display: String,
}

impl ParentReference {
    /// Build a reference, deriving the label from the title.
    pub fn new<N: HierarchyNode>(issue: &N) -> Self {
        Self {
            id: hierarchy_ref(issue),
            number: issue.number(),
            display: display_label(issue.number(), issue.title()),
        }
    }
}

fn hierarchy_ref<N: HierarchyNode>(issue: &N) -> IssueRef {
    issue
        .canonical_id()
        .and_then(IssueRef::id)
        .map(|reference| reference.with_number(issue.number()))
        .unwrap_or_else(|| IssueRef::Number(issue.number()))
}

/// The shared display form for a referenced issue: `#12 Fix the thing`.
///
/// One function, because a second formatting site is how two surfaces end up
/// disagreeing about what an issue is called.
pub fn display_label(number: u32, title: &str) -> String {
    let title = title.trim();
    if title.is_empty() {
        format!("#{number}")
    } else {
        format!("#{number} {title}")
    }
}

/// A child, as `data-model.md` §2's ordered list element.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChildRef {
    /// The child's canonical graph identity.
    pub id: IssueRef,
    /// The child's number.
    pub number: u32,
    /// The child's derived display label.
    pub display: String,
}

/// The derived set of an issue's direct children (`data-model.md` §2).
///
/// Derived, never stored: this is the mechanical guard for C-003, and
/// `no_child_list_is_stored_in_the_index` pins it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChildMembership {
    /// The issue the children belong to.
    pub parent: u32,
    /// Direct children, ordered by issue number.
    pub children: Vec<ChildRef>,
    /// `children.len()`, carried because callers ask for it constantly.
    pub child_count: usize,
}

impl ChildMembership {
    fn empty(parent: u32) -> Self {
        Self {
            parent,
            children: Vec::new(),
            child_count: 0,
        }
    }
}

/// The derived parent/child view over one snapshot of issues.
///
/// Built once and read many times. Both maps are `BTreeMap`, so every iteration
/// is in issue-number order and repeated reads of the same snapshot are
/// byte-identical (NFR-003).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HierarchyIndex {
    /// child identity -> parent identity. Only issues that *have* a parent appear.
    parent_by_child: BTreeMap<IssueRef, IssueRef>,
    /// parent identity -> child identities, ascending.
    children_by_parent: BTreeMap<IssueRef, Vec<IssueRef>>,
    /// identity -> issue number alias.
    numbers: BTreeMap<IssueRef, u32>,
    /// number alias -> every identity carrying it.
    refs_by_number: BTreeMap<u32, Vec<IssueRef>>,
    /// identity -> display label, for the issues this index knows about.
    labels: BTreeMap<IssueRef, String>,
    /// identity -> status, for completion resolution.
    statuses: BTreeMap<IssueRef, String>,
    /// identity -> source filename, for exact lint attribution.
    filenames: BTreeMap<IssueRef, String>,
    /// The one project-wide alias index this snapshot was built from.
    aliases: AliasIndex,
    /// Alias failures retained in addition to unresolved-parent states.
    alias_diagnostics: Vec<HierarchyDiagnostic>,
}

struct AliasNode<'a, N>(&'a N);

impl<N: HierarchyNode> IdentityNode for AliasNode<'_, N> {
    fn canonical_id(&self) -> Option<&str> {
        self.0.canonical_id()
    }
    fn issue_number(&self) -> u32 {
        self.0.number()
    }
    fn issue_filename(&self) -> &str {
        self.0.filename().unwrap_or("")
    }
    fn issue_title(&self) -> &str {
        self.0.title()
    }
}

impl HierarchyIndex {
    /// Build the index from an in-memory issue set.
    ///
    /// A child whose recorded parent is not in the set is **kept** in
    /// `parent_by_child`: dropping it would turn a diagnosable dangling reference
    /// into a silently absent one, which is the failure `UnresolvedParentState`
    /// exists to prevent. [`Self::unresolved`] reports those.
    pub fn build<N: HierarchyNode>(issues: &[N]) -> Self {
        let mut index = Self::default();
        for issue in issues {
            let number = issue.number();
            let identity = hierarchy_ref(issue);
            index.numbers.insert(identity, number);
            index
                .refs_by_number
                .entry(number)
                .or_default()
                .push(identity);
            index
                .labels
                .insert(identity, display_label(number, issue.title()));
            index
                .filenames
                .insert(identity, issue.filename().unwrap_or("").to_string());
            index.statuses.insert(identity, issue.status().to_string());
        }
        let alias_nodes: Vec<AliasNode<'_, N>> = issues.iter().map(AliasNode).collect();
        index.aliases = AliasIndex::build(&alias_nodes);
        for refs in index.refs_by_number.values_mut() {
            refs.sort();
            refs.dedup();
        }
        for issue in issues {
            let child_identity = hierarchy_ref(issue);
            let parent = issue
                .parent_ref()
                .copied()
                .or_else(|| issue.parent_number().map(IssueRef::Number));
            if let Some(parent) = parent {
                let parent = match index.aliases.resolve(&parent) {
                    Ok(resolved) => resolved,
                    Err(error) => {
                        let kind = match error {
                            crate::id::AliasError::Ambiguous { .. } => {
                                HierarchyDiagnosticKind::AmbiguousTarget
                            }
                            crate::id::AliasError::DuplicateId { .. } => {
                                HierarchyDiagnosticKind::DuplicateIdentity
                            }
                            crate::id::AliasError::Missing(_) => {
                                HierarchyDiagnosticKind::UnresolvedParent
                            }
                        };
                        if kind != HierarchyDiagnosticKind::UnresolvedParent {
                            index.alias_diagnostics.push(
                                HierarchyDiagnostic::new(
                                    kind,
                                    issue.number(),
                                    format!(
                                        "{PARENT_KEY}: {} cannot be resolved: {}",
                                        parent.human(),
                                        alias_error_text(&error)
                                    ),
                                )
                                .with_source_file(issue.filename().unwrap_or("")),
                            );
                        }
                        parent
                    }
                };
                index.parent_by_child.insert(child_identity, parent);
                index
                    .children_by_parent
                    .entry(parent)
                    .or_default()
                    .push(child_identity);
            }
        }
        // Child order is the human-facing issue-number order. Canonical ids are
        // the map identity, but random id order is not a useful report order.
        for children in index.children_by_parent.values_mut() {
            children.sort_by_key(|child| index.numbers.get(child).copied().unwrap_or_default());
        }
        index
    }

    fn identity_for_number(&self, issue: u32) -> Option<IssueRef> {
        match self.refs_by_number.get(&issue)?.as_slice() {
            [one] => Some(*one),
            _ => None,
        }
    }

    fn number_for_identity(&self, identity: &IssueRef) -> Option<u32> {
        self.numbers.get(identity).copied()
    }

    /// Alias failures discovered while resolving stored parent references.
    pub fn alias_diagnostics(&self) -> &[HierarchyDiagnostic] {
        &self.alias_diagnostics
    }

    /// The canonical parent reference stored on `issue`.
    pub fn parent_ref_of(&self, issue: u32) -> Option<&IssueRef> {
        self.identity_for_number(issue)
            .and_then(|identity| self.parent_by_child.get(&identity))
            .or_else(|| self.parent_by_child.get(&IssueRef::Number(issue)))
    }

    /// The canonical recorded parent of one canonical issue reference.
    pub fn parent_ref_for(&self, issue: &IssueRef) -> Option<&IssueRef> {
        self.parent_by_child.get(issue)
    }

    /// The canonical identity of `issue` itself.
    pub fn identity_ref_of(&self, issue: u32) -> Option<IssueRef> {
        self.identity_for_number(issue)
    }

    /// The ordered direct children of `issue`.
    ///
    /// An issue with no children returns an empty membership, **not** an error:
    /// "has no children" is the ordinary state of most issues.
    pub fn children_of(&self, issue: u32) -> ChildMembership {
        let identity = self
            .identity_for_number(issue)
            .unwrap_or(IssueRef::Number(issue));
        let Some(children) = self.children_by_parent.get(&identity) else {
            return ChildMembership::empty(issue);
        };
        let children: Vec<ChildRef> = children
            .iter()
            .map(|child| ChildRef {
                id: *child,
                number: self.number_for_identity(child).unwrap_or_default(),
                display: self.label_ref(child),
            })
            .collect();
        ChildMembership {
            parent: issue,
            child_count: children.len(),
            children,
        }
    }

    /// The stored parent number of `issue`, if it has one.
    ///
    /// Returns the number without resolving it, so a dangling reference is still
    /// visible here. Use [`Self::unresolved`] to separate the two cases.
    pub fn parent_of(&self, issue: u32) -> Option<u32> {
        self.parent_ref_of(issue).and_then(|parent| {
            parent
                .as_number()
                .or_else(|| self.number_for_identity(parent))
        })
    }

    /// The derived display label for an issue this index knows.
    pub fn label(&self, issue: u32) -> String {
        self.identity_for_number(issue)
            .map_or_else(|| format!("#{issue}"), |identity| self.label_ref(&identity))
    }

    fn label_ref(&self, identity: &IssueRef) -> String {
        self.labels
            .get(identity)
            .cloned()
            .unwrap_or_else(|| identity.to_string())
    }

    /// An issue's raw status, as the index recorded it.
    pub fn status_of(&self, issue: u32) -> Option<&str> {
        self.identity_for_number(issue)
            .and_then(|identity| self.statuses.get(&identity))
            .map(String::as_str)
    }

    /// Whether `issue` exists in the indexed set.
    pub fn contains(&self, issue: u32) -> bool {
        self.identity_for_number(issue).is_some()
    }

    /// Whether a canonical reference resolves in the indexed set.
    pub fn contains_ref(&self, reference: &IssueRef) -> bool {
        self.labels.contains_key(reference)
    }

    /// Every child whose recorded parent no longer exists.
    ///
    /// Each retains the **recorded** number so the reference can be repaired
    /// rather than merely reported (`data-model.md` §5).
    pub fn unresolved(&self) -> Vec<UnresolvedParentState> {
        let mut out: Vec<UnresolvedParentState> = self
            .parent_by_child
            .iter()
            .filter(|(_, parent)| !self.labels.contains_key(parent))
            .map(|(child, parent)| UnresolvedParentState {
                child: self.number_for_identity(child).unwrap_or_default(),
                recorded_parent: *parent,
                source_file: self.filenames.get(child).cloned().unwrap_or_default(),
                reason: unresolved_reason(
                    self.number_for_identity(child).unwrap_or_default(),
                    *parent,
                ),
            })
            .collect();
        out.sort_by_key(|s| s.child);
        out
    }
}

// ---------------------------------------------------------------------------
// T005 — UnresolvedParentState and deletion impact
// ---------------------------------------------------------------------------

/// The diagnosed state of a child whose parent no longer exists
/// (`data-model.md` §5).
///
/// The child's file is **not** modified when its parent is deleted: the
/// reference survives so it can be repaired. Any cascade would be an escalation
/// trigger.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnresolvedParentState {
    /// The child holding the reference.
    pub child: u32,
    /// The reference exactly as stored, retained for repair.
    pub recorded_parent: IssueRef,
    /// The child file carrying the unresolved reference.
    pub source_file: String,
    /// Human-readable text, reused verbatim by lint, the CLI, the TUI and MCP.
    ///
    /// One string, produced here, because four surfaces re-deriving it is four
    /// chances to word it differently.
    pub reason: String,
}

/// The single wording for an unresolved parent reference.
pub fn unresolved_reason(child: u32, parent: impl std::fmt::Display) -> String {
    let parent = parent.to_string();
    let parent = if parent.bytes().all(|byte| byte.is_ascii_digit()) {
        format!("#{parent}")
    } else {
        parent
    };
    format!(
        "{child}'s parent {parent} no longer exists (the reference is kept so it can be repaired)"
    )
}

/// The issues a delete of `parent` would orphan, in issue-number order.
///
/// It **reports**; it does not delete, and the module has no mutating sibling
/// (T005 step 2). WP05 consumes this for the delete-time impact notice.
pub fn affected_by_deletion<N: HierarchyNode>(issues: &[N], parent: u32) -> Vec<ChildRef> {
    let index = HierarchyIndex::build(issues);
    let Some(parent_identity) = index.identity_for_number(parent) else {
        return Vec::new();
    };
    index
        .children_by_parent
        .get(&parent_identity)
        .map(|children| {
            children
                .iter()
                .map(|child| ChildRef {
                    id: *child,
                    number: index.number_for_identity(child).unwrap_or_default(),
                    display: index.label_ref(child),
                })
                .collect()
        })
        .unwrap_or_default()
}

// ---------------------------------------------------------------------------
// T002 — set / change / clear, with single-parent enforced by the API
// ---------------------------------------------------------------------------

/// The three hierarchy mutations, as the `## History` section records them.
///
/// Declared here rather than added to `model::HistoryEventKind` because WP01 may
/// not edit `src/model.rs`; WP02 maps these onto that enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParentEventKind {
    /// An issue gained its first parent.
    ParentSet,
    /// An existing parent reference was repointed.
    ParentChanged,
    /// The reference was removed.
    ParentCleared,
}

impl ParentEventKind {
    /// The canonical snake_case spelling the History section will carry.
    pub fn as_str(self) -> &'static str {
        match self {
            ParentEventKind::ParentSet => "parent_set",
            ParentEventKind::ParentChanged => "parent_changed",
            ParentEventKind::ParentCleared => "parent_cleared",
        }
    }
}

/// One hierarchy mutation, ready for storage to append to `## History`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParentEvent {
    /// Which of the three mutations this is.
    pub kind: ParentEventKind,
    /// The child that changed.
    pub child: u32,
    /// The parent after the change; `None` for a clear.
    pub parent: Option<u32>,
}

/// The outcome of a hierarchy mutation: the new state plus the event to record.
///
/// The service produces the event and **does not write**; storage performs the
/// write using it, so the atomicity rule lives in exactly one place.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParentChange {
    /// The child whose reference changed.
    pub child: u32,
    /// The child's parent after the change.
    pub parent: Option<u32>,
    /// The child's parent number before the mutation, for the human audit line.
    pub previous: Option<u32>,
    /// The canonical parent reference to persist; `None` for a clear.
    pub parent_ref: Option<IssueRef>,
    /// The event to append, or `None` when the mutation was a no-op.
    ///
    /// `None` for clearing a child that had no parent: that is not a change, and
    /// recording it would put an entry in the audit trail for nothing.
    pub event: Option<ParentEvent>,
}

/// Why a hierarchy mutation was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HierarchyError {
    /// A validation rule rejected the proposal. Blocking: no write, no event.
    ///
    /// This is the **only** refusal the service produces. It used to carry a
    /// second variant, `UnknownIssue { selector }`, for "the named issue is not in
    /// the snapshot" — but the service takes issue **numbers**, not selectors, so a
    /// selector-shaped variant was the wrong shape and nothing ever constructed it.
    /// An unknown child is now a `Rejected` result carrying
    /// [`HierarchyDiagnosticKind::UnknownChild`], which flows through the same
    /// renderer as every other refusal (decision on tix #1373, option 1).
    Rejected(HierarchyValidationResult),
}

impl std::fmt::Display for HierarchyError {
    /// The user-facing message, **without** an `invalid input:` prefix.
    ///
    /// The prefix belongs to [`crate::error::TixError::InvalidInput`], which
    /// [`From`] supplies. Emitting it here too produced the doubled
    /// `invalid input: invalid input: ...` on the one path that reached this impl.
    ///
    /// A rejected proposal renders **every** diagnostic through the shared
    /// [`render_diagnostics`], the same renderer the relationship service uses, so
    /// a user who learned `tix link`'s refusal format does not have to learn a
    /// second one. It deliberately does not report only the first: a rejection can
    /// carry several findings, and showing one at a time makes a user fix and retry
    /// repeatedly to discover the rest.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HierarchyError::Rejected(result) if result.errors.is_empty() => {
                f.write_str("hierarchy validation failed")
            }
            HierarchyError::Rejected(result) => f.write_str(&render_diagnostics(
                "E-tix-hierarchy",
                result
                    .errors
                    .iter()
                    .map(|e| (e.kind.as_str(), e.message.as_str())),
            )),
        }
    }
}

impl std::error::Error for HierarchyError {}

/// A hierarchy refusal becomes user input error, so `?` works at the call site.
///
/// The conversion is total and lossless: the type's own `Display` already renders
/// the full diagnostic set, and `InvalidInput` supplies the `invalid input:` prefix
/// every other validation failure in the crate carries.
impl From<HierarchyError> for TixError {
    fn from(err: HierarchyError) -> TixError {
        TixError::Refused(err.to_string())
    }
}

/// Point `child` at `parent`, whatever it pointed at before.
///
/// Single-parent is enforced by the **shape**: `parent` is one `Option<u32>`, and
/// no function here accepts a collection. A request for two parents is not
/// expressible, not merely rejected (C-001).
///
/// Validates before producing anything, so a refused call yields no change and
/// no event.
///
/// Setting the parent the child already has is a **no-op**, and reports one:
/// `ParentChange::event` documents `None` "when the mutation was a no-op: that is
/// not a change, and recording it would put an entry in the audit trail for
/// nothing". This function was the one place that did not honour its own return
/// type's contract — it emitted a `parent_changed` whose detail read
/// `parent #1 -> #1` — while `change_parent` did.
///
/// **Validation runs first, and the no-op check second.** The order is the whole
/// point. An early return for the no-op case was tried and rejected: it skipped
/// `validate_proposed`, so a child that *already recorded* itself as its own
/// parent — or a parent that no longer exists — was accepted as a no-op, while
/// the identical request against a child that did not already record it was
/// correctly refused. Contract §3 says a self-parent is "**always** rejected" and
/// an unknown parent is "rejected at write time"; no prior state may buy an
/// exception. A no-op is a statement about a *valid* request that happens to be
/// redundant, so it can only be recognised after the request is known to be valid.
pub fn set_parent(
    index: &HierarchyIndex,
    child: u32,
    parent: u32,
) -> Result<ParentChange, HierarchyError> {
    set_parent_ref(
        index,
        index
            .identity_for_number(child)
            .unwrap_or(IssueRef::Number(child)),
        index
            .identity_for_number(parent)
            .unwrap_or(IssueRef::Number(parent)),
    )
}

/// Canonical-reference form of [`set_parent`].
pub fn set_parent_ref(
    index: &HierarchyIndex,
    child: IssueRef,
    parent: IssueRef,
) -> Result<ParentChange, HierarchyError> {
    let result = validate_proposed_ref(index, child, Some(parent));
    if result.blocking {
        return Err(HierarchyError::Rejected(result));
    }
    let child_number = index
        .number_for_identity(&child)
        .or_else(|| child.as_number())
        .unwrap_or_default();
    let parent_number = index
        .number_for_identity(&parent)
        .or_else(|| parent.as_number())
        .unwrap_or_default();
    let previous = index.parent_ref_for(&child).copied();
    if previous == Some(parent) {
        return Ok(ParentChange {
            child: child_number,
            parent: Some(parent_number),
            previous: previous.and_then(|reference| index.number_for_identity(&reference)),
            parent_ref: Some(parent),
            event: None,
        });
    }
    let kind = if previous.is_some() {
        ParentEventKind::ParentChanged
    } else {
        ParentEventKind::ParentSet
    };
    Ok(ParentChange {
        child: child_number,
        parent: Some(parent_number),
        previous: previous.and_then(|reference| index.number_for_identity(&reference)),
        parent_ref: Some(parent),
        event: Some(ParentEvent {
            kind,
            child: child_number,
            parent: Some(parent_number),
        }),
    })
}

/// Repoint `child` at a new parent.
///
/// The same rule as [`set_parent`]; the distinct name is what callers read at the
/// call site, and the History event is the same `parent_changed` kind. Re-applying
/// the same parent is a no-op and yields **no** event, so a retried command does
/// not pad the audit trail.
///
/// Delegates with no early return of its own. An early return here looked like it
/// documented "repoint if different", but it also **skipped validation**: a child
/// that already recorded itself as its own parent, or already recorded a parent
/// that no longer exists, was accepted as a no-op — the one state where the
/// contract's "always rejected" rules must not bend. [`set_parent`] validates
/// first and no-ops second, and the two operations then cannot disagree.
pub fn change_parent(
    index: &HierarchyIndex,
    child: u32,
    parent: u32,
) -> Result<ParentChange, HierarchyError> {
    set_parent(index, child, parent)
}

/// Canonical-reference form of [`change_parent`].
pub fn change_parent_ref(
    index: &HierarchyIndex,
    child: IssueRef,
    parent: IssueRef,
) -> Result<ParentChange, HierarchyError> {
    set_parent_ref(index, child, parent)
}

/// Remove `child`'s parent, yielding the absent state rather than a dangling
/// value (`data-model.md` §1).
///
/// Clearing a child that has no parent is a no-op that produces no event.
///
/// An unknown **child** is refused, not treated as the no-op: validation runs
/// first (contract §3.5), so "valid and unchanged" stays distinct from "invalid"
/// (decision on tix #1373, option 1).
pub fn clear_parent(index: &HierarchyIndex, child: u32) -> Result<ParentChange, HierarchyError> {
    clear_parent_ref(
        index,
        index
            .identity_for_number(child)
            .unwrap_or(IssueRef::Number(child)),
    )
}

/// Canonical-reference form of [`clear_parent`].
pub fn clear_parent_ref(
    index: &HierarchyIndex,
    child: IssueRef,
) -> Result<ParentChange, HierarchyError> {
    let result = validate_proposed_ref(index, child, None);
    if result.blocking {
        return Err(HierarchyError::Rejected(result));
    }
    if index.parent_ref_for(&child).is_none() {
        let child_number = index.number_for_identity(&child).unwrap_or_default();
        return Ok(ParentChange {
            child: child_number,
            parent: None,
            previous: None,
            parent_ref: None,
            event: None,
        });
    }
    let child_number = index.number_for_identity(&child).unwrap_or_default();
    let previous = index
        .parent_ref_for(&child)
        .and_then(|reference| index.number_for_identity(reference));
    Ok(ParentChange {
        child: child_number,
        parent: None,
        previous,
        parent_ref: None,
        event: Some(ParentEvent {
            kind: ParentEventKind::ParentCleared,
            child: child_number,
            parent: None,
        }),
    })
}

// ---------------------------------------------------------------------------
// T003 — validation
// ---------------------------------------------------------------------------

/// The diagnostic kinds `contracts/hierarchy-service.md` §3 names, spelled exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HierarchyDiagnosticKind {
    /// `child == parent`.
    SelfParent,
    /// The proposed chain would close a cycle.
    Cycle,
    /// The child is not in the snapshot at all, so the write was refused.
    ///
    /// **Sibling of [`Self::UnknownParent`]**: the service validates both ends of
    /// the proposed edge. `Store` resolves selectors before calling in, so the CLI
    /// cannot reach this today, but two direct consumers can — the parity harness
    /// and any future caller that hands the service a snapshot and a number
    /// (decision on tix #1373, option 1).
    UnknownChild,
    /// The parent selector resolved to no issue, so the write was refused.
    UnknownParent,
    /// A numeric parent alias matches more than one issue.
    AmbiguousTarget,
    /// Two issues claim the same canonical id used by the parent graph.
    DuplicateIdentity,
    /// An issue records a parent that is not in the snapshot (WP05 T022).
    ///
    /// **Distinct from [`Self::UnknownParent`]**, and the distinction is the
    /// difference between a rejected write and retained data. `unknown_parent` means
    /// the service refused to write anything, so there is nothing to repair;
    /// `unresolved_parent` means a reference *was* written and its target has since
    /// gone, so a user must re-point it. Contract §3 rule 4 draws the line ("a
    /// reference that *later* becomes unresolvable is not rejected — it becomes the
    /// `UnresolvedParentState` described in §5") and T022 step 1 fixes the name.
    UnresolvedParent,
}

impl HierarchyDiagnosticKind {
    /// The contract's spelling, used verbatim in lint and in MCP payloads.
    pub fn as_str(self) -> &'static str {
        match self {
            HierarchyDiagnosticKind::SelfParent => "self_parent",
            HierarchyDiagnosticKind::UnresolvedParent => "unresolved_parent",
            HierarchyDiagnosticKind::Cycle => "cycle",
            HierarchyDiagnosticKind::UnknownChild => "unknown_child",
            HierarchyDiagnosticKind::UnknownParent => "unknown_parent",
            HierarchyDiagnosticKind::AmbiguousTarget => "ambiguous_target",
            HierarchyDiagnosticKind::DuplicateIdentity => "duplicate_identity",
        }
    }
}

fn alias_error_text(error: &crate::id::AliasError) -> String {
    match error {
        crate::id::AliasError::Missing(value) => format!("`{value}` resolves to no issue"),
        crate::id::AliasError::Ambiguous { alias, candidates } => format!(
            "`{alias}` is ambiguous: {}",
            candidates
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(", ")
        ),
        crate::id::AliasError::DuplicateId { id, numbers } => {
            format!("id `{id}` is claimed by issues {numbers:?}")
        }
    }
}

/// One field-aware hierarchy diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HierarchyDiagnostic {
    /// Which rule was broken.
    pub kind: HierarchyDiagnosticKind,
    /// The issue the diagnostic is about.
    pub issue: u32,
    /// The frontmatter field at fault — always [`PARENT_KEY`] today, carried
    /// explicitly so a future field does not need a new diagnostic type.
    pub field: String,
    /// Human-readable message.
    pub message: String,
    /// The exact source file, when the issue-number alias is ambiguous.
    pub source_file: Option<String>,
    /// The offending chain, for a cycle: the walk from the proposed parent up to
    /// the issue that closes the loop, inclusive.
    pub path: Option<Vec<u32>>,
}

impl HierarchyDiagnostic {
    fn new(kind: HierarchyDiagnosticKind, issue: u32, message: String) -> Self {
        Self {
            kind,
            issue,
            field: PARENT_KEY.to_string(),
            message,
            source_file: None,
            path: None,
        }
    }

    fn with_source_file(mut self, filename: impl Into<String>) -> Self {
        self.source_file = Some(filename.into());
        self
    }
}

/// The result of hierarchy validation (`data-model.md` §4).
///
/// Mirrors the relationship service's shape, so lint consumes both the same way.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HierarchyValidationResult {
    /// Every diagnostic found.
    pub errors: Vec<HierarchyDiagnostic>,
    /// True when the write must be rejected.
    pub blocking: bool,
}

impl HierarchyValidationResult {
    /// A clean result: no findings, not blocking.
    pub fn clean() -> Self {
        Self {
            errors: Vec::new(),
            blocking: false,
        }
    }

    /// A result carrying one blocking diagnostic.
    pub fn blocking(diagnostic: HierarchyDiagnostic) -> Self {
        Self {
            blocking: true,
            errors: vec![diagnostic],
        }
    }

    /// Whether anything at all was found, blocking or not.
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// The diagnostic kinds present, in order.
    pub fn kinds(&self) -> Vec<HierarchyDiagnosticKind> {
        self.errors.iter().map(|e| e.kind).collect()
    }
}

/// Validate a proposed parent change, before any write.
///
/// Checks, in order: the child exists, the parent exists, `child != parent`, and
/// the proposed chain does not close a cycle. Returns a result rather than
/// `Err` for rule violations so `tix lint` can call the same code.
///
/// **Both ends of the edge are validated.** The child check is the symmetric half
/// of the `unknown_parent` check: a service that emits an event for a child that
/// does not exist is the kind of thing a later direct caller relies on by
/// accident. It also runs for a `clear` (`parent: None`), so an unknown child is
/// refused rather than returning the "already absent" no-op (decision on tix
/// #1373, option 1).
pub fn validate_proposed(
    index: &HierarchyIndex,
    child: u32,
    parent: Option<u32>,
) -> HierarchyValidationResult {
    validate_proposed_ref(
        index,
        index
            .identity_for_number(child)
            .unwrap_or(IssueRef::Number(child)),
        parent.map(|parent| {
            index
                .identity_for_number(parent)
                .unwrap_or(IssueRef::Number(parent))
        }),
    )
}

/// Canonical-reference form of [`validate_proposed`].
pub fn validate_proposed_ref(
    index: &HierarchyIndex,
    child: IssueRef,
    parent: Option<IssueRef>,
) -> HierarchyValidationResult {
    let child_number = index
        .number_for_identity(&child)
        .or_else(|| child.as_number())
        .unwrap_or_default();
    if !index.contains_ref(&child) {
        return HierarchyValidationResult::blocking(HierarchyDiagnostic::new(
            HierarchyDiagnosticKind::UnknownChild,
            child_number,
            format!("{PARENT_KEY}: child {} does not exist", child.human()),
        ));
    }
    let Some(parent) = parent else {
        // A clear cannot violate a hierarchy rule: it removes an edge.
        return HierarchyValidationResult::clean();
    };
    let parent_number = index
        .number_for_identity(&parent)
        .or_else(|| parent.as_number())
        .unwrap_or_default();
    if !index.contains_ref(&parent) {
        return HierarchyValidationResult::blocking(HierarchyDiagnostic::new(
            HierarchyDiagnosticKind::UnknownParent,
            child_number,
            format!("{PARENT_KEY}: {} does not exist", parent.human()),
        ));
    }
    if child == parent {
        return HierarchyValidationResult::blocking(HierarchyDiagnostic::new(
            HierarchyDiagnosticKind::SelfParent,
            child_number,
            format!("{PARENT_KEY}: an issue cannot be its own parent"),
        ));
    }
    match cycle_path_ref(index, child, parent) {
        Some(path) => {
            let mut diagnostic = HierarchyDiagnostic::new(
                HierarchyDiagnosticKind::Cycle,
                child_number,
                format!(
                    "{PARENT_KEY}: setting parent {} closes a cycle ({})",
                    parent_number,
                    render_path(&path)
                ),
            );
            diagnostic.path = Some(path);
            HierarchyValidationResult::blocking(diagnostic)
        }
        None => HierarchyValidationResult::clean(),
    }
}

/// The `## History` detail line for a parent change: `parent #1 -> #2`.
///
/// **One renderer, in the service, for every caller.** Three call sites need this
/// string — the storage write path, the `--parent` edit flag, and MCP's `update_issue`
/// when WP07 lands — and a spelling rule that lives at the call site is a spelling
/// rule that will drift. It lives here, beside the event kinds it describes, and
/// takes plain numbers so it depends on no model type.
pub fn change_detail<B, A>(before: Option<B>, after: Option<A>) -> String
where
    B: Into<IssueRef>,
    A: Into<IssueRef>,
{
    let render = |reference: Option<IssueRef>| match reference {
        Some(reference) => reference.human(),
        None => "none".to_string(),
    };
    format!(
        "parent {} -> {}",
        render(before.map(Into::into)),
        render(after.map(Into::into))
    )
}

/// Validate a proposed parent for an issue that **does not exist yet**.
///
/// The create path's entry point, and the one place the two obvious rules cannot
/// apply: a not-yet-created child has no number, so it cannot be its own parent and
/// cannot close a cycle. `unknown_parent` is therefore the only rule that can bite,
/// and asking `validate_proposed` with a placeholder child number would encode that
/// reasoning as a lie in a diagnostic.
///
/// The diagnostic's `issue` is [`NO_ISSUE_YET`] for this path, because there is no
/// issue to name. A caller with a real child must use [`set_parent`] or
/// [`change_parent`], which report the real number.
pub fn validate_new_parent(index: &HierarchyIndex, parent: u32) -> Result<(), HierarchyError> {
    if index.contains(parent) {
        return Ok(());
    }
    Err(HierarchyError::Rejected(
        HierarchyValidationResult::blocking(HierarchyDiagnostic::new(
            HierarchyDiagnosticKind::UnknownParent,
            NO_ISSUE_YET,
            format!("{PARENT_KEY}: #{parent} does not exist"),
        )),
    ))
}

/// The issue number a diagnostic carries when it is about an issue that does not
/// exist yet — the create path's "no child" marker.
///
/// `u32::MAX`, and **provably** not a real issue number: `Store::resolve_next_number`
/// allocates with `max.checked_add(1)` and returns `Err("issue-number overflow")`
/// when that would wrap, so `u32::MAX` is never handed out.
///
/// `0` was the first choice and it is **wrong** — `resolve_next_number` returns
/// `Ok(0)` for an empty directory, so the first issue in every fresh repository is
/// `#0` (found by running the binary, not by reading the code). A `0` sentinel would
/// have named a real issue in exactly the repositories most likely to use the create
/// path. Pre-existing number allocation, filed separately as tix #1376.
pub const NO_ISSUE_YET: u32 = u32::MAX;

/// The chain that closes a cycle if `child` were pointed at `parent`, or `None`.
///
/// **Iterative**, from `parent` upward through the existing parents. Because each
/// issue has at most one parent the hierarchy is a *functional* graph, so this is
/// the only walk needed — there is no branching to explore. Recursion would
/// overflow the stack on a 10,000-deep chain (NFR-001), so the loop carries its
/// own `visited` set and terminates on the first repeat or the root.
fn cycle_path_ref(index: &HierarchyIndex, child: IssueRef, parent: IssueRef) -> Option<Vec<u32>> {
    let mut path = vec![index.number_for_identity(&child).unwrap_or_default()];
    let mut visited: BTreeSet<IssueRef> = BTreeSet::new();
    visited.insert(child);
    let mut current = parent;
    loop {
        if !visited.insert(current) {
            // `current` already appears in the walk, so the proposed edge closes
            // the loop. The path is reported from the first occurrence so the
            // message shows the cycle itself, not the tail that led to it.
            let current_number = index.number_for_identity(&current).unwrap_or_default();
            let start = path
                .iter()
                .position(|number| *number == current_number)
                .unwrap_or(0);
            return Some(path[start..].to_vec());
        }
        path.push(index.number_for_identity(&current).unwrap_or_default());
        match index.parent_ref_for(&current).copied() {
            // A dangling reference ends the walk. It cannot close a cycle, and
            // it is reported by `unresolved` instead.
            Some(next) if index.contains_ref(&next) => current = next,
            _ => return None,
        }
    }
}

/// `1 -> 2 -> 3`, for a cycle message.
fn render_path(path: &[u32]) -> String {
    path.iter()
        .map(|n| n.to_string())
        .collect::<Vec<_>>()
        .join(" -> ")
}

/// Validate a whole in-memory snapshot.
///
/// **Never** returns `Err` — lint calls it directly and must keep scanning, so a
/// single bad issue cannot abort the sweep (the relationship service's FR-018
/// rule, reused per C-002).
///
/// Reports every self-parent, every dangling reference, and every cycle.
pub fn validate_hierarchy<N: HierarchyNode>(issues: &[N]) -> HierarchyValidationResult {
    let index = HierarchyIndex::build(issues);
    let mut errors: Vec<HierarchyDiagnostic> = index.alias_diagnostics().to_vec();

    let mut dangling: Vec<HierarchyDiagnostic> = index
        .unresolved()
        .into_iter()
        .map(|state| {
            // `UnresolvedParent`, not `UnknownParent`: the reference exists and is
            // retained, so there is something for a user to repair. The two are one
            // situation only if you forget that one of them already wrote a file.
            HierarchyDiagnostic::new(
                HierarchyDiagnosticKind::UnresolvedParent,
                state.child,
                state.reason,
            )
            .with_source_file(state.source_file)
        })
        .collect();
    errors.append(&mut dangling);

    let mut self_parents: Vec<HierarchyDiagnostic> = issues
        .iter()
        .filter(|issue| {
            let reference = hierarchy_ref(*issue);
            index
                .parent_ref_for(&reference)
                .is_some_and(|parent| *parent == reference)
        })
        .map(|issue| {
            HierarchyDiagnostic::new(
                HierarchyDiagnosticKind::SelfParent,
                issue.number(),
                format!("{PARENT_KEY}: an issue cannot be its own parent"),
            )
            .with_source_file(issue.filename().unwrap_or(""))
        })
        .collect();
    errors.append(&mut self_parents);

    // One cycle per connected component, reported on the issue whose parent edge
    // closes it. Deterministic because the walk order is issue-number order.
    let mut seen: BTreeSet<IssueRef> = BTreeSet::new();
    let mut sorted: Vec<IssueRef> = issues.iter().map(hierarchy_ref).collect();
    sorted.sort_by_key(|reference| index.number_for_identity(reference).unwrap_or_default());
    for child in sorted {
        let Some(parent) = index.parent_ref_for(&child).copied() else {
            continue;
        };
        if !index.contains_ref(&parent) || seen.contains(&child) {
            continue;
        }
        if let Some(path) = cycle_path_ref(&index, child, parent) {
            for node in &path {
                if let Some(reference) = index
                    .refs_by_number
                    .get(node)
                    .and_then(|refs| (refs.len() == 1).then(|| refs[0]))
                {
                    seen.insert(reference);
                }
            }
            let child_number = index.number_for_identity(&child).unwrap_or_default();
            let mut diagnostic = HierarchyDiagnostic::new(
                HierarchyDiagnosticKind::Cycle,
                child_number,
                format!("{PARENT_KEY}: cycle ({})", render_path(&path)),
            );
            if let Some(filename) = index.filenames.get(&child) {
                diagnostic.source_file = Some(filename.clone());
            }
            diagnostic.path = Some(path);
            errors.push(diagnostic);
        }
    }

    HierarchyValidationResult {
        blocking: !errors.is_empty(),
        errors,
    }
}

// ---------------------------------------------------------------------------
// T004 — the typed rollup
// ---------------------------------------------------------------------------

/// Which population the rollup's figures describe (`data-model.md` §3).
///
/// Carried on the value so a consumer can never mistake one figure for the other,
/// and so widening the basis later is a visible change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionBasis {
    /// Only the issue's direct children.
    DirectChildren,
}

impl CompletionBasis {
    /// The wording a surface should print next to the figure.
    pub fn as_str(self) -> &'static str {
        match self {
            CompletionBasis::DirectChildren => "direct children",
        }
    }
}

/// The derived progress figures for a parent (`data-model.md` §3, FR-003).
///
/// A typed value, never a rendered string, so CLI, TUI and MCP can be compared
/// for equality (NFR-002).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParentRollup {
    /// The issue the rollup is about.
    pub parent: u32,
    /// Direct children.
    pub direct_children: usize,
    /// Direct children in the caller's completion column.
    pub completed_children: usize,
    /// The typed progress value — [`planning::Progress`], reused rather than
    /// reinvented (research R3).
    pub progress: Progress,
    /// Which population the figures describe.
    pub completion_basis: CompletionBasis,
}

/// Compute the rollup for `issue`.
///
/// `done_column` is the board's **configured** completion column, resolved by the
/// caller from config. It is a parameter and never a literal `"done"` here, so a
/// board that calls its completion column something else still reports correctly.
///
/// Reuses the index's child list rather than re-scanning the issue set, so a
/// board render stays linear in the number of children.
pub fn rollup(index: &HierarchyIndex, issue: u32, done_column: &str) -> ParentRollup {
    let membership = index.children_of(issue);
    let completed_children = membership
        .children
        .iter()
        .filter(|child| index.status_of(child.number) == Some(done_column))
        .count();
    ParentRollup {
        parent: issue,
        direct_children: membership.child_count,
        completed_children,
        progress: Progress {
            done: completed_children,
            total: membership.child_count,
        },
        completion_basis: CompletionBasis::DirectChildren,
    }
}

/// Reuse the relationship graph's validation idiom rather than a second one.
///
/// Not used by this module's own validation — the hierarchy's functional-graph
/// walk is genuinely different from a relationship cycle check, and reusing a
/// general graph walk here would mean exploring branches that cannot exist. This
/// exists so the *naming* has one home and a future reader can see that the
/// similarity was considered and rejected for a reason.
#[allow(dead_code)]
fn relationship_graph_of<'a, N: HierarchyNode + 'a>(issues: &'a [N]) -> RelationshipGraph<'a> {
    // A hierarchy-only snapshot has no edges, so the graph is built empty. The
    // call exists to document the decision, not to validate anything.
    let _ = issues;
    RelationshipGraph::new(&[], "done")
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    /// An in-memory issue. Nothing here touches the filesystem, which is the point.
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct Node {
        number: u32,
        title: String,
        status: String,
        parent: Option<u32>,
    }

    impl Node {
        fn new(number: u32, title: &str) -> Self {
            Self {
                number,
                title: title.to_string(),
                status: "todo".to_string(),
                parent: None,
            }
        }
        fn with_status(mut self, status: &str) -> Self {
            self.status = status.to_string();
            self
        }
    }

    impl HierarchyNode for Node {
        fn number(&self) -> u32 {
            self.number
        }
        fn title(&self) -> &str {
            &self.title
        }
        fn status(&self) -> &str {
            &self.status
        }
        fn parent_number(&self) -> Option<u32> {
            self.parent
        }
    }

    /// A node with an explicit status and parent, for the rollup fixtures.
    fn node(number: u32, title: &str, status: &str, parent: Option<u32>) -> Node {
        let mut n = Node::new(number, title).with_status(status);
        n.parent = parent;
        n
    }

    fn nodes(spec: &[(u32, &str, Option<u32>)]) -> Vec<Node> {
        spec.iter()
            .map(|(n, t, p)| {
                let mut node = Node::new(*n, t);
                node.parent = *p;
                node
            })
            .collect()
    }

    // -- T001 ------------------------------------------------------------

    #[test]
    fn children_are_ordered_by_issue_number_regardless_of_input_order() {
        let shuffled = nodes(&[
            (9, "I", Some(1)),
            (3, "C", Some(1)),
            (7, "G", Some(1)),
            (5, "E", Some(1)),
        ]);
        let index = HierarchyIndex::build(&shuffled);
        let membership = index.children_of(1);
        assert_eq!(
            membership
                .children
                .iter()
                .map(|c| c.number)
                .collect::<Vec<_>>(),
            vec![3, 5, 7, 9],
            "children must be ascending by number even when the input is not"
        );
        assert_eq!(membership.child_count, 4);
        assert_eq!(membership.children[0].display, "#3 C");
    }

    #[test]
    fn the_index_is_stable_across_repeated_builds_from_the_same_input() {
        let issues = nodes(&[(1, "A", None), (2, "B", Some(1)), (3, "C", Some(1))]);
        let first = HierarchyIndex::build(&issues);
        let second = HierarchyIndex::build(&issues);
        assert_eq!(first, second, "two builds of one snapshot must be equal");
        // And the derived reads, not just the struct, are byte-identical.
        assert_eq!(first.children_of(1), second.children_of(1));
        assert_eq!(rollup(&first, 1, "done"), rollup(&second, 1, "done"));
    }

    #[test]
    fn a_child_appears_under_exactly_one_parent() {
        let issues = nodes(&[(1, "A", None), (2, "B", Some(1)), (3, "C", Some(2))]);
        let index = HierarchyIndex::build(&issues);
        let mut appearances = 0;
        for parent in 1..=3 {
            appearances += index.children_of(parent).child_count;
        }
        assert_eq!(
            appearances, 2,
            "each of the two parented issues must be counted exactly once"
        );
        assert_eq!(index.parent_of(2), Some(1));
        assert_eq!(index.parent_of(1), None);
    }

    #[test]
    fn no_child_list_is_stored_in_the_index() {
        // C-003's mechanical guard: the index holds maps of canonical references. There is
        // nowhere for a child list to live, so the "derived, never stored"
        // invariant cannot be violated by a later change that adds one.
        let issues = nodes(&[(1, "A", None), (2, "B", Some(1))]);
        let index = HierarchyIndex::build(&issues);
        // `HierarchyIndex` has no field that is a `Vec<ChildRef>`; if one were
        // added, this file would fail to compile against the struct literal below.
        let rebuilt = HierarchyIndex {
            parent_by_child: index.parent_by_child.clone(),
            children_by_parent: index.children_by_parent.clone(),
            numbers: index.numbers.clone(),
            refs_by_number: index.refs_by_number.clone(),
            labels: index.labels.clone(),
            statuses: index.statuses.clone(),
            filenames: index.filenames.clone(),
            aliases: index.aliases.clone(),
            alias_diagnostics: index.alias_diagnostics.clone(),
        };
        assert_eq!(rebuilt, index, "the index is exactly these fields");
        // And `children_of` is the only way to get children — the private map is
        // number-only, so a display label can only come from derivation.
        assert!(
            index
                .children_by_parent
                .values()
                .all(|v| v.iter().all(|n| index.labels.contains_key(n)))
        );
    }

    #[test]
    fn an_issue_with_no_children_returns_an_empty_membership_not_an_error() {
        let index = HierarchyIndex::build(&nodes(&[(1, "A", None)]));
        let membership = index.children_of(1);
        assert_eq!(membership.child_count, 0);
        assert_eq!(membership.children, [] as [crate::hierarchy::ChildRef; 0]);
        assert_eq!(membership.parent, 1);
    }

    // -- T002 ------------------------------------------------------------

    #[test]
    fn set_then_change_then_clear_produces_three_distinct_states() {
        let issues = nodes(&[
            (1, "P", None),
            (2, "A", None),
            (3, "B", None),
            (4, "C", None),
        ]);
        let index = HierarchyIndex::build(&issues);

        let set = set_parent(&index, 2, 1).unwrap();
        assert_eq!(set.parent, Some(1));
        assert_eq!(
            set.event.as_ref().map(|e| e.kind),
            Some(ParentEventKind::ParentSet)
        );

        // Change needs an index that already reflects the set.
        let mut after_set = issues.clone();
        after_set[1].parent = Some(1);
        let index2 = HierarchyIndex::build(&after_set);
        let changed = change_parent(&index2, 2, 3).unwrap();
        assert_eq!(changed.parent, Some(3));
        assert_eq!(
            changed.event.as_ref().map(|e| e.kind),
            Some(ParentEventKind::ParentChanged)
        );

        let mut after_change = after_set.clone();
        after_change[1].parent = Some(3);
        let index3 = HierarchyIndex::build(&after_change);
        let cleared = clear_parent(&index3, 2).unwrap();
        assert_eq!(cleared.parent, None);
        assert_eq!(
            cleared.event.as_ref().map(|e| e.kind),
            Some(ParentEventKind::ParentCleared)
        );

        // Three distinct resulting states, so the sequence is observable.
        let states = [set.parent, changed.parent, cleared.parent];
        assert_eq!(states, [Some(1), Some(3), None]);
    }

    #[test]
    fn clearing_a_child_with_no_parent_is_a_no_op_with_no_event() {
        let index = HierarchyIndex::build(&nodes(&[(1, "A", None)]));
        let cleared = clear_parent(&index, 1).unwrap();
        assert_eq!(cleared.parent, None);
        assert!(
            cleared.event.is_none(),
            "a no-op must not pad the audit trail"
        );
    }

    #[test]
    fn setting_the_parent_the_child_already_has_is_a_no_op_with_no_event() {
        // The `set_parent` half of the pair. `change_parent` already had this
        // behaviour; `set_parent` emitted a `parent_changed` naming nothing,
        // contradicting `ParentChange::event`'s own documentation.
        let issues = nodes(&[(1, "P", None), (2, "C", Some(1))]);
        let index = HierarchyIndex::build(&issues);
        let again = set_parent(&index, 2, 1).unwrap();
        assert_eq!(
            again.parent,
            Some(1),
            "the resulting state is still reported"
        );
        assert!(
            again.event.is_none(),
            "an accepted mutation that changes nothing must not pad the audit trail"
        );
    }

    #[test]
    fn a_no_op_check_must_not_launder_a_self_parent() {
        // Regression. The no-op guard used to run *before* validation, so a child
        // that already recorded itself as its own parent was accepted as a no-op
        // while the same request against any other child was correctly refused.
        // Contract §3: a self-parent is rejected *always*.
        let index = HierarchyIndex::build(&nodes(&[(1, "P", None), (2, "C", Some(2))]));
        for (label, outcome) in [
            ("set_parent", set_parent(&index, 2, 2)),
            ("change_parent", change_parent(&index, 2, 2)),
        ] {
            let err = outcome.expect_err(&format!(
                "{label}(child=2, parent=2) must be refused even when 2 already records it"
            ));
            assert!(
                matches!(&err, HierarchyError::Rejected(r) if r.kinds() == [HierarchyDiagnosticKind::SelfParent]),
                "{label} refused for the wrong reason: {err:?}"
            );
        }
        // The control, so the test cannot pass by the rule being absent entirely.
        let clean = HierarchyIndex::build(&nodes(&[(1, "P", None), (2, "C", None)]));
        assert!(
            set_parent(&clean, 2, 2).is_err(),
            "the rule must still fire"
        );
    }

    #[test]
    fn a_no_op_check_must_not_launder_an_unknown_parent() {
        // Same regression, second rule. A child already pointing at a parent that
        // no longer exists must still be *refused* when asked to re-point there,
        // not accepted as a redundant request. The stored reference is kept for
        // repair (UnresolvedParentState); keeping it is not the same as accepting
        // a new write of the same dangling value.
        let index = HierarchyIndex::build(&nodes(&[(1, "P", None), (2, "C", Some(999))]));
        for (label, outcome) in [
            ("set_parent", set_parent(&index, 2, 999)),
            ("change_parent", change_parent(&index, 2, 999)),
        ] {
            let err = outcome.expect_err(&format!(
                "{label}(child=2, parent=999) must be refused: #999 is not in the snapshot"
            ));
            assert!(
                matches!(&err, HierarchyError::Rejected(r) if r.kinds() == [HierarchyDiagnosticKind::UnknownParent]),
                "{label} refused for the wrong reason: {err:?}"
            );
        }
        // A self-parent against a *clean* child is still refused, and a
        // legitimately redundant request is still a no-op.
        let clean = HierarchyIndex::build(&nodes(&[(1, "P", None), (2, "C", None)]));
        assert!(set_parent(&clean, 2, 2).is_err());
        let ok = HierarchyIndex::build(&nodes(&[(1, "P", None), (2, "C", Some(1))]));
        assert!(
            set_parent(&ok, 2, 1).unwrap().event.is_none(),
            "no-op still a no-op"
        );
    }

    #[test]
    fn re_applying_the_same_parent_is_a_no_op_with_no_event() {
        let issues = nodes(&[(1, "P", None), (2, "C", Some(1))]);
        let index = HierarchyIndex::build(&issues);
        let again = change_parent(&index, 2, 1).unwrap();
        assert_eq!(again.parent, Some(1));
        assert!(
            again.event.is_none(),
            "a retried command must not append a second event"
        );
    }

    #[test]
    fn a_second_parent_cannot_be_expressed() {
        // C-001 is enforced by the *shape*: `parent` is one `Option<u32>`, so a
        // request for two parents does not compile. The runtime half of the rule
        // is that a change replaces rather than adds.
        let issues = nodes(&[(1, "A", None), (2, "B", Some(1)), (3, "C", Some(1))]);
        assert_eq!(
            HierarchyIndex::build(&issues).children_of(1).child_count,
            2,
            "precondition: two children start under #1"
        );
        let mut after = issues.clone();
        after[1].parent = Some(3);
        let index2 = HierarchyIndex::build(&after);
        assert_eq!(
            index2.children_of(1).child_count,
            1,
            "repointing must move the child, never duplicate it"
        );
        assert_eq!(index2.parent_of(2), Some(3));
        assert_eq!(index2.children_of(3).child_count, 1);
    }

    // -- T003 ------------------------------------------------------------

    #[test]
    fn a_self_parent_is_rejected_with_its_own_diagnostic_kind() {
        let index = HierarchyIndex::build(&nodes(&[(1, "A", None)]));
        let result = validate_proposed(&index, 1, Some(1));
        assert!(result.blocking);
        assert_eq!(result.kinds(), vec![HierarchyDiagnosticKind::SelfParent]);
        assert_eq!(result.errors[0].field, PARENT_KEY);
    }

    #[test]
    fn an_unknown_parent_is_rejected_with_its_own_diagnostic_kind() {
        let index = HierarchyIndex::build(&nodes(&[(1, "A", None)]));
        let result = validate_proposed(&index, 1, Some(99));
        assert!(result.blocking);
        assert_eq!(result.kinds(), vec![HierarchyDiagnosticKind::UnknownParent]);
        assert!(
            result.errors[0].message.contains("#99"),
            "the message must name the missing parent: {}",
            result.errors[0].message
        );
    }

    #[test]
    fn a_three_node_cycle_is_rejected_and_the_path_is_reported() {
        let index = HierarchyIndex::build(&nodes(&[
            (1, "A", Some(2)),
            (2, "B", Some(3)),
            (3, "C", None),
        ]));
        let result = validate_proposed(&index, 3, Some(1));
        assert!(result.blocking);
        assert_eq!(result.kinds(), vec![HierarchyDiagnosticKind::Cycle]);
        let path = result.errors[0]
            .path
            .as_ref()
            .expect("a cycle must report its path");
        // The path is the loop in walk order: 3 -> 1 -> 2, and the *proposed* edge
        // 3->1 is what closes it, because 2's stored parent is 3. So the invariant
        // is that the last element's stored parent is the first — not that the
        // first and last are equal, which is what the first version asserted and
        // which was simply wrong about what a cycle path is.
        assert_eq!(
            index.parent_of(*path.last().expect("a cycle path is never empty")),
            path.first().copied(),
            "the reported path must be a closed loop"
        );
        assert_eq!(path.len(), 3, "the whole 3-node cycle must be shown");
        assert!(
            result.errors[0].message.contains("->"),
            "the message must render the chain: {}",
            result.errors[0].message
        );
    }

    #[test]
    fn a_deep_chain_is_walked_without_stack_overflow() {
        // NFR-001's guard. A recursive DFS passes every small case and dies here.
        const DEPTH: u32 = 10_000;
        let mut issues: Vec<Node> = (1..=DEPTH + 1)
            .map(|n| {
                let mut node = Node::new(n, "n");
                // Node `DEPTH + 1` is a second root, so the child lives in the
                // snapshot but outside the chain. It has to be *in* the index at
                // all: the service refuses a child it cannot see (#1373), so the
                // walk is what is under test here, not the membership check.
                node.parent = if n == 1 || n == DEPTH + 1 {
                    None
                } else {
                    Some(n - 1)
                };
                node
            })
            .collect();
        let index = HierarchyIndex::build(&issues);

        // A walk that runs all the way to the root and finds no cycle. The child
        // sits outside the chain, so this is the long *non-cyclic* path — the case
        // a recursive DFS blows the stack on.
        //
        // (The first version proposed `1 -> 2` and asserted it was *not* a cycle.
        // It is one: 2's stored parent is already 1. The assertion was wrong, not
        // the walk.)
        let outside_child = DEPTH + 1;
        let result = validate_proposed(&index, outside_child, Some(DEPTH / 2));
        assert!(
            !result.blocking,
            "pointing a new child into the middle of a 10,000-deep chain is not a \
             cycle: {:?}",
            result.errors
        );

        // And closing the loop at the far end *is* detected, iteratively.
        let root = DEPTH;
        issues[root as usize - 1].parent = Some(root);
        let index2 = HierarchyIndex::build(&issues);
        let result = validate_proposed(&index2, 1, Some(root));
        assert!(
            result.blocking,
            "a 10,000-deep chain closed into a cycle must be caught"
        );
        assert_eq!(result.kinds(), vec![HierarchyDiagnosticKind::Cycle]);
    }

    #[test]
    fn a_clean_hierarchy_validates_with_no_findings() {
        let issues = nodes(&[
            (1, "Root", None),
            (2, "A", Some(1)),
            (3, "B", Some(1)),
            (4, "C", Some(2)),
        ]);
        let result = validate_hierarchy(&issues);
        assert!(result.is_empty(), "unexpected: {:?}", result.errors);
        assert!(!result.blocking);
    }

    #[test]
    fn validate_hierarchy_reports_each_kind_over_a_snapshot() {
        let issues = nodes(&[
            (1, "Self", Some(1)),
            (2, "Dangling", Some(99)),
            (3, "A", Some(4)),
            (4, "B", Some(3)),
        ]);
        let result = validate_hierarchy(&issues);
        assert!(result.blocking);
        let kinds = result.kinds();
        for expected in [
            HierarchyDiagnosticKind::SelfParent,
            // `UnresolvedParent`, not `UnknownParent`. WP01 folded the two together
            // and this test asserted the folded spelling; WP05 T022 step 1 fixes the
            // name, and the distinction is the difference between a write the
            // service **refused** and a reference that was written and whose target
            // has since gone. The diagnostic's `issue` is the **child**, which is
            // what lint attributes to a file — so the contract's "names the child and
            // the recorded parent" is satisfied by the pair `(issue, message)`.
            HierarchyDiagnosticKind::UnresolvedParent,
            HierarchyDiagnosticKind::Cycle,
        ] {
            assert!(
                kinds.contains(&expected),
                "expected {expected:?} in {kinds:?}"
            );
        }
        // The unknown-parent kind still exists and still means a refused write.
        assert_eq!(
            HierarchyDiagnosticKind::UnknownParent.as_str(),
            "unknown_parent"
        );
        assert_eq!(
            HierarchyDiagnosticKind::UnresolvedParent.as_str(),
            "unresolved_parent",
            "T022 step 1 fixes this spelling; a different one is a contract violation"
        );
    }

    #[test]
    fn a_rejected_proposal_yields_no_change_and_no_event() {
        let index = HierarchyIndex::build(&nodes(&[(1, "A", None), (2, "B", Some(1))]));
        let err = set_parent(&index, 1, 1).unwrap_err();
        let HierarchyError::Rejected(result) = err;
        assert!(result.blocking);
    }

    #[test]
    fn an_unknown_child_is_refused_by_set_change_and_clear() {
        // Decision on tix #1373, option 1. The child half of the edge is validated
        // symmetrically with the parent half: a service that emits an event for a
        // child it cannot see is the kind of thing a later direct caller relies on
        // by accident.
        let index = HierarchyIndex::build(&nodes(&[(1, "P", None), (2, "C", None)]));
        let missing = 99;

        // `validate_proposed` carries the finding, so a lint or direct caller sees
        // it too, not only the three mutation entry points.
        let result = validate_proposed(&index, missing, Some(1));
        assert!(result.blocking);
        assert_eq!(result.kinds(), vec![HierarchyDiagnosticKind::UnknownChild]);
        assert_eq!(result.errors[0].issue, missing);
        assert!(
            result.errors[0].message.contains("#99"),
            "the message must name the missing child: {}",
            result.errors[0].message
        );

        for (label, outcome) in [
            ("set_parent", set_parent(&index, missing, 1)),
            ("change_parent", change_parent(&index, missing, 1)),
            ("clear_parent", clear_parent(&index, missing)),
        ] {
            let err = outcome.expect_err(&format!("{label}(child={missing}) must be refused"));
            assert!(
                matches!(&err, HierarchyError::Rejected(r) if r.kinds() == [HierarchyDiagnosticKind::UnknownChild]),
                "{label} refused for the wrong reason: {err:?}"
            );
        }

        // The control, so the test cannot pass by the rule firing everywhere: a
        // known child is still accepted (set) and still a no-op (clear).
        assert!(set_parent(&index, 2, 1).is_ok());
        assert!(clear_parent(&index, 2).unwrap().event.is_none());
    }

    #[test]
    fn the_child_check_runs_before_the_parent_check() {
        // Both ends are missing. The child is named, because it is the end the
        // caller passed first and the one it can act on by re-resolving the child.
        let index = HierarchyIndex::build(&nodes(&[(1, "P", None)]));
        let result = validate_proposed(&index, 77, Some(88));
        assert_eq!(result.kinds(), vec![HierarchyDiagnosticKind::UnknownChild]);
    }

    #[test]
    fn an_unknown_child_is_not_laundered_into_a_clear_no_op() {
        // Contract §3.5: the no-op path is reachable only after validation. An
        // unknown child that trivially "has no parent" must not return the absent
        // state as if the request had been accepted.
        let index = HierarchyIndex::build(&nodes(&[(1, "A", None)]));
        assert!(clear_parent(&index, 42).is_err());
        assert!(
            clear_parent(&index, 1).is_ok(),
            "a known child with no parent is still a no-op"
        );
    }

    // -- T004 ------------------------------------------------------------

    #[test]
    fn a_parent_with_three_children_reports_counts_and_typed_progress() {
        let issues = nodes(&[
            (1, "Parent", None),
            (2, "A", Some(1)),
            (3, "B", Some(1)),
            (4, "C", Some(1)),
        ]);
        let mut issues = issues;
        issues[1].status = "done".to_string();
        let index = HierarchyIndex::build(&issues);
        let rollup = rollup(&index, 1, "done");
        assert_eq!(rollup.direct_children, 3);
        assert_eq!(rollup.completed_children, 1);
        assert_eq!(
            rollup.progress,
            Progress { done: 1, total: 3 },
            "progress must be the typed value, not a formatted string"
        );
        assert_eq!(rollup.completion_basis, CompletionBasis::DirectChildren);
    }

    #[test]
    fn an_issue_with_no_children_rolls_up_to_zero() {
        let index = HierarchyIndex::build(&nodes(&[(1, "Lonely", None)]));
        let rollup = rollup(&index, 1, "done");
        assert_eq!(rollup.direct_children, 0);
        assert_eq!(rollup.completed_children, 0);
        assert_eq!(rollup.progress, Progress { done: 0, total: 0 });
    }

    #[test]
    fn completion_is_resolved_through_the_supplied_column_not_a_literal() {
        // A board that calls its completion column "shipped".
        let issues = vec![
            Node::new(1, "Parent"),
            Node {
                parent: Some(1),
                ..Node::new(2, "A").with_status("shipped")
            },
            Node {
                parent: Some(1),
                ..Node::new(3, "B").with_status("done")
            },
        ];
        let index = HierarchyIndex::build(&issues);
        assert_eq!(
            index.children_of(1).child_count,
            2,
            "precondition: the parent must actually have two children — the first \
             version of this test never set a parent, so it was measuring zero \
             children and asserting a count of one"
        );
        assert_eq!(
            rollup(&index, 1, "shipped").completed_children,
            1,
            "with 'shipped' as the completion column, A counts and B does not"
        );
        assert_eq!(
            rollup(&index, 1, "done").completed_children,
            1,
            "and with 'done', B counts instead"
        );
        // Both columns find exactly one child, and it is a *different* one: the
        // figure is produced by the supplied column, not by a hardcoded "done".
        // `children_of` exposes the labels, so the difference is checkable.
        let membership = index.children_of(1);
        let complete_under_shipped = membership
            .children
            .iter()
            .find(|c| index.status_of(c.number) == Some("shipped"))
            .map(|c| c.number);
        let complete_under_done = membership
            .children
            .iter()
            .find(|c| index.status_of(c.number) == Some("done"))
            .map(|c| c.number);
        assert_eq!(complete_under_shipped, Some(2));
        assert_eq!(complete_under_done, Some(3));
        assert_ne!(complete_under_shipped, complete_under_done);
    }

    #[test]
    fn repeated_rollup_over_the_same_snapshot_returns_equal_values() {
        let issues = nodes(&[(1, "P", None), (2, "A", Some(1)), (3, "B", Some(1))]);
        let index = HierarchyIndex::build(&issues);
        assert_eq!(rollup(&index, 1, "done"), rollup(&index, 1, "done"));
    }

    // -- T005 ------------------------------------------------------------

    #[test]
    fn an_unresolved_parent_retains_the_recorded_reference_for_repair() {
        let issues = nodes(&[(1, "Child", Some(42))]);
        let index = HierarchyIndex::build(&issues);
        let unresolved = index.unresolved();
        assert_eq!(unresolved.len(), 1);
        assert_eq!(unresolved[0].child, 1);
        assert_eq!(
            unresolved[0].recorded_parent, 42,
            "the reference must survive so it can be repaired, not be forgotten"
        );
        assert!(
            unresolved[0].reason.contains("#42"),
            "the reason must name the missing parent: {}",
            unresolved[0].reason
        );
    }

    #[test]
    fn deletion_reports_affected_children_without_deleting_them() {
        let issues = nodes(&[
            (1, "Parent", None),
            (2, "A", Some(1)),
            (3, "B", Some(1)),
            (4, "Elsewhere", None),
        ]);
        let affected = affected_by_deletion(&issues, 1);
        assert_eq!(
            affected.iter().map(|c| c.number).collect::<Vec<_>>(),
            vec![2, 3]
        );
        // The set is untouched: this reports, it does not mutate.
        assert_eq!(issues.len(), 4);
        assert_eq!(issues[1].parent, Some(1));
        assert!(
            affected_by_deletion(&issues, 4).is_empty(),
            "an issue with no children affects nobody"
        );
    }

    #[test]
    fn the_whole_surface_runs_without_a_store_or_a_tempfile() {
        // T005 step 4 as an executable property: everything above ran on
        // in-memory `Node`s. This asserts the module exposes no filesystem entry
        // point by naming the only constructor and calling the full path.
        let issues = nodes(&[
            (1, "Root", None),
            (2, "A", Some(1)),
            (3, "B", Some(1)),
            (4, "Orphan", Some(77)),
        ]);
        let index = HierarchyIndex::build(&issues);
        assert_eq!(index.children_of(1).child_count, 2);
        assert_eq!(rollup(&index, 1, "done").direct_children, 2);
        assert_eq!(index.unresolved().len(), 1);
        assert!(!validate_hierarchy(&issues).is_empty());
        assert!(set_parent(&index, 3, 2).is_ok());
    }

    // -----------------------------------------------------------------------
    // WP03 — the create path's own entry point
    // -----------------------------------------------------------------------

    #[test]
    fn a_new_issues_parent_must_exist() {
        // `validate_new_parent` is the only rule a not-yet-created child can break,
        // and it is tested at its own level because the CLI cannot reach it: a
        // selector that does not resolve is refused by `Store::resolve_issue` first,
        // and a selector that does resolve names an issue that is necessarily in the
        // index. Asserted here so the function is not untested code waiting for a
        // caller that never arrives.
        let index = HierarchyIndex::build(&nodes(&[(1, "P", None)]));
        assert!(
            validate_new_parent(&index, 1).is_ok(),
            "an existing issue is a valid parent"
        );

        let err = validate_new_parent(&index, 404).expect_err("a missing issue is not");
        assert!(
            matches!(&err, HierarchyError::Rejected(r) if r.kinds() == [HierarchyDiagnosticKind::UnknownParent]),
            "refused for the wrong reason: {err:?}"
        );
        // The diagnostic has no child to name, and says so with the documented
        // marker rather than a number that could be a real issue.
        let HierarchyError::Rejected(r) = err;
        assert_eq!(r.errors[0].issue, NO_ISSUE_YET);
        assert!(
            r.errors[0].message.contains("404"),
            "the message must name the missing parent: {}",
            r.errors[0].message
        );
    }

    #[test]
    fn no_issue_yet_is_not_a_number_the_store_can_hand_out() {
        // The sentinel is only sound if it can never be a real issue number.
        // `Store::resolve_next_number` allocates with `checked_add(1)` and errors on
        // overflow, so `u32::MAX` is unreachable.
        //
        // `0` was the first choice and is **not** sound. It was unsound for a
        // different reason than "it looks like a default": the allocator *did*
        // hand it out, because `max()` over an empty issue set has no answer and
        // `0` was the fallback — so every fresh repository's first issue was `#0`,
        // making the sentinel a real number. `resolve_next_number` now starts at
        // `1` (tix #1376), which is what closes the hole; this constant is the
        // other half of the same fix.
        assert_eq!(NO_ISSUE_YET, u32::MAX);
        assert!(
            NO_ISSUE_YET.checked_add(1).is_none(),
            "the sentinel must be the one value the allocator cannot produce"
        );
    }

    // -----------------------------------------------------------------------
    // WP04 / T015 — the completion basis, pinned
    // -----------------------------------------------------------------------

    #[test]
    fn t015_the_completion_basis_is_direct_children_and_the_rollup_says_so() {
        // data-model.md §3.1 records the decision; this makes the artifact and the
        // code agree, and stops a later reader reinterpreting the figure.
        //
        // The rollup is 1/2 for a parent whose two direct children are `done` and
        // `todo` — **even though the `done` child has a `done` child of its own**.
        // A subtree-recursive basis would report 2/2 here, so the fixture is built
        // to distinguish the two: the expected value only holds for a
        // direct-children basis.
        let issues = vec![
            node(1, "Parent", "todo", None),
            node(2, "Done child", "done", Some(1)),
            node(3, "Todo child", "todo", Some(1)),
            node(4, "Grandchild of #2", "done", Some(2)),
        ];
        let index = HierarchyIndex::build(&issues);
        let r = rollup(&index, 1, "done");
        assert_eq!(r.completion_basis, CompletionBasis::DirectChildren);
        assert_eq!(r.direct_children, 2, "the direct children are counted");
        assert_eq!(
            r.completed_children, 1,
            "only #2 is in the completion column"
        );
        assert_eq!(r.progress.done, 1);
        assert_eq!(r.progress.total, 2);
        // The grandchild must not have leaked into either figure.
        assert_eq!(r.direct_children + r.progress.total, 4, "2 + 2, not 3");
    }

    #[test]
    fn t015_a_grandchild_completed_does_not_complete_its_grandparent() {
        // The other half of the same distinction, stated as its own case: a
        // grandparent whose only child is done, but whose grandchild is not.
        let issues = vec![
            node(1, "Grandparent", "todo", None),
            node(2, "Child", "done", Some(1)),
            node(3, "Grandchild", "todo", Some(2)),
        ];
        let index = HierarchyIndex::build(&issues);
        // Bound as `r`, not `rollup`: the binding shadows the function for the rest
        // of the body, and the first version of this test hit exactly that.
        let r = rollup(&index, 1, "done");
        assert_eq!(
            r.completed_children, 1,
            "the child counts, not the grandchild"
        );
        assert_eq!(r.progress.total, 1);
        // And the child, whose own grandchild is not done, is itself 0/1.
        let child_rollup = rollup(&index, 2, "done");
        assert_eq!(child_rollup.completed_children, 0);
        assert_eq!(child_rollup.progress.total, 1);
    }

    #[test]
    fn t015_direct_children_are_reported_separately_from_the_rollup() {
        // T015's note: "direct children must be reported separately from the
        // rollup figure". Two fields, so `children: 40  completed: 12/40` cannot be
        // misread as a single figure.
        let issues: Vec<Node> = (1..=6)
            .map(|n| {
                node(
                    n,
                    &format!("Child {n}"),
                    if n % 2 == 0 { "done" } else { "todo" },
                    Some(1),
                )
            })
            .collect();
        let index = HierarchyIndex::build(&issues);
        let r = rollup(&index, 1, "done");
        assert_eq!(r.direct_children, 6);
        assert_eq!(r.completed_children, 3);
        assert_eq!(r.progress.done, 3);
        assert_eq!(r.progress.total, 6);
    }

    // -----------------------------------------------------------------------
    // WP05 / T020 — the unresolved-parent contract, confirmed
    // -----------------------------------------------------------------------
    //
    // T020 is a *confirm* subtask: WP01 already provides both behaviours. These
    // tests exist so the confirmation is evidence rather than a reading of the
    // source, and so the two properties the subtask names that were **not**
    // previously covered are covered now.

    #[test]
    fn t020_dropping_a_parent_from_the_set_does_not_clear_the_childs_reference() {
        // The mechanical guard against a cascade. A child whose parent leaves the
        // snapshot keeps its recorded number — `unresolved()` exists to report it,
        // and a reference that vanished with its target could not be repaired.
        let before = vec![
            node(1, "Parent", "todo", None),
            node(2, "Child", "todo", Some(1)),
        ];
        let mut after = before.clone();
        after.retain(|n| n.number != 1);

        let index = HierarchyIndex::build(&after);
        assert_eq!(
            index.parent_of(2),
            Some(1),
            "the recorded reference must survive its target"
        );
        let unresolved = index.unresolved();
        assert_eq!(unresolved.len(), 1, "and be diagnosed");
        assert_eq!(unresolved[0].child, 2);
        assert_eq!(unresolved[0].recorded_parent, 1);
        // The child's own `parent` field is untouched too — nothing in this module
        // can reach the issue set to rewrite it, and the type carries no mutator.
        assert_eq!(after[0].parent, Some(1));
    }

    #[test]
    fn t020_repairing_a_child_resolves_it_with_no_cleanup_step() {
        // T020 step 4. Re-pointing the child is the *only* repair: there is no
        // separate "clear the unresolved state" call, because there is no stored
        // unresolved state to clear — it is derived on every read.
        let dangling = vec![node(2, "Child", "todo", Some(1))];
        let index = HierarchyIndex::build(&dangling);
        assert_eq!(index.unresolved().len(), 1, "starts unresolved");

        // The repair: a parent exists and the child points at it.
        let repaired = vec![
            node(1, "Parent", "todo", None),
            node(2, "Child", "todo", Some(1)),
        ];
        let index = HierarchyIndex::build(&repaired);
        assert!(
            index.unresolved().is_empty(),
            "the unresolved state disappears because it is derived, not stored"
        );
        assert_eq!(index.parent_of(2), Some(1), "and the parent now resolves");
        assert!(index.contains(1), "and the target is in the index");

        // Re-pointing at a *different* live parent also resolves it, with no
        // intermediate step.
        let repointed = vec![
            node(1, "Parent", "todo", None),
            node(2, "Child", "todo", Some(9)),
            node(9, "Other", "todo", None),
        ];
        let index = HierarchyIndex::build(&repointed);
        assert_eq!(
            index.unresolved(),
            [] as [crate::hierarchy::UnresolvedParentState; 0]
        );
        assert_eq!(index.parent_of(2), Some(9));
    }

    #[test]
    fn t020_unresolved_is_ordered_by_child_so_a_lint_run_is_deterministic() {
        // T022's determinism acceptance criterion rests on this: `unresolved()`
        // iterates a `BTreeMap`, so the order is by child number regardless of the
        // order issues were read in. Two different input orders must give the same
        // output.
        let forward = vec![
            node(1, "A", "todo", Some(99)),
            node(2, "B", "todo", Some(98)),
            node(3, "C", "todo", Some(97)),
        ];
        let mut reversed = forward.clone();
        reversed.reverse();
        let a = HierarchyIndex::build(&forward).unresolved();
        let b = HierarchyIndex::build(&reversed).unresolved();
        assert_eq!(a, b, "the report must not depend on the read order");
        assert_eq!(
            a.iter().map(|s| s.child).collect::<Vec<_>>(),
            vec![1, 2, 3],
            "and it is ordered by child number"
        );
    }

    #[test]
    fn t020_a_resolved_parent_is_never_reported_unresolved() {
        // The control for the three above. Without it, a `unresolved()` that
        // reported everything would pass `repaired`-style assertions written as
        // "is_empty" only by accident, and a `retain` that dropped nothing would
        // pass the first.
        let clean = vec![
            node(1, "Parent", "todo", None),
            node(2, "Child", "todo", Some(1)),
            node(3, "Grandchild", "todo", Some(2)),
        ];
        let index = HierarchyIndex::build(&clean);
        assert!(
            index.unresolved().is_empty(),
            "a clean hierarchy reports nothing: {:?}",
            index.unresolved()
        );
    }
}