tix-tracker 0.11.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
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
//! Typed relationship domain service.
//!
//! This module is the **single owner** of every relationship semantic in
//! `tix`: the closed relation vocabulary, stable relationship identity, the
//! canonical direction convention, adjacency, and all graph validation
//! (self-link, missing target, conflicting edge, cycle). The CLI, TUI, MCP,
//! `tix lint`, the move guard, and the sync adapters all call into here —
//! none of them re-derives direction handling, cycle detection, or blocked
//! state locally. That is what makes CLI/TUI/MCP parity structural rather
//! than a convention (charter: "share domain/application logic where
//! practical").
//!
//! # Canonical direction convention
//!
//! There is exactly one convention, and it is stated here rather than only in
//! a test:
//!
//! - `blocks` is authored from the **blocking** issue to the **blocked** issue
//!   and is the **only authoritative stored form** of a blocking relationship.
//! - `blocked_by` is the explicit inverse **input spelling** of that same
//!   edge. [`normalize`] rewrites it into the canonical `blocks` edge, so a
//!   `blocked_by` value is never persisted and a pair is never stored twice:
//!   `A --blocked_by--> B` and `B --blocks--> A` are the same edge.
//! - `duplicates` and `related` are authored source → target and never produce
//!   a mirrored edge. `related` is the only non-directional kind.
//!
//! A **reciprocal** blocking pair (`A blocks B` *and* `B blocks A`) is a
//! two-edge directed cycle and is therefore rejected by the cycle rule. There
//! is no accept-and-normalize path for it.
//!
//! # Closed vocabulary
//!
//! Exactly four kinds ship: `blocks`, `blocked_by`, `duplicates`, `related`
//! (decision `01M3BXC5P4MK0BYECA3K1B9Z82`). The set is **compiled in** — this
//! module adds no `tix.toml` relation-type configuration key, and an unknown
//! kind is a validation error, never a free-form string and never a coerced
//! default.
//!
//! # Blocked-state resolution predicate
//!
//! [`RelationshipGraph::blocked_state`] is the only place "is this blocker
//! still open?" is answered. An inbound `blocks` edge from blocker `X` to
//! issue `Y` counts **iff** `X` resolves to an existing issue **and** `X`'s
//! status is not the board's configured `done_column`. A dangling edge whose
//! blocker no longer exists is reported as `missing_target` by validation but
//! is **excluded** here, so invalid data can never permanently freeze an
//! issue. Completion is resolved from configuration, never by matching the
//! literal string `done`; workflow *category* semantics are out of scope
//! (source issue #183).
//!
//! # Breaking replacement
//!
//! The retired `links:` frontmatter key is a **validation result**
//! ([`DiagnosticKind::RetiredLinksKey`]), never a parse fallback. Nothing in
//! this module reads legacy link values as typed data (C-001).
//!
//! # Complexity
//!
//! [`RelationshipGraph::validate_snapshot`] is a single `O(V + E)` pass and
//! never returns `Err` — it yields a [`RelationshipValidationResult`] so
//! `tix lint` can call it directly. Cycle detection and blocked-state
//! derivation share one adjacency build, so a surface that shows both does not
//! pay twice (NFR-001). Traversal is iterative throughout: a 10,000-node chain
//! must not overflow the stack.
//!
//! # Scope of this module
//!
//! This is the domain layer only. Of the operations in
//! `contracts/relationship-service.md` §1, it owns the *computation* half:
//!
//! | Contract operation | Provided here | Supplied by |
//! |---|---|---|
//! | `validate_snapshot` | yes | — |
//! | `dependency_chain` | yes | — |
//! | `blocked_state` | yes | — |
//! | `list_relations` | yes, as `relationships_for` / `blocks` / `blocked_by` / `duplicates_of` / `related_to` | — |
//! | "are these the same relationship?" | yes, as `find_canonical` | — |
//! | `create_relation` | validation + lookup only: `validate_create`, `find_canonical`, `normalize` | write path: WP02 `Store`, WP03 CLI |
//! | `edit_relation` | validation only: `validate_edit` | write path: WP02 `Store`, WP03 CLI |
//! | `remove_relation` | lookup only: `find_relationship` | write path: WP02 `Store`, WP03 CLI |
//!
//! Nothing here reads or writes a file, so the write half cannot be added
//! without the storage seam. `validate_*` returns a verdict; persisting it is
//! the caller's job, and it must not write anything at all when the verdict is
//! blocking (contract §4).

use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// T001 — the closed vocabulary and the typed edge
// ---------------------------------------------------------------------------

/// The closed vocabulary of typed relations.
///
/// Exactly four kinds ship in this mission (decision
/// `01M3BXC5P4MK0BYECA3K1B9Z82`). The set is compiled in — there is no
/// configuration key — and an unknown kind is rejected rather than coerced.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RelationKind {
    /// The source issue blocks the target issue. The canonical stored form of
    /// a blocking relationship.
    Blocks,
    /// The source issue is blocked by the target issue. An **input spelling
    /// only**: it normalizes into the equivalent [`RelationKind::Blocks`] edge
    /// and is never persisted.
    BlockedBy,
    /// The source issue duplicates the target issue. No blocked-state effect.
    Duplicates,
    /// Explicit non-directional association. Stored once, never mirrored, and
    /// the only non-directional kind.
    Related,
}

impl RelationKind {
    /// Every kind in the closed vocabulary, in canonical spell order.
    pub const ALL: [RelationKind; 4] = [
        RelationKind::Blocks,
        RelationKind::BlockedBy,
        RelationKind::Duplicates,
        RelationKind::Related,
    ];

    /// The canonical lowercase spelling used in files and CLI output.
    pub fn as_str(self) -> &'static str {
        match self {
            RelationKind::Blocks => "blocks",
            RelationKind::BlockedBy => "blocked_by",
            RelationKind::Duplicates => "duplicates",
            RelationKind::Related => "related",
        }
    }

    /// Whether the kind has a direction. False only for [`RelationKind::Related`].
    pub fn is_directional(self) -> bool {
        !matches!(self, RelationKind::Related)
    }

    /// The kind that describes the same edge seen from the other endpoint.
    ///
    /// `Blocks` ↔ `BlockedBy`; `Duplicates` and `Related` have no inverse
    /// because neither mirrors.
    pub fn inverse(self) -> Option<Self> {
        match self {
            RelationKind::Blocks => Some(RelationKind::BlockedBy),
            RelationKind::BlockedBy => Some(RelationKind::Blocks),
            RelationKind::Duplicates | RelationKind::Related => None,
        }
    }

    /// The kind this one normalizes to for storage, plus whether the
    /// endpoints must be swapped to reach it.
    ///
    /// `blocked_by` is the only kind that swaps: `A blocked_by B` is stored as
    /// `B blocks A`.
    fn canonical(self) -> (Self, bool) {
        match self {
            RelationKind::BlockedBy => (RelationKind::Blocks, true),
            other => (other, false),
        }
    }
}

impl fmt::Display for RelationKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for RelationKind {
    type Err = Diagnostic;

    /// Parse a canonical kind spelling, rejecting anything outside the closed
    /// vocabulary with an [`DiagnosticKind::UnknownKind`] diagnostic. An
    /// unknown kind is never coerced to `related`.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "blocks" => Ok(RelationKind::Blocks),
            "blocked_by" => Ok(RelationKind::BlockedBy),
            "duplicates" => Ok(RelationKind::Duplicates),
            "related" => Ok(RelationKind::Related),
            other => Err(Diagnostic::unknown_kind(
                "kind",
                format!(
                    "unknown relation kind `{other}`; expected one of blocks, blocked_by, duplicates, related"
                ),
            )),
        }
    }
}

/// A stable relationship identifier (`rel_` + 26 Crockford base32 characters,
/// ULID-shaped: a 48-bit millisecond timestamp followed by 80 random bits).
///
/// The id is generated once at creation and survives retargeting, renaming,
/// and export/import, so it is persisted rather than regenerated.
pub type RelationshipId = String;

/// A single typed edge between two issues.
///
/// Field names and invariants come from `data-model.md` §2. The `from`/`to`
/// fields are issue numbers ([`crate::model::Issue::number`], never reused).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Relationship {
    /// Stable identifier; survives retarget, rename, export, and import.
    #[serde(default)]
    pub id: RelationshipId,
    /// The issue that declares the edge.
    pub from: u32,
    /// The issue the edge points at.
    pub to: u32,
    /// The relation kind. A persisted edge never carries
    /// [`RelationKind::BlockedBy`] — it is normalized to
    /// [`RelationKind::Blocks`] before storage.
    pub kind: RelationKind,
    /// Human-readable display name, e.g. `blocks #42 Fix flaky test`.
    /// Recomputed from the target title by [`Relationship::refresh_display`];
    /// omitted from the serialized form while empty.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub display: String,
}

impl Relationship {
    /// Build a relationship with a freshly generated stable id and the
    /// canonical display name for `target_title`.
    pub fn new(from: u32, to: u32, kind: RelationKind, target_title: &str) -> Self {
        let canonical = CanonicalEdge::new(from, to, kind);
        Self {
            id: generate_relationship_id(),
            from: canonical.from,
            to: canonical.to,
            kind: canonical.kind,
            display: display_name(canonical.kind, canonical.to, target_title),
        }
    }

    /// Rebuild [`Relationship::display`] from the current kind and the target
    /// issue's title, leaving the stable id untouched.
    pub fn refresh_display(&mut self, target_title: &str) {
        self.display = display_name(self.kind, self.to, target_title);
    }

    /// The canonical form of this edge: the direction convention applied, so a
    /// `blocked_by` edge comes back with swapped endpoints and kind `blocks`,
    /// and a `related` edge comes back in `(min, max)` order.
    pub fn canonical(&self) -> CanonicalEdge {
        CanonicalEdge::new(self.from, self.to, self.kind)
    }
}

/// Whether landing on an edge that already exists is an error, or the
/// idempotent no-op that `data-model.md` §2 requires of a re-applied edit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Duplicate {
    /// Re-asserting an edge that already exists is fine. This is the `create`
    /// path: running `tix link A B --type blocks` twice must not fail.
    Allowed,
    /// Landing on a triple another relationship already occupies is an error,
    /// because the edit would leave two stored edges for one relationship.
    /// This is the `edit` path.
    Rejected,
}

/// The human-readable display name for an edge, e.g. `blocks #42 Fix flaky test`.
pub fn display_name(kind: RelationKind, target: u32, target_title: &str) -> String {
    if target_title.trim().is_empty() {
        format!("{} #{target}", kind.as_str())
    } else {
        format!("{} #{target} {}", kind.as_str(), target_title.trim())
    }
}

// ---------------------------------------------------------------------------
// T002 — canonical direction convention and inverse normalization
// ---------------------------------------------------------------------------

/// An edge in canonical form: the direction convention already applied.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CanonicalEdge {
    /// The blocking side for a blocking edge; the source otherwise.
    pub from: u32,
    /// The blocked side for a blocking edge; the target otherwise.
    pub to: u32,
    /// Always [`RelationKind::Blocks`] for a blocking edge, never
    /// [`RelationKind::BlockedBy`].
    pub kind: RelationKind,
}

impl CanonicalEdge {
    /// Apply the direction convention to an authored edge.
    ///
    /// Two kinds need their endpoints rearranged, for different reasons:
    ///
    /// - [`RelationKind::BlockedBy`] **swaps**. It is the inverse spelling of
    ///   a blocking edge, so `A blocked_by B` is stored as `B blocks A`.
    /// - [`RelationKind::Related`] is **order-normalized** to `(min, max)`. It
    ///   is the only non-directional kind, so the endpoint order carries no
    ///   meaning; fixing it makes `1 related 2` and `2 related 1` the same
    ///   stored edge, which is what `data-model.md` §1 requires ("stored
    ///   once; no mirrored edge"). The visible consequence is that an edge
    ///   authored as `2 related 1` displays as `related #1 …`; the orientation
    ///   was arbitrary, so this is a canonical choice, not a loss.
    ///
    /// [`RelationKind::Duplicates`] is directional and is deliberately **not**
    /// reordered — "2 duplicates 1" is not the same claim as "1 duplicates 2".
    pub fn new(from: u32, to: u32, kind: RelationKind) -> Self {
        let (kind, swap) = kind.canonical();
        // Both rearrangements end in a swap; they differ only in *when* they
        // apply. `blocked_by` always swaps, `related` swaps only when that puts
        // the pair in (min, max) order.
        if swap || (!kind.is_directional() && from > to) {
            Self {
                from: to,
                to: from,
                kind,
            }
        } else {
            Self { from, to, kind }
        }
    }

    /// Whether both endpoints resolve to the same issue.
    pub fn is_self_link(self) -> bool {
        self.from == self.to
    }
}

/// Apply the canonical direction convention to an authored edge.
///
/// `A --blocked_by--> B` and `B --blocks--> A` both normalize to the same
/// canonical edge, which is why a pair can never be stored twice.
pub fn normalize(from: u32, to: u32, kind: RelationKind) -> CanonicalEdge {
    CanonicalEdge::new(from, to, kind)
}

/// Normalize a batch of authored edges into a deduplicated, deterministically
/// ordered canonical set.
///
/// This is the property that makes `(from, to, kind)` uniqueness testable: two
/// spellings of the same edge collapse to one entry, and the output is sorted
/// so repeated calls on the same input are byte-identical.
pub fn normalize_all<I>(authored: I) -> Vec<CanonicalEdge>
where
    I: IntoIterator<Item = (u32, u32, RelationKind)>,
{
    let mut seen: HashSet<CanonicalEdge> = HashSet::new();
    for (from, to, kind) in authored {
        seen.insert(CanonicalEdge::new(from, to, kind));
    }
    let mut edges: Vec<CanonicalEdge> = seen.into_iter().collect();
    edges.sort_unstable();
    edges
}

// ---------------------------------------------------------------------------
// T004 — diagnostics and the validation result
// ---------------------------------------------------------------------------

/// The closed set of relationship validation diagnostics.
///
/// The names are authoritative and come from
/// `contracts/relationship-service.md` §3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticKind {
    /// `from == to`; always rejected.
    SelfLink,
    /// A selector resolved to no issue.
    MissingTarget,
    /// A stored edge contradicts the canonical direction for the same pair.
    ConflictingEdge,
    /// An edge would close a directed cycle.
    Cycle,
    /// A relation kind outside the closed vocabulary.
    UnknownKind,
    /// An edit or remove named a relationship id that does not exist.
    UnknownRelation,
    /// Legacy `links:` frontmatter key is still present.
    RetiredLinksKey,
}

impl DiagnosticKind {
    /// The canonical snake_case name used in CLI, TUI, and MCP output.
    pub fn as_str(self) -> &'static str {
        match self {
            DiagnosticKind::SelfLink => "self_link",
            DiagnosticKind::MissingTarget => "missing_target",
            DiagnosticKind::ConflictingEdge => "conflicting_edge",
            DiagnosticKind::Cycle => "cycle",
            DiagnosticKind::UnknownKind => "unknown_kind",
            DiagnosticKind::UnknownRelation => "unknown_relation",
            DiagnosticKind::RetiredLinksKey => "retired_links_key",
        }
    }
}

impl fmt::Display for DiagnosticKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One field-aware relationship diagnostic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Diagnostic {
    /// Which rule failed.
    pub kind: DiagnosticKind,
    /// The offending field or selector, e.g. `to`, `kind`, or `links`.
    pub field: String,
    /// Human-readable explanation, safe to print in CLI output, the TUI, and
    /// lint.
    pub message: String,
    /// The issue this diagnostic is **about**, when there is exactly one.
    ///
    /// Added for WP06 T025. `tix lint` has to attribute a diagnostic to a *file*,
    /// and a file is found by issue number — so without this the only route is to
    /// read the number back out of `message`, and the message is prose whose shape
    /// is not a contract. It already is not one: `self_link` opens with `#1 while
    /// `missing_target` opens with `issue #1`, and `conflicting_edge` names two
    /// issues. A consumer that assumed either shape would work until the wording
    /// changed, and would then attribute findings to the wrong file.
    ///
    /// `None` where the diagnostic is genuinely not about one issue.
    ///
    /// Which is not the same as "not a kind that has a subject". An
    /// [`DiagnosticKind::UnknownKind`] naming a bare selector and an
    /// [`DiagnosticKind::UnknownRelation`] naming a relationship id are always
    /// `None` — but [`DiagnosticKind::ConflictingEdge`] and
    /// [`DiagnosticKind::Cycle`] are `Some` when they come from
    /// [`RelationshipGraph::validate_snapshot`] and `None` when they come from
    /// [`RelationshipGraph::validate_authored`], which builds them with
    /// [`Diagnostic::new`].
    ///
    /// That asymmetry is recorded rather than papered over, because the field
    /// exists to be a contract and a doc claiming more than the code does is worse
    /// than no doc. Only `validate_snapshot` reaches lint, so nothing observable
    /// depends on the untagged half today; if a caller starts reading `issue` on a
    /// write-path diagnostic, that is the moment to tag those three sites.
    pub issue: Option<u32>,
}

impl Diagnostic {
    /// Build a diagnostic of any kind.
    pub fn new(kind: DiagnosticKind, field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            kind,
            field: field.into(),
            message: message.into(),
            issue: None,
        }
    }

    /// A diagnostic that is about one specific issue — the form lint needs, since
    /// it has to name the file.
    pub fn about(
        issue: u32,
        kind: DiagnosticKind,
        field: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            field: field.into(),
            message: message.into(),
            issue: Some(issue),
        }
    }

    /// A [`DiagnosticKind::SelfLink`] for the given issue.
    pub fn self_link(issue: u32) -> Self {
        Self::about(
            issue,
            DiagnosticKind::SelfLink,
            "to",
            format!("#{issue} cannot block itself: a self-link is not a valid relationship"),
        )
    }

    /// A [`DiagnosticKind::MissingTarget`] for an unresolvable selector.
    pub fn missing_target(issue: u32, selector: impl fmt::Display) -> Self {
        Self::about(
            issue,
            DiagnosticKind::MissingTarget,
            "to",
            format!("issue #{issue} references `{selector}`, which resolves to no issue"),
        )
    }

    /// A [`DiagnosticKind::UnknownKind`] for a kind outside the vocabulary.
    pub fn unknown_kind(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self::new(DiagnosticKind::UnknownKind, field, message)
    }

    /// A [`DiagnosticKind::UnknownRelation`] for a relationship id with no match.
    pub fn unknown_relation(id: &str) -> Self {
        Self::new(
            DiagnosticKind::UnknownRelation,
            "id",
            format!("no relationship with id `{id}`"),
        )
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} ({}): {}",
            self.kind.as_str(),
            self.field,
            self.message
        )
    }
}

/// The per-field diagnostic set returned by every validation call.
///
/// It is a **value**, never an `Err`: `tix lint` needs a value even when
/// nothing is wrong, and a read-only sweep must not fail fast (FR-001, C-004).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct RelationshipValidationResult {
    /// Every diagnostic found, in a deterministic order.
    pub errors: Vec<Diagnostic>,
}

impl RelationshipValidationResult {
    /// A result carrying no diagnostics.
    pub fn clean() -> Self {
        Self::default()
    }

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

    /// Whether no rule failed.
    pub fn is_clean(&self) -> bool {
        self.errors.is_empty()
    }

    /// Whether a mutation must be rejected.
    ///
    /// Every diagnostic kind is blocking for a write: a partial or
    /// reinterpreted edge is worse than a refused one, and a legacy `links:`
    /// key must never be silently dropped by a rewrite (C-001, SC-005).
    pub fn blocking(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Whether any diagnostic of `kind` was reported.
    pub fn has(&self, kind: DiagnosticKind) -> bool {
        self.errors.iter().any(|d| d.kind == kind)
    }

    /// Fold `other` into this result, keeping the combined order deterministic.
    pub fn merge(&mut self, other: Self) {
        self.errors.extend(other.errors);
    }

    /// Sort diagnostics by `(kind, field, message)` so repeated sweeps over the
    /// same snapshot are byte-comparable across surfaces.
    pub fn sort_diagnostics(&mut self) {
        self.errors
            .sort_by(|a, b| (a.kind, &a.field, &a.message).cmp(&(b.kind, &b.field, &b.message)));
    }
}

// ---------------------------------------------------------------------------
// T003 — the in-memory graph
// ---------------------------------------------------------------------------

/// The minimal projection of an issue that the relationship service needs.
///
/// This is deliberately *not* [`crate::model::Issue`]: the issue model gains
/// its typed relationship field in a later work package, and keeping the
/// service on a narrow view means the graph stays filesystem-free and
/// testable with a plain in-memory list.
#[derive(Debug, Clone, Copy)]
pub struct IssueView<'a> {
    /// The stable issue number (`Issue::number`, never reused).
    pub number: u32,
    /// The issue title, used to build display names.
    pub title: &'a str,
    /// The board column the issue sits in, compared against `done_column`.
    pub status: &'a str,
    /// The issue's stored relationships, in authored file order.
    pub relationships: &'a [Relationship],
    /// Whether the source frontmatter still carries a legacy `links:` key.
    /// The key is reported as a validation result and never read as typed data
    /// (C-001); this flag is how the storage layer signals it.
    pub has_retired_links_key: bool,
    /// The issue's decomposition parent, as an issue number.
    ///
    /// Present on the relationship service's view so the **hierarchy** service
    /// ([`crate::hierarchy`]) reads the same in-memory projection rather than a
    /// parallel one built by each caller. Two projections of one issue type is how
    /// two services end up disagreeing about the same snapshot — the divergence
    /// `contracts/surface-parity.md` §3 exists to prevent.
    ///
    /// Not read by the relationship graph. A parent is a decomposition and a
    /// `blocks` edge is a scheduling dependency; they are separate fields and are
    /// never combined (C-007).
    pub parent: Option<u32>,
}

impl<'a> IssueView<'a> {
    /// Build an issue view without the retired-key flag.
    pub fn new(
        number: u32,
        title: &'a str,
        status: &'a str,
        relationships: &'a [Relationship],
    ) -> Self {
        Self {
            number,
            title,
            status,
            relationships,
            has_retired_links_key: false,
            parent: None,
        }
    }

    /// Build an issue view, flagging a legacy `links:` key.
    pub fn with_retired_links_key(mut self, flagged: bool) -> Self {
        self.has_retired_links_key = flagged;
        self
    }

    /// Build an issue view carrying a decomposition parent.
    pub fn with_parent(mut self, parent: Option<u32>) -> Self {
        self.parent = parent;
        self
    }
}

// ---------------------------------------------------------------------------
// The hierarchy service reads the same view (WP01's `HierarchyNode`).
// ---------------------------------------------------------------------------

impl crate::hierarchy::HierarchyNode for IssueView<'_> {
    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
    }
}

/// One node of a dependency chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChainNode {
    /// The issue number.
    pub number: u32,
    /// The issue title at read time.
    pub title: String,
}

impl ChainNode {
    /// Build a chain node.
    pub fn new(number: u32, title: impl Into<String>) -> Self {
        Self {
            number,
            title: title.into(),
        }
    }
}

/// The transitive blocker chain of an issue (`data-model.md` §3).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct DependencyChain {
    /// The issue the chain was requested for.
    pub root: u32,
    /// Ordered node sequences from the root upward toward its blockers.
    pub paths: Vec<Vec<ChainNode>>,
    /// Set when the traversal bound was reached, so display can say so rather
    /// than silently truncating.
    pub truncated: bool,
}

impl DependencyChain {
    /// The distinct issues in the chain, in first-seen order.
    pub fn nodes(&self) -> Vec<&ChainNode> {
        let mut seen = HashSet::new();
        self.paths
            .iter()
            .flatten()
            .filter(|n| seen.insert(n.number))
            .collect()
    }
}

/// The derived blocked condition surfaced by every surface (`data-model.md` §4).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct BlockedState {
    /// At least one open inbound `blocks` edge exists.
    pub is_blocked: bool,
    /// The open blockers, ordered by issue number.
    pub blockers: Vec<ChainNode>,
    /// The human-readable explanation reused verbatim by the move warning and
    /// by detail rendering.
    pub reason: String,
}

/// How many nodes a single chain traversal will visit before setting
/// [`DependencyChain::truncated`]. A defensive display guard, not a graph bound.
///
/// Public because a surface that reports truncation has to name the bound it
/// hit, and a literal copy of this number in a printer is a number that drifts
/// the moment this one changes (WP03's `tix chain` truncation note).
pub const MAX_CHAIN_NODES: usize = 1_000;

/// The in-memory relationship graph: one adjacency build, every derived read.
///
/// The struct is built once per read from an in-memory issue set — no
/// filesystem access — and answers `relationships_for`, `blocks`,
/// `blocked_by`, `duplicates_of`, `related_to`, `dependency_chain`,
/// `blocked_state`, and `validate_snapshot` from the same indices.
#[derive(Debug)]
pub struct RelationshipGraph<'a> {
    issues: HashMap<u32, IssueView<'a>>,
    issues_by_number: Vec<u32>,
    /// Stored relationships, sorted by `(kind, target, from)`; every accessor
    /// slices this order so output is byte-comparable across surfaces.
    edges: Vec<Relationship>,
    by_id: HashMap<RelationshipId, usize>,
    /// Indices into `edges` for every edge touching an issue, ascending.
    by_issue: HashMap<u32, Vec<usize>>,
    /// `blocks` adjacency only. `duplicates` and `related` never appear.
    blocks_out: HashMap<u32, Vec<u32>>,
    blocks_in: HashMap<u32, Vec<u32>>,
    done_column: String,
    /// How many times [`RelationshipGraph::validate_snapshot`] has run on this
    /// graph.
    ///
    /// Instrumentation, and the **only** honest witness for NFR-001's "one pass".
    /// A timing ratio detects a change in the scaling *exponent* — quadratic vs
    /// linear — so it cannot see a second pass, which doubles both measurements and
    /// leaves their ratio untouched. Adding a redundant `validate_cycles()` call to
    /// `validate_snapshot` kept the entire suite green until this counter existed.
    ///
    /// An atomic so the graph stays `Sync`; the cost is one relaxed increment per
    /// call, not per edge, so it does not affect the measurement it exists to
    /// support.
    validation_passes: std::sync::atomic::AtomicUsize,
}

impl Clone for RelationshipGraph<'_> {
    /// A copy starts its own count. Cloning a graph is building a *new* one, so
    /// inheriting the source's pass count would make the instrument lie.
    fn clone(&self) -> Self {
        Self {
            issues: self.issues.clone(),
            issues_by_number: self.issues_by_number.clone(),
            edges: self.edges.clone(),
            by_id: self.by_id.clone(),
            by_issue: self.by_issue.clone(),
            blocks_out: self.blocks_out.clone(),
            blocks_in: self.blocks_in.clone(),
            done_column: self.done_column.clone(),
            validation_passes: std::sync::atomic::AtomicUsize::new(0),
        }
    }
}

impl<'a> RelationshipGraph<'a> {
    /// How many validation passes this graph has run. See
    /// [`RelationshipGraph::validation_passes`] for why this exists.
    pub fn validation_passes(&self) -> usize {
        self.validation_passes
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Build the graph from an in-memory issue set.
    ///
    /// `done_column` is the board's configured completion column, used by the
    /// resolution predicate in [`RelationshipGraph::blocked_state`]. Pass the
    /// configured value (`BoardConfiguration::effective_done_column`), never a
    /// hard-coded `"done"`.
    ///
    /// An empty `done_column` is accepted and means *no column marks
    /// completion*, so nothing is treated as done. `Config` validation keeps
    /// `columns` non-empty in practice, but a caller that passes `""` must not
    /// silently get "an empty status counts as completed".
    pub fn new(issues: &[IssueView<'a>], done_column: &str) -> Self {
        let mut issues_by_number: Vec<u32> = issues.iter().map(|i| i.number).collect();
        issues_by_number.sort_unstable();

        let mut graph = Self {
            issues: issues.iter().map(|i| (i.number, *i)).collect(),
            issues_by_number,
            edges: Vec::new(),
            by_id: HashMap::new(),
            by_issue: HashMap::new(),
            blocks_out: HashMap::new(),
            blocks_in: HashMap::new(),
            done_column: done_column.to_string(),
            validation_passes: std::sync::atomic::AtomicUsize::new(0),
        };
        graph.rebuild_edges();
        graph
    }

    /// Re-derive the edge set and every index from the issue views.
    ///
    /// Stored edges are normalized on ingest, so a hand-edited file that
    /// persisted the `blocked_by` spelling still contributes the correct
    /// `blocks` adjacency instead of silently dropping out of blocked state.
    ///
    /// A relationship's own `from` is authoritative. It is deliberately *not*
    /// overwritten with the owning issue's number: an edge authored as
    /// `A blocked_by B` legitimately points at `A` from `B`'s side, so forcing
    /// the owner would silently rewrite a normalized edge into a self-link.
    fn rebuild_edges(&mut self) {
        let mut edges: Vec<Relationship> = Vec::new();
        for number in &self.issues_by_number {
            let view = self.issues[number];
            for rel in view.relationships {
                let mut stored = rel.clone();
                let canonical = stored.canonical();
                stored.from = canonical.from;
                stored.to = canonical.to;
                stored.kind = canonical.kind;
                // Refresh the display from the target's *current* title. The
                // persisted string is a cache of a title that may since have
                // been renamed, and every surface renders this field, so a
                // stale value would be user-visible (review R1). A dangling
                // edge keeps its persisted display, since there is no title to
                // rebuild it from.
                if let Some(target) = self.issues.get(&stored.to) {
                    stored.refresh_display(target.title);
                }
                edges.push(stored);
            }
        }

        // Deterministic order: (kind, target, from). Sorting here means every
        // index built below inherits it, so no accessor has to sort again.
        edges.sort_by(|a, b| (a.kind, a.to, a.from, &a.id).cmp(&(b.kind, b.to, b.from, &b.id)));

        self.by_id = edges
            .iter()
            .enumerate()
            .map(|(i, e)| (e.id.clone(), i))
            .collect();
        self.by_issue = HashMap::new();
        self.blocks_out = HashMap::new();
        self.blocks_in = HashMap::new();

        for (i, edge) in edges.iter().enumerate() {
            // Register each edge once per *distinct* endpoint. A self-link has
            // one endpoint, so pushing both would report it twice and make
            // `relationships_for(..).len()` disagree with `edge_count()`
            // (review R2).
            self.by_issue.entry(edge.from).or_default().push(i);
            if edge.to != edge.from {
                self.by_issue.entry(edge.to).or_default().push(i);
            }
            // A self-link is invalid data, reported by `validate_snapshot` as
            // `self_link`. It stays visible through `relationships_for` so the
            // user can find and fix it, but it is kept out of the graph
            // adjacency: it is not a real edge, and admitting it would make an
            // issue its own blocker (review R3).
            if edge.kind == RelationKind::Blocks && edge.from != edge.to {
                self.blocks_out.entry(edge.from).or_default().push(edge.to);
                self.blocks_in.entry(edge.to).or_default().push(edge.from);
            }
        }

        // Redundant rows are *kept* in `edges` so no stored relationship id
        // silently stops resolving, but the adjacency is a set and must not
        // repeat a neighbour. A hand-edited file can hold two spellings of one
        // association (normalization makes them the same canonical triple);
        // dropping a row here would destroy an id the user still holds, and
        // `validate_edit` on it would report a bare `unknown_relation`
        // indistinguishable from a typo (review round 3, finding A). The
        // redundancy is collapsed on the read side instead — see
        // `related_to` — where it costs the user nothing.
        for adjacency in [&mut self.blocks_out, &mut self.blocks_in] {
            for targets in adjacency.values_mut() {
                targets.sort_unstable();
                targets.dedup();
            }
        }

        self.edges = edges;
    }

    /// The configured completion column used by the resolution predicate.
    pub fn done_column(&self) -> &str {
        &self.done_column
    }

    /// How many issues are in the graph.
    pub fn issue_count(&self) -> usize {
        self.issues_by_number.len()
    }

    /// How many stored edges are in the graph.
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }

    /// The issue numbers, ascending.
    pub fn issue_numbers(&self) -> &[u32] {
        &self.issues_by_number
    }

    /// Whether `number` resolves to an issue in the graph.
    pub fn has_issue(&self, number: u32) -> bool {
        self.issues.contains_key(&number)
    }

    /// The stored relationship with this stable id, if any.
    pub fn find_relationship(&self, id: &str) -> Option<&Relationship> {
        self.by_id.get(id).map(|i| &self.edges[*i])
    }

    /// The stored relationship for this canonical `(from, to, kind)`, if any.
    ///
    /// **This is the service's answer to "are these the same relationship?"**
    /// A write path must use it rather than comparing endpoints itself, because
    /// the comparison is domain logic and getting it wrong silently breaks
    /// idempotency. `tix link 1 2 --type blocked_by` and `tix link 2 1
    /// --type blocks` name one edge; a caller comparing the *authored*
    /// endpoints would see two and append a second row.
    ///
    /// `from`, `to` and `kind` are the **authored** values. Canonicalization
    /// happens here, so the caller cannot get the direction convention wrong:
    ///
    /// - `blocked_by` is normalized to the equivalent `blocks` edge with the
    ///   endpoints swapped;
    /// - `related` is order-normalized, so either orientation finds the row.
    ///
    /// When redundant rows exist for one canonical triple — a hand-edited file
    /// can hold two spellings of one association — the lowest-id row is
    /// returned, so the answer is stable across builds.
    pub fn find_canonical(&self, from: u32, to: u32, kind: RelationKind) -> Option<&Relationship> {
        let canonical = CanonicalEdge::new(from, to, kind);
        // Scoped to the canonical source's edge list rather than the whole edge
        // set: the matching row always has `from == canonical.from`, so this is
        // a short list and stays cheap on the write path.
        self.by_issue
            .get(&canonical.from)?
            .iter()
            .map(|i| &self.edges[*i])
            .find(|edge| edge.canonical() == canonical)
    }

    /// Every stored relationship, in deterministic order.
    pub fn all_relationships(&self) -> &[Relationship] {
        &self.edges
    }

    /// Every relationship touching `number` from either endpoint, in
    /// deterministic `(kind, target)` order.
    ///
    /// An unknown issue yields an empty vector rather than an error; callers
    /// that need an `unknown_issue` signal check
    /// [`RelationshipGraph::has_issue`].
    pub fn relationships_for(&self, number: u32) -> Vec<&Relationship> {
        match self.by_issue.get(&number) {
            Some(indices) => indices.iter().map(|i| &self.edges[*i]).collect(),
            None => Vec::new(),
        }
    }

    /// Relationships authored by `number` with the given kind.
    pub fn relationships_of_kind(&self, number: u32, kind: RelationKind) -> Vec<&Relationship> {
        self.relationships_for(number)
            .into_iter()
            .filter(|r| r.kind == kind)
            .collect()
    }

    /// Issues `number` blocks, ascending.
    pub fn blocks(&self, number: u32) -> &[u32] {
        self.blocks_out
            .get(&number)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Issues blocking `number`, ascending.
    ///
    /// This is the raw inbound adjacency. It is **not** the open-blocker set —
    /// use [`RelationshipGraph::blocked_state`] for that, which applies the
    /// resolution predicate.
    pub fn blocked_by(&self, number: u32) -> &[u32] {
        self.blocks_in
            .get(&number)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Issues duplicated *by* `number`, ascending.
    ///
    /// `duplicates` is **directional** (`data-model.md` section 1), so this is
    /// deliberately one-directional: it reports the targets of the edges
    /// `number` declares and ignores edges that merely point *at* `number`. On
    /// a stored `2 duplicates 1` edge the answer is therefore empty — the claim
    /// is "2 duplicates 1", not "1 duplicates 2". Reading `r.to` over every
    /// edge touching the subject instead reports the subject itself (P4).
    pub fn duplicates_of(&self, number: u32) -> Vec<u32> {
        let mut targets: Vec<u32> = self
            .relationships_of_kind(number, RelationKind::Duplicates)
            .into_iter()
            .filter(|edge| edge.from == number)
            .map(|edge| edge.to)
            .collect();
        targets.sort_unstable();
        targets
    }

    /// Issues associated with `number` by a `related` edge, ascending.
    ///
    /// `related` is the one **non-directional** kind, so both endpoints are
    /// equivalent. `relationships_for` returns edges from both sides, so the
    /// other side of each edge is projected explicitly — reading `r.to`
    /// directly reports the subject itself for an edge authored from the far
    /// side (P3).
    ///
    /// Redundant rows collapse *here* rather than in the stored edge set: two
    /// spellings of one association are one relationship to the user, and
    /// discarding a row at build time would silently invalidate an id the user
    /// still holds (round 3, finding A).
    pub fn related_to(&self, number: u32) -> Vec<u32> {
        let mut others: Vec<u32> = self
            .relationships_of_kind(number, RelationKind::Related)
            .into_iter()
            .map(|edge| {
                if edge.from == number {
                    edge.to
                } else {
                    edge.from
                }
            })
            .collect();
        others.sort_unstable();
        others.dedup();
        others
    }

    // -----------------------------------------------------------------------
    // T005 — derived reads
    // -----------------------------------------------------------------------

    /// The open blockers of `number`, per the resolution predicate.
    ///
    /// An inbound `blocks` edge counts **iff** the blocker is a *different*
    /// existing issue and its status is not the configured `done_column`. A
    /// dangling edge is excluded here (validation reports it as
    /// `missing_target`) so invalid data cannot permanently freeze an issue.
    pub fn open_blockers(&self, number: u32) -> Vec<ChainNode> {
        self.blocked_by(number)
            .iter()
            .filter(|blocker| self.is_open_blocker(number, **blocker))
            .map(|blocker| self.chain_node(*blocker))
            .collect()
    }

    /// The single resolution predicate, and the whole of it.
    ///
    /// `contracts/relationship-service.md` §7 makes this function the sole
    /// owner of the rule, so every precondition is stated here rather than
    /// delegated to the adjacency build. Three things are not an open blocker:
    ///
    /// 1. a missing blocker — invalid data, diagnosed as `missing_target`;
    /// 2. a blocker in the board's configured `done_column` — it is finished;
    /// 3. the subject itself — an issue is never blocked by itself.
    ///
    /// On (3): `rebuild_edges` already keeps self-links out of the adjacency,
    /// so that branch is **unreachable today** and is covered by no passing
    /// test. It is retained deliberately rather than as a second live layer —
    /// a safety rule that states its own preconditions stays correct if the
    /// build step is ever changed, and the cost is one comparison. The test
    /// `the_blocked_adjacency_never_contains_the_subject` pins the invariant
    /// that makes it unreachable, so a regression there fails a test rather
    /// than silently leaning on this branch.
    fn is_open_blocker(&self, subject: u32, blocker: u32) -> bool {
        if blocker == subject {
            return false;
        }
        let Some(blocker) = self.issues.get(&blocker) else {
            return false;
        };
        // An unconfigured completion column must fail *closed*: with no
        // `done_column` no column means "finished", so nothing is completed
        // and every real blocker keeps blocking. Comparing the status against
        // an empty string instead would treat a blocker with an empty status
        // as done, which is the dangerous direction for a guard that gates a
        // confirmation prompt.
        self.done_column.is_empty() || blocker.status != self.done_column
    }

    /// The derived blocked state for `number`.
    ///
    /// `reason` is the text the move warning and the detail view both display,
    /// so the two surfaces cannot drift.
    pub fn blocked_state(&self, number: u32) -> BlockedState {
        let blockers = self.open_blockers(number);
        let is_blocked = !blockers.is_empty();
        BlockedState {
            is_blocked,
            reason: if is_blocked {
                blocked_reason(&blockers)
            } else {
                String::new()
            },
            blockers,
        }
    }

    /// The transitive dependency chain of `root`, walking **outbound** `blocks`
    /// edges: the issues this one blocks, and what they block in turn.
    ///
    /// Direction note: `data-model.md` §9 specifies the chain is derived "from
    /// outbound `blocks` edges", so this follows `blocks_out` and answers "what
    /// does this issue hold up?". The opposite question — "what blocks this
    /// issue?" — is what the move guard needs, and is answered by
    /// [`RelationshipGraph::open_blockers`] over the inbound adjacency.
    ///
    /// The traversal is iterative and marks visited nodes, so a hand-edited
    /// cyclic file terminates instead of hanging the TUI.
    pub fn dependency_chain(&self, root: u32) -> DependencyChain {
        let mut chain = DependencyChain {
            root,
            paths: Vec::new(),
            truncated: false,
        };
        if !self.has_issue(root) {
            return chain;
        }

        let mut visited_nodes = 1usize;
        let mut path = vec![self.chain_node(root)];
        self.walk_downstream(root, &mut path, &mut chain.paths, &mut visited_nodes);
        chain.truncated = visited_nodes >= MAX_CHAIN_NODES;
        chain
    }

    /// Iterative outbound walk, pushing one path per leaf of the closure.
    fn walk_downstream(
        &self,
        node: u32,
        path: &mut Vec<ChainNode>,
        paths: &mut Vec<Vec<ChainNode>>,
        visited_nodes: &mut usize,
    ) {
        let downstream = self.blocks(node);
        if downstream.is_empty() {
            return;
        }
        // Deduplicate: the same node reached through two paths must not fork
        // the walk twice.
        let mut unique: Vec<u32> = Vec::new();
        for target in downstream {
            if !unique.contains(target) {
                unique.push(*target);
            }
        }
        for target in unique {
            if *visited_nodes >= MAX_CHAIN_NODES {
                return;
            }
            *visited_nodes += 1;
            if path.iter().any(|n| n.number == target) {
                // Defensive only: write-time cycle rejection makes this
                // unreachable for a well-formed graph.
                continue;
            }
            path.push(self.chain_node(target));
            if self.blocks(target).is_empty() {
                paths.push(path.clone());
            } else {
                self.walk_downstream(target, path, paths, visited_nodes);
                path.pop();
            }
        }
    }

    /// A chain node for `number`, falling back to an empty title for an edge
    /// endpoint that no longer resolves.
    fn chain_node(&self, number: u32) -> ChainNode {
        match self.issues.get(&number) {
            Some(issue) => ChainNode::new(number, issue.title),
            None => ChainNode::new(number, String::new()),
        }
    }

    // -----------------------------------------------------------------------
    // T004 — validation
    // -----------------------------------------------------------------------

    /// Sweep every stored edge and every issue, reporting every problem.
    ///
    /// A single `O(V + E)` pass, **never** an `Err`: `tix lint` consumes the
    /// returned value. Cycle detection reuses the `blocks` adjacency built at
    /// construction, so it is not a second scan.
    pub fn validate_snapshot(&self) -> RelationshipValidationResult {
        let mut result = RelationshipValidationResult::clean();

        for number in &self.issues_by_number {
            let view = self.issues[number];
            // The wording names the **command** and the **flag**, not just the
            // kind vocabulary.
            //
            // An earlier version said "record the relationships as typed edges
            // (`blocks`, `blocked_by`, `duplicates`, or `related`)" — which reads
            // as though those four names were frontmatter *keys*. They are
            // `--type` values; the real field is `relationships:`, holding objects.
            // A user who obeyed that message literally would write `blocks: [2]`
            // at the top level, and then hit the worse bug underneath: the model
            // carries no unknown keys, so `tix lint` would certify the file and the
            // next unrelated `tix edit` would delete the key without a word.
            //
            // So the advice is the command that actually does it, and the
            // vocabulary is explicitly the argument's value. The README's
            // conversion section already said this; the diagnostic and the docs
            // disagreed, and the diagnostic is the one a user in the middle of a
            // problem will read.
            if view.has_retired_links_key {
                result.errors.push(Diagnostic::about(
                    *number,
                    DiagnosticKind::RetiredLinksKey,
                    "links",
                    format!(
                        "#{number} still carries the retired `links:` key, which the typed \
                         model no longer reads \u{2014} remove the key, then recreate each \
                         relationship with `tix link <from> <to> --type <kind>` (or the \
                         `link_issue` tool), where `<kind>` is one of `blocks`, \
                         `blocked_by`, `duplicates`, or `related`"
                    ),
                ));
            }
        }

        // Per-edge rules. Each edge is examined once so an implied second
        // report for the same problem cannot appear.
        let mut pair_kind: HashMap<(u32, u32), RelationKind> = HashMap::new();
        for edge in &self.edges {
            if edge.from == edge.to {
                result.errors.push(Diagnostic::self_link(edge.from));
                continue;
            }
            if !self.has_issue(edge.to) {
                result
                    .errors
                    .push(Diagnostic::missing_target(edge.from, edge.to));
                continue;
            }
            // One authoritative kind per ordered pair: two different kinds for
            // the same pair is a conflict, an identical repeat is idempotent.
            let key = (edge.from, edge.to);
            match pair_kind.get(&key) {
                Some(existing) if *existing != edge.kind => {
                    // Attributed to `from`: that is the issue whose relationship
                    // set carries the conflict, and therefore the file lint names.
                    result.errors.push(Diagnostic::about(
                        edge.from,
                        DiagnosticKind::ConflictingEdge,
                        "kind",
                        format!(
                            "#{from} → #{to} is already `{existing}`; refusing to store it as `{}` as well",
                            edge.kind.as_str(),
                            from = edge.from,
                            to = edge.to
                        ),
                    ));
                }
                Some(_) => {}
                None => {
                    pair_kind.insert(key, edge.kind);
                }
            }
        }

        result.merge(self.validate_cycles());
        result.sort_diagnostics();
        result
    }

    /// Validate a proposed relationship creation.
    ///
    /// Runs every per-edge rule plus the cycle check, so the caller gets one
    /// blocking verdict before touching any file (SC-005).
    pub fn validate_create(
        &self,
        from: u32,
        to: u32,
        kind: RelationKind,
    ) -> RelationshipValidationResult {
        self.validate_authored(from, to, kind, None, Duplicate::Allowed)
    }

    /// [`RelationshipGraph::validate_create`], with the ability to ignore one
    /// already-stored relationship and to say whether landing on an edge that
    /// already exists is an error.
    ///
    /// `exclude` is the id of the relationship being edited. An edge never
    /// conflicts with itself, so the edited record must not be counted while
    /// looking for a different kind on the same pair — but every *other*
    /// pre-existing edge on that pair still must. Filtering the finished result
    /// instead of excluding by id would also swallow a conflict that was
    /// already true of the stored data (review R4).
    fn validate_authored(
        &self,
        from: u32,
        to: u32,
        kind: RelationKind,
        exclude: Option<&str>,
        duplicate: Duplicate,
    ) -> RelationshipValidationResult {
        let mut result = RelationshipValidationResult::clean();
        let canonical = CanonicalEdge::new(from, to, kind);

        if !self.has_issue(from) {
            result.errors.push(Diagnostic::missing_target(to, from));
        }
        if canonical.is_self_link() {
            result.errors.push(Diagnostic::self_link(from));
        } else if !self.has_issue(to) {
            result.errors.push(Diagnostic::missing_target(from, to));
        }

        if let Some(existing) = self.relationships_for(from).into_iter().find(|r| {
            let c = r.canonical();
            c.from == canonical.from
                && c.to == canonical.to
                && c.kind != canonical.kind
                && exclude != Some(r.id.as_str())
        }) {
            result.errors.push(Diagnostic::new(
                DiagnosticKind::ConflictingEdge,
                "kind",
                format!(
                    "#{} → #{} is already `{}`; refusing to store it as `{}` as well",
                    canonical.from,
                    canonical.to,
                    existing.kind.as_str(),
                    canonical.kind.as_str()
                ),
            ));
        }

        if let Some(cycle) = self.cycle_if_added(canonical) {
            result.errors.push(cycle);
        }

        // Landing on a triple another relationship already occupies would give
        // two stored edges for one relationship, breaking the
        // `(from, to, kind)` uniqueness invariant (data-model §2). Only an edit
        // treats this as an error: a *create* that re-asserts an edge that
        // already exists is the idempotent no-op §2 requires, whereas an edit
        // would silently collapse two distinct relationship ids into one
        // (review P2).
        if duplicate == Duplicate::Rejected {
            if let Some(clash) = self
                .relationships_for(from)
                .into_iter()
                .find(|r| r.canonical() == canonical && exclude != Some(r.id.as_str()))
            {
                result.errors.push(Diagnostic::new(
                    DiagnosticKind::ConflictingEdge,
                    "kind",
                    format!(
                        "#{from} already has a `{}` relationship to #{} (`{}`); this edit would store a second one — drop the existing edge or pick a different kind",
                        canonical.kind.as_str(),
                        canonical.to,
                        clash.id
                    ),
                ));
            }
        }

        result.sort_diagnostics();
        result
    }

    /// Validate a proposed edit of an existing relationship.
    ///
    /// An edit naming its own current target and kind is the identity, not a
    /// duplicate — and nothing else is forgiven. The edit must still agree with
    /// the graph as it already stands, so `validate_edit` never returns a
    /// cleaner verdict than `validate_snapshot` for the same stored data.
    pub fn validate_edit(
        &self,
        id: &str,
        new_to: Option<u32>,
        new_kind: Option<RelationKind>,
    ) -> RelationshipValidationResult {
        let Some(existing) = self.find_relationship(id) else {
            let mut result = RelationshipValidationResult::clean();
            result.errors.push(Diagnostic::unknown_relation(id));
            return result;
        };

        let from = existing.from;
        let to = new_to.unwrap_or(existing.to);
        let kind = new_kind.unwrap_or(existing.kind);
        self.validate_authored(from, to, kind, Some(id), Duplicate::Rejected)
    }

    /// Detect every cycle in the `blocks` adjacency.
    ///
    /// Kahn's algorithm peels the acyclic part in `O(V + E)`; the residue is
    /// the set of nodes on, or downstream of, a cycle. One iterative
    /// three-colour DFS over that residue then names each distinct cycle, so
    /// the whole sweep stays `O(V + E)` rather than re-walking per node
    /// (NFR-001).
    fn validate_cycles(&self) -> RelationshipValidationResult {
        let mut result = RelationshipValidationResult::clean();
        for path in self.cycles() {
            // A cycle names every issue on it, so there is no single subject. The
            // **first** node stands in, because lint needs one file to hang the
            // finding on and the first node is the one whose relationship set a
            // reader has to edit to break the cycle. The message still names the
            // whole path, so the finding is not misleading about its scope.
            result.errors.push(Diagnostic::about(
                path[0],
                DiagnosticKind::Cycle,
                "to",
                format!("cycle: {}", render_cycle(&path)),
            ));
        }
        result
    }

    /// Every distinct cycle in the `blocks` adjacency, each reported once.
    ///
    /// Iterative throughout: a 10,000-node chain must not overflow the stack.
    fn cycles(&self) -> Vec<Vec<u32>> {
        // Counted **here**, at the traversal, rather than at
        // `validate_snapshot`'s entry. A count at the entry witnesses how many
        // times the operation was *called*; this witnesses how many times the
        // blocks adjacency was actually *walked*, which is what "one pass" means.
        // A redundant `let _ = self.validate_cycles();` inside `validate_snapshot`
        // leaves an entry count at 1 and doubles this one — and that redundant call
        // kept the entire suite green until this counter existed.
        self.validation_passes
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let residue = self.cyclic_residue();
        if residue.is_empty() {
            return Vec::new();
        }

        const WHITE: u8 = 0;
        const GREY: u8 = 1;
        const BLACK: u8 = 2;

        let mut color: HashMap<u32, u8> = HashMap::new();
        let mut cycles: Vec<Vec<u32>> = Vec::new();
        let mut reported: HashSet<Vec<u32>> = HashSet::new();
        let mut path: Vec<u32> = Vec::new();
        let mut position: HashMap<u32, usize> = HashMap::new();
        let mut work: Vec<(u32, usize)> = Vec::new();

        for start in &self.issues_by_number {
            let start = *start;
            if !residue.contains(&start) || color.get(&start) == Some(&BLACK) {
                continue;
            }
            color.insert(start, GREY);
            position.insert(start, path.len());
            path.push(start);
            work.push((start, 0));

            while let Some(top) = work.last_mut() {
                let (node, cursor) = (top.0, top.1);
                let downstream = self.blocks(node);
                if cursor < downstream.len() {
                    top.1 += 1;
                    let next = downstream[cursor];
                    if !residue.contains(&next) {
                        continue;
                    }
                    match color.get(&next).copied().unwrap_or(WHITE) {
                        GREY => {
                            // Back edge: the cycle is the grey span on the path.
                            if let Some(start_at) = position.get(&next) {
                                let cycle = path[*start_at..].to_vec();
                                if reported.insert(cycle_key(&cycle)) {
                                    cycles.push(cycle);
                                }
                            }
                        }
                        WHITE => {
                            color.insert(next, GREY);
                            position.insert(next, path.len());
                            path.push(next);
                            work.push((next, 0));
                        }
                        _ => {}
                    }
                } else {
                    color.insert(node, BLACK);
                    position.remove(&node);
                    path.pop();
                    work.pop();
                }
            }
        }
        cycles
    }

    /// The nodes Kahn's algorithm cannot free: those on, or downstream of, a
    /// directed cycle. Empty means the graph is acyclic.
    fn cyclic_residue(&self) -> HashSet<u32> {
        let mut indegree: HashMap<u32, usize> =
            self.issues_by_number.iter().map(|n| (*n, 0usize)).collect();
        for edge in &self.edges {
            if edge.kind != RelationKind::Blocks || edge.from == edge.to {
                continue;
            }
            if !self.has_issue(edge.from) || !self.has_issue(edge.to) {
                continue;
            }
            *indegree.entry(edge.to).or_default() += 1;
        }

        let mut queue: VecDeque<u32> = indegree
            .iter()
            .filter(|(_, degree)| **degree == 0)
            .map(|(node, _)| *node)
            .collect();
        while let Some(node) = queue.pop_front() {
            // Self-links never reach the adjacency (see `rebuild_edges`), and
            // the degree is only decremented while positive, so a node is
            // enqueued exactly once and the peel terminates.
            for next in self.blocks(node) {
                if let Some(degree) = indegree.get_mut(next) {
                    if *degree > 0 {
                        *degree -= 1;
                        if *degree == 0 {
                            queue.push_back(*next);
                        }
                    }
                }
            }
        }

        indegree
            .into_iter()
            .filter(|(_, degree)| *degree > 0)
            .map(|(node, _)| node)
            .collect()
    }

    /// The `cycle` diagnostic an added edge would produce, if any.
    ///
    /// `from -> to` closes a cycle exactly when `to` already reaches `from`.
    /// The walk is iterative, so a 10,000-node chain is safe.
    fn cycle_if_added(&self, edge: CanonicalEdge) -> Option<Diagnostic> {
        if edge.is_self_link() {
            return Some(Diagnostic::self_link(edge.from));
        }
        // Only `blocks` can close a cycle. The reachability search below walks the
        // `blocks` adjacency, so running it for `related` or `duplicates` asks a
        // question about an edge that is not in that graph at all -- and answers
        // it wrongly, because the search finds a `blocks` path between the two
        // endpoints and reports a cycle for an edge that closes none.
        //
        // `data-model.md` §1 gives `duplicates` "no blocked-state effect", and
        // `contracts/relationship-service.md` §3.3 scopes the rule to "a **new
        // edge** that would close a directed cycle". Neither `related` nor
        // `duplicates` participates in the dependency graph, so neither can close
        // one.
        //
        // The cost of getting this wrong is not only a spurious rejection: with
        // `2 blocks 0` stored, re-kinding that edge to `related` is *refused*,
        // and the only route to a `related` edge between those two issues became
        // the destructive path in `Store::edit_relation`.
        if edge.kind != RelationKind::Blocks {
            return None;
        }
        if !self.has_issue(edge.to) {
            return None;
        }
        let path = self.shortest_path(edge.to, edge.from)?;
        let mut full = Vec::with_capacity(path.len() + 1);
        full.push(edge.from);
        full.extend(path);
        Some(Diagnostic::new(
            DiagnosticKind::Cycle,
            "to",
            format!("cycle: {}", render_cycle(&full)),
        ))
    }

    /// An iterative breadth-first search from `start` to `goal`, returning the
    /// node sequence inclusive of both ends.
    fn shortest_path(&self, start: u32, goal: u32) -> Option<Vec<u32>> {
        if start == goal {
            return Some(vec![start]);
        }
        let mut previous: HashMap<u32, u32> = HashMap::new();
        let mut seen: HashSet<u32> = HashSet::new();
        let mut queue: std::collections::VecDeque<u32> = std::collections::VecDeque::new();
        seen.insert(start);
        queue.push_back(start);
        while let Some(node) = queue.pop_front() {
            for next in self.blocks(node) {
                if !seen.insert(*next) {
                    continue;
                }
                previous.insert(*next, node);
                if *next == goal {
                    let mut path = vec![goal];
                    let mut cursor = goal;
                    while let Some(step) = previous.get(&cursor) {
                        path.push(*step);
                        cursor = *step;
                    }
                    path.reverse();
                    return Some(path);
                }
                queue.push_back(*next);
            }
        }
        None
    }
}

/// The move-warning / detail-view text for a non-empty blocker set.
///
/// Derived from [`BlockedState::blockers`] so every surface shows the same
/// string (parity contract §3).
pub fn blocked_reason(blockers: &[ChainNode]) -> String {
    if blockers.len() == 1 {
        let node = &blockers[0];
        return format!("Blocked by #{} {}", node.number, node.title)
            .trim_end()
            .to_string();
    }
    let list = blockers
        .iter()
        .map(|n| format!("#{} {}", n.number, n.title).trim_end().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    format!("Blocked by {} issues: {list}", blockers.len())
}

fn render_cycle(path: &[u32]) -> String {
    let rendered = path
        .iter()
        .map(u32::to_string)
        .collect::<Vec<_>>()
        .join(" -> ");
    format!("{rendered} -> #{}", path[0])
}

fn cycle_key(path: &[u32]) -> Vec<u32> {
    // Canonical rotation so the same cycle is reported once regardless of
    // which node the walk happened to start from.
    let Some(min_position) = path
        .iter()
        .enumerate()
        .min_by_key(|(_, n)| **n)
        .map(|(i, _)| i)
    else {
        return path.to_vec();
    };
    let mut rotated = path[min_position..].to_vec();
    rotated.extend_from_slice(&path[..min_position]);
    rotated
}

// ---------------------------------------------------------------------------
// Stable identifier generation (T001)
// ---------------------------------------------------------------------------

/// Generate a stable relationship identifier.
///
/// The format is `rel_` followed by 26 Crockford base32 characters: a 48-bit
/// millisecond timestamp followed by 80 pseudo-random bits. It is ULID-shaped
/// so ids sort by creation time and stay stable across retarget, rename, and
/// export/import.
///
/// Randomness comes from the OS-seeded hasher state plus a process-local
/// counter, so the crate keeps **zero new dependencies** (C-001).
pub fn generate_relationship_id() -> RelationshipId {
    use std::hash::{BuildHasher, Hasher};
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .unwrap_or(0);
    let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
    hasher.write_u128(millis);
    hasher.write_u64(counter);
    let entropy = hasher.finish();
    // 80 bits: 64 from the hasher, 16 more from a second pass over the counter.
    let mut second = std::collections::hash_map::RandomState::new().build_hasher();
    second.write_u64(entropy);
    second.write_u64(counter.wrapping_mul(0x9E37_79B9_7F4A_7C15));
    let high = second.finish() & 0xFFFF;

    let value = (millis << 80u32) | (u128::from(entropy) << 16) | u128::from(high);
    // The Crockford encoder is shared with the issue-id generator (`crate::id`),
    // so the crate has one base32 implementation rather than two.
    format!("rel_{}", crate::id::crockford(value, 26))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- test fixtures -----------------------------------------------------

    /// An owned issue, so tests can build borrowed [`IssueView`]s from a
    /// stable backing allocation.
    #[derive(Clone)]
    struct Owned {
        number: u32,
        title: String,
        status: String,
        relationships: Vec<Relationship>,
        retired: bool,
    }

    impl Owned {
        fn new(number: u32, title: &str, status: &str) -> Self {
            Self {
                number,
                title: title.to_string(),
                status: status.to_string(),
                relationships: Vec::new(),
                retired: false,
            }
        }

        /// Consuming builder: this issue blocks `to`.
        fn blocking(mut self, to: u32, title: &str) -> Self {
            self.relationships.push(Relationship::new(
                self.number,
                to,
                RelationKind::Blocks,
                title,
            ));
            self
        }

        /// In-place builder, for loops that build many edges on one issue.
        fn push_block(&mut self, to: u32, title: &str) {
            self.relationships.push(Relationship::new(
                self.number,
                to,
                RelationKind::Blocks,
                title,
            ));
        }

        /// This issue is `related` to `to`.
        fn with_related(self, to: u32, title: &str) -> Self {
            let mut this = self;
            this.relationships.push(Relationship::new(
                this.number,
                to,
                RelationKind::Related,
                title,
            ));
            this
        }

        fn with_retired_links_key(mut self) -> Self {
            self.retired = true;
            self
        }

        fn view(&self) -> IssueView<'_> {
            IssueView::new(self.number, &self.title, &self.status, &self.relationships)
                .with_retired_links_key(self.retired)
        }
    }

    fn graph_of<'x>(owned: &'x [Owned], done_column: &str) -> RelationshipGraph<'x> {
        let views: Vec<IssueView<'x>> = owned.iter().map(Owned::view).collect();
        RelationshipGraph::new(&views, done_column)
    }

    // -- T001: vocabulary --------------------------------------------------

    #[test]
    fn relation_kind_has_exactly_four_variants_with_canonical_spellings() {
        let spellings: Vec<&str> = RelationKind::ALL.iter().map(|k| k.as_str()).collect();
        assert_eq!(spellings, ["blocks", "blocked_by", "duplicates", "related"]);
    }

    #[test]
    fn is_directional_is_false_only_for_related() {
        for kind in RelationKind::ALL {
            assert_eq!(
                kind.is_directional(),
                kind != RelationKind::Related,
                "{kind} directionality"
            );
        }
    }

    #[test]
    fn inverse_truth_table_matches_the_contract() {
        assert_eq!(
            RelationKind::Blocks.inverse(),
            Some(RelationKind::BlockedBy)
        );
        assert_eq!(
            RelationKind::BlockedBy.inverse(),
            Some(RelationKind::Blocks)
        );
        assert_eq!(RelationKind::Duplicates.inverse(), None);
        assert_eq!(RelationKind::Related.inverse(), None);
    }

    #[test]
    fn from_str_parses_every_canonical_spelling() {
        for kind in RelationKind::ALL {
            assert_eq!(kind.as_str().parse::<RelationKind>().unwrap(), kind);
        }
    }

    #[test]
    fn unknown_kind_is_rejected_and_never_coerced_to_related() {
        let err = "depends_on".parse::<RelationKind>().unwrap_err();
        assert_eq!(err.kind, DiagnosticKind::UnknownKind);
        assert!(err.message.contains("depends_on"));
        assert!(err.message.contains("blocks"));
    }

    #[test]
    fn relationship_serde_round_trip_is_stable() {
        let rel = Relationship::new(42, 51, RelationKind::Blocks, "Refactor store");
        let yaml = serde_yaml::to_string(&rel).unwrap();
        let parsed: Relationship = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(rel, parsed);
        assert_eq!(serde_yaml::to_string(&parsed).unwrap(), yaml);
    }

    #[test]
    fn relationship_parses_with_display_omitted() {
        let yaml = "id: rel_1\nfrom: 1\nto: 2\nkind: blocks\n";
        let rel: Relationship = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(rel.display, "");
        // An empty display is omitted rather than written as `display: ""`.
        assert!(!serde_yaml::to_string(&rel).unwrap().contains("display"));
    }

    #[test]
    fn display_name_combines_kind_number_and_title() {
        assert_eq!(
            display_name(RelationKind::Blocks, 42, "Fix flaky test"),
            "blocks #42 Fix flaky test"
        );
        assert_eq!(
            display_name(RelationKind::Related, 7, "   "),
            "related #7",
            "a blank title must not leave a trailing space"
        );
    }

    #[test]
    fn stable_ids_are_unique_across_a_batch_and_prefixed() {
        let mut seen = std::collections::HashSet::new();
        for _ in 0..2_000 {
            let id = generate_relationship_id();
            assert!(id.starts_with("rel_"), "unexpected id shape: {id}");
            assert_eq!(id.len(), "rel_".len() + 26, "unexpected id length: {id}");
            assert!(
                id["rel_".len()..]
                    .bytes()
                    .all(|b| crate::id::CROCKFORD.contains(&b)),
                "non-Crockford character in {id}"
            );
            assert!(seen.insert(id), "duplicate relationship id generated");
        }
    }

    // -- T002: direction convention ----------------------------------------

    #[test]
    fn both_spellings_of_a_blocking_pair_normalize_to_one_canonical_edge() {
        let forward = normalize(1, 2, RelationKind::Blocks);
        let inverse = normalize(1, 2, RelationKind::BlockedBy);
        assert_eq!(
            forward,
            CanonicalEdge {
                from: 1,
                to: 2,
                kind: RelationKind::Blocks
            }
        );
        assert_eq!(
            inverse,
            CanonicalEdge {
                from: 2,
                to: 1,
                kind: RelationKind::Blocks
            },
            "blocked_by must swap the endpoints into the canonical blocks form"
        );
        assert_eq!(
            forward.to, inverse.from,
            "the two spellings are the same edge"
        );
    }

    #[test]
    fn a_persisted_blocking_edge_never_carries_the_blocked_by_kind() {
        let stored = Relationship::new(1, 2, RelationKind::BlockedBy, "T");
        assert_eq!(stored.kind, RelationKind::Blocks);
        assert_eq!((stored.from, stored.to), (2, 1));
    }

    #[test]
    fn normalize_all_deduplicates_both_spellings_and_is_idempotent() {
        // "1 blocks 2" and "2 is blocked by 1" are one edge.
        let authored = [
            (1, 2, RelationKind::Blocks),
            (2, 1, RelationKind::BlockedBy),
            (3, 4, RelationKind::Related),
        ];
        let once = normalize_all(authored);
        assert_eq!(once.len(), 2, "the two spellings collapse to one edge");
        assert_eq!(
            once,
            normalize_all(authored),
            "normalization is deterministic"
        );
        assert_eq!(
            once,
            normalize_all(
                once.iter()
                    .map(|e| (e.from, e.to, e.kind))
                    .collect::<Vec<_>>()
            )
        );
    }

    #[test]
    fn related_and_duplicates_never_swap_endpoints() {
        for kind in [RelationKind::Related, RelationKind::Duplicates] {
            let edge = normalize(1, 2, kind);
            assert_eq!((edge.from, edge.to, edge.kind), (1, 2, kind));
        }
    }

    #[test]
    fn a_reciprocal_blocking_pair_is_rejected_as_a_cycle() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let b = Owned::new(2, "B", "todo").blocking(1, "A");
        let owned = vec![a, b];
        let graph = graph_of(&owned, "done");

        let result = graph.validate_snapshot();
        assert!(
            result.has(DiagnosticKind::Cycle),
            "expected a cycle diagnostic: {result:?}"
        );
        assert!(result.blocking(), "a reciprocal pair must be blocking");
    }

    #[test]
    fn a_conflicting_kind_for_the_same_pair_is_reported() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let mut a = a;
        a.relationships
            .push(Relationship::new(1, 2, RelationKind::Related, "B"));
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let result = graph_of(&owned, "done").validate_snapshot();
        assert!(
            result.has(DiagnosticKind::ConflictingEdge),
            "expected conflicting_edge: {result:?}"
        );
    }

    // -- T003: graph build and ordering ------------------------------------

    #[test]
    fn edges_are_returned_from_both_endpoints() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");
        assert_eq!(graph.relationships_for(1).len(), 1);
        assert_eq!(
            graph.relationships_for(2).len(),
            1,
            "the target sees the edge too"
        );
    }

    #[test]
    fn ordering_is_stable_across_repeated_builds() {
        let a = Owned::new(1, "A", "todo")
            .blocking(4, "D")
            .blocking(2, "B")
            .blocking(3, "C");
        let owned = vec![
            a,
            Owned::new(2, "B", "todo"),
            Owned::new(3, "C", "todo"),
            Owned::new(4, "D", "todo"),
        ];
        let first: Vec<(RelationKind, u32)> = graph_of(&owned, "done")
            .relationships_for(1)
            .iter()
            .map(|r| (r.kind, r.to))
            .collect();
        let second: Vec<(RelationKind, u32)> = graph_of(&owned, "done")
            .relationships_for(1)
            .iter()
            .map(|r| (r.kind, r.to))
            .collect();
        assert_eq!(first, second, "repeated builds must be byte-comparable");
        assert_eq!(
            first,
            vec![
                (RelationKind::Blocks, 2),
                (RelationKind::Blocks, 3),
                (RelationKind::Blocks, 4)
            ],
            "edges are ordered by (kind, target)"
        );
    }

    #[test]
    fn related_and_duplicates_never_enter_blocked_adjacency() {
        let mut a = Owned::new(1, "A", "todo");
        a.relationships
            .push(Relationship::new(1, 2, RelationKind::Related, "B"));
        a.relationships
            .push(Relationship::new(1, 3, RelationKind::Duplicates, "C"));
        let owned = vec![a, Owned::new(2, "B", "todo"), Owned::new(3, "C", "todo")];
        let graph = graph_of(&owned, "done");
        assert!(
            graph.blocks(1).is_empty(),
            "related/duplicates are not blockers"
        );
        assert_eq!(graph.blocked_by(2), [] as [u32; 0]);
        assert_eq!(graph.blocked_by(3), [] as [u32; 0]);
        assert_eq!(graph.duplicates_of(1), vec![3]);
        assert_eq!(graph.related_to(1), vec![2]);
    }

    #[test]
    fn an_issue_with_no_edges_yields_empty_results_not_an_error() {
        let owned = vec![Owned::new(1, "A", "todo")];
        let graph = graph_of(&owned, "done");
        assert_eq!(
            graph.relationships_for(1),
            [] as [&crate::relationships::Relationship; 0]
        );
        assert_eq!(graph.blocks(1), [] as [u32; 0]);
        assert_eq!(graph.blocked_by(1), [] as [u32; 0]);
        assert_eq!(
            graph.open_blockers(1),
            [] as [crate::relationships::ChainNode; 0]
        );
        assert!(graph.dependencies_are_empty_for_unknown_issue());
    }

    impl RelationshipGraph<'_> {
        /// Small readability helper for the empty-result test.
        fn dependencies_are_empty_for_unknown_issue(&self) -> bool {
            self.dependency_chain(9_999).paths.is_empty()
        }
    }

    // -- T004: validation --------------------------------------------------

    #[test]
    fn an_empty_snapshot_validates_clean() {
        let owned = vec![Owned::new(1, "A", "todo")];
        let result = graph_of(&owned, "done").validate_snapshot();
        assert!(result.is_clean(), "unexpected diagnostics: {result:?}");
        assert!(!result.blocking());
    }

    #[test]
    fn self_link_create_is_rejected() {
        let owned = vec![Owned::new(1, "A", "todo")];
        let result = graph_of(&owned, "done").validate_create(1, 1, RelationKind::Blocks);
        assert!(result.has(DiagnosticKind::SelfLink), "{result:?}");
        assert!(result.blocking());
    }

    #[test]
    fn missing_target_create_is_rejected() {
        let owned = vec![Owned::new(1, "A", "todo")];
        let result = graph_of(&owned, "done").validate_create(1, 99, RelationKind::Blocks);
        assert!(result.has(DiagnosticKind::MissingTarget), "{result:?}");
    }

    #[test]
    fn validate_create_accepts_both_spellings_of_the_same_pair() {
        let owned = vec![Owned::new(1, "A", "todo"), Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");
        assert!(graph.validate_create(1, 2, RelationKind::Blocks).is_clean());
        assert!(
            graph
                .validate_create(1, 2, RelationKind::BlockedBy)
                .is_clean(),
            "the inverse spelling is the same edge, not a conflict"
        );
    }

    #[test]
    fn editing_an_unknown_relationship_id_is_reported() {
        let owned = vec![Owned::new(1, "A", "todo")];
        let result = graph_of(&owned, "done").validate_edit("rel_missing", None, None);
        assert!(result.has(DiagnosticKind::UnknownRelation), "{result:?}");
    }

    #[test]
    fn a_retired_links_key_is_reported_and_never_read_as_typed_data() {
        let owned = vec![
            Owned::new(1, "A", "todo").with_retired_links_key(),
            Owned::new(2, "B", "todo"),
        ];
        let result = graph_of(&owned, "done").validate_snapshot();
        assert!(result.has(DiagnosticKind::RetiredLinksKey), "{result:?}");
        assert_eq!(
            result
                .errors
                .iter()
                .find(|d| d.kind == DiagnosticKind::RetiredLinksKey)
                .map(|d| d.field.as_str()),
            Some("links")
        );
    }

    #[test]
    fn a_snapshot_with_three_distinct_problems_reports_exactly_three_diagnostics() {
        let mut self_linked = Owned::new(1, "A", "todo");
        self_linked
            .relationships
            .push(Relationship::new(3, 3, RelationKind::Blocks, "C"));
        let mut dangling = Owned::new(2, "B", "todo");
        dangling
            .relationships
            .push(Relationship::new(2, 404, RelationKind::Blocks, "gone"));
        let owned = vec![
            self_linked,
            dangling,
            Owned::new(3, "C", "todo").with_retired_links_key(),
        ];
        let result = graph_of(&owned, "done").validate_snapshot();
        assert_eq!(
            result.errors.len(),
            3,
            "expected no duplicate or implied reports: {result:?}"
        );
    }

    // -- T005: cycles, chains, blocked state -------------------------------

    #[test]
    fn a_three_chain_returns_the_ordered_path() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let b = Owned::new(2, "B", "todo").blocking(3, "C");
        let owned = vec![a, b, Owned::new(3, "C", "todo")];
        let chain = graph_of(&owned, "done").dependency_chain(1);
        assert_eq!(chain.root, 1);
        assert_eq!(chain.paths.len(), 1);
        assert_eq!(
            chain.paths[0].iter().map(|n| n.number).collect::<Vec<_>>(),
            vec![1, 2, 3],
            "the chain walks upstream from the root toward its blockers"
        );
        assert!(!chain.truncated);
    }

    #[test]
    fn a_cycle_closing_edge_is_rejected() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let b = Owned::new(2, "B", "todo").blocking(3, "C");
        let owned = vec![a, b, Owned::new(3, "C", "todo")];
        let result = graph_of(&owned, "done").validate_create(3, 1, RelationKind::Blocks);
        assert!(result.has(DiagnosticKind::Cycle), "{result:?}");
        assert!(result.blocking());
    }

    #[test]
    fn blocked_state_is_true_only_for_an_open_inbound_blocks_edge() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");

        let state = graph.blocked_state(2);
        assert!(state.is_blocked);
        assert_eq!(
            state.blockers.iter().map(|n| n.number).collect::<Vec<_>>(),
            vec![1]
        );
        assert!(
            state.reason.contains("#1"),
            "the reason names the blocker: {}",
            state.reason
        );

        assert!(
            !graph.blocked_state(1).is_blocked,
            "the blocker is not itself blocked"
        );
    }

    #[test]
    fn moving_the_blocker_into_the_configured_done_column_clears_blocked_state() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let owned = vec![a, Owned::new(2, "B", "todo")];
        // A board whose completion column is "shipped", not "done".
        let graph = graph_of(&owned, "shipped");
        assert!(
            graph.blocked_state(2).is_blocked,
            "A is not in the shipped column yet"
        );

        let mut moved = owned.clone();
        moved[0].status = "shipped".to_string();
        let after = graph_of(&moved, "shipped");
        assert!(
            !after.blocked_state(2).is_blocked,
            "a blocker in the configured done_column stops blocking"
        );
    }

    #[test]
    fn a_blocker_in_a_non_completion_column_keeps_blocking() {
        let a = Owned::new(1, "A", "in review").blocking(2, "B");
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "shipped");
        assert!(graph.blocked_state(2).is_blocked);
        assert_ne!(graph.blocked_state(2).reason, "");
    }

    #[test]
    fn a_dangling_edge_is_diagnosed_but_does_not_freeze_the_issue() {
        // Edge 1 -> 404 where 404 does not exist: validation reports it, but the
        // blocked-state derivation must exclude it.
        let mut blocker = Owned::new(1, "A", "todo");
        blocker
            .relationships
            .push(Relationship::new(1, 404, RelationKind::Blocks, "gone"));
        let owned = vec![blocker, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");

        let result = graph.validate_snapshot();
        assert!(
            result.has(DiagnosticKind::MissingTarget),
            "the dangling edge is still reported: {result:?}"
        );
        assert!(
            !graph.blocked_state(2).is_blocked,
            "invalid data must not permanently freeze an issue"
        );
    }

    #[test]
    fn a_hand_edited_cyclic_file_terminates_instead_of_hanging() {
        // Write-time rejection makes this unreachable, but a hand-edited file
        // must not hang the TUI.
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let b = Owned::new(2, "B", "todo").blocking(1, "A");
        let owned = vec![a, b];
        let graph = graph_of(&owned, "done");

        assert!(graph.validate_snapshot().has(DiagnosticKind::Cycle));
        let chain = graph.dependency_chain(1);
        assert!(
            chain.paths.iter().all(|p| p.len() <= owned.len()),
            "the visited-set guard must bound every path"
        );
    }

    // -- NFR-001: linear single pass ---------------------------------------

    #[test]
    fn a_ten_thousand_edge_graph_validates_in_one_pass() {
        const ISSUES: u32 = 2_000;
        const PER_ISSUE: u32 = 6;
        // Forward-only edges (lower index blocks higher) keep the graph acyclic,
        // so a clean verdict is the correct expectation.
        let mut owned: Vec<Owned> = (0..ISSUES)
            .map(|n| Owned::new(n + 1, &format!("Issue {n}"), "todo"))
            .collect();
        for n in 0..ISSUES {
            for k in 1..=PER_ISSUE {
                let target = n + k;
                if target < ISSUES {
                    owned[n as usize].push_block(target + 1, "Target");
                }
            }
        }
        let graph = graph_of(&owned, "done");
        assert!(
            graph.edge_count() >= 10_000,
            "expected a 10,000-edge graph, built {}",
            graph.edge_count()
        );

        // Measure structure (pass completed, correct result) rather than a
        // wall-clock bound so the suite does not go flaky on shared CI hardware.
        let result = graph.validate_snapshot();
        assert!(
            result.is_clean(),
            "a well-formed graph validates clean: {result:?}"
        );
        assert_eq!(graph.issue_count(), ISSUES as usize);
        assert!(graph.blocked_state(2).is_blocked);
    }

    #[test]
    fn a_ten_thousand_node_chain_does_not_overflow_the_stack() {
        const DEPTH: u32 = 10_000;
        let mut owned: Vec<Owned> = (0..DEPTH)
            .map(|n| Owned::new(n + 1, &format!("Node {n}"), "todo"))
            .collect();
        for n in 0..DEPTH - 1 {
            owned[n as usize].push_block(n + 2, "Next");
        }
        let graph = graph_of(&owned, "done");
        // Iterative traversal: a recursive DFS would blow the stack here.
        assert!(graph.validate_snapshot().is_clean());
        let chain = graph.dependency_chain(1);
        assert!(chain.truncated, "the defensive node bound engages");
        assert!(
            graph
                .cycle_if_added(CanonicalEdge {
                    from: DEPTH,
                    to: 1,
                    kind: RelationKind::Blocks
                })
                .is_some()
        );
    }

    // -- review round 4 regression -----------------------------------------

    #[test]
    fn d1_inverse_spellings_find_the_same_row() {
        // Stored: 1 blocks 2.
        let owned = vec![
            Owned::new(1, "A", "todo").blocking(2, "B"),
            Owned::new(2, "B", "todo"),
        ];
        let graph = graph_of(&owned, "done");
        let forward = graph
            .find_canonical(1, 2, RelationKind::Blocks)
            .map(|r| r.id.clone());
        let inverse = graph
            .find_canonical(2, 1, RelationKind::BlockedBy)
            .map(|r| r.id.clone());
        assert!(forward.is_some(), "the stored edge must be found");
        assert_eq!(
            forward, inverse,
            "1 blocks 2 and 2 blocked_by 1 name one relationship"
        );
        assert_ne!(
            forward,
            graph
                .find_canonical(1, 2, RelationKind::BlockedBy)
                .map(|r| r.id.clone()),
            "1 blocked_by 2 is the inverse of the stored edge, so it must not match"
        );
    }

    #[test]
    fn d1_related_is_found_from_either_orientation() {
        let mut two = Owned::new(2, "B", "todo");
        two.relationships
            .push(Relationship::new(2, 1, RelationKind::Related, "A"));
        let owned = vec![Owned::new(1, "A", "todo"), two];
        let graph = graph_of(&owned, "done");
        let a = graph
            .find_canonical(1, 2, RelationKind::Related)
            .map(|r| r.id.clone());
        let b = graph
            .find_canonical(2, 1, RelationKind::Related)
            .map(|r| r.id.clone());
        assert!(a.is_some(), "related is order-normalized, so it is found");
        assert_eq!(a, b);
    }

    #[test]
    fn d1_a_self_link_or_unrelated_pair_does_not_match() {
        let owned = vec![
            Owned::new(1, "A", "todo").blocking(2, "B"),
            Owned::new(2, "B", "todo"),
            Owned::new(3, "C", "todo"),
        ];
        let graph = graph_of(&owned, "done");
        assert!(graph.find_canonical(1, 1, RelationKind::Blocks).is_none());
        assert!(graph.find_canonical(1, 3, RelationKind::Blocks).is_none());
        assert!(graph.find_canonical(3, 1, RelationKind::Blocks).is_none());
        assert!(graph.find_canonical(1, 2, RelationKind::Related).is_none());
        assert!(
            graph.find_canonical(1, 2, RelationKind::Blocks).is_some(),
            "the real edge still resolves"
        );
    }

    #[test]
    fn d1_redundant_rows_resolve_to_the_same_row_every_time() {
        let one = Owned::new(1, "A", "todo").with_related(2, "B");
        let two = Owned::new(2, "B", "todo").with_related(1, "A");
        let owned = vec![one, two];
        let first = graph_of(&owned, "done")
            .find_canonical(1, 2, RelationKind::Related)
            .map(|r| r.id.clone());
        let second = graph_of(&owned, "done")
            .find_canonical(1, 2, RelationKind::Related)
            .map(|r| r.id.clone());
        assert!(first.is_some());
        assert_eq!(first, second, "the answer must be stable, not arbitrary");
    }

    #[test]
    fn d1_an_unknown_pair_returns_none() {
        let owned = vec![Owned::new(1, "A", "todo")];
        let graph = graph_of(&owned, "done");
        assert!(graph.find_canonical(1, 404, RelationKind::Blocks).is_none());
        assert!(graph.find_canonical(404, 1, RelationKind::Blocks).is_none());
    }

    // -- review round 2 regressions ---------------------------------------

    #[test]
    fn p1_related_reads_as_one_association_across_orientations() {
        // `related` is the only non-directional kind, so both authorings are
        // the same association. Normalization collapses them to one canonical
        // triple and the read side shows one entry.
        let one = Owned::new(1, "A", "todo").with_related(2, "B");
        let two = Owned::new(2, "B", "todo").with_related(1, "A");
        let owned = vec![one, two];
        let graph = graph_of(&owned, "done");
        assert_eq!(graph.related_to(1), vec![2], "one association, not two");
        assert_eq!(graph.related_to(2), vec![1]);
        assert_eq!(
            normalize_all([(1, 2, RelationKind::Related), (2, 1, RelationKind::Related),]).len(),
            1,
            "both authorings normalize to one canonical edge"
        );
    }

    // -- review round 3 regressions ---------------------------------------

    #[test]
    fn a3_no_stored_relationship_id_silently_stops_resolving() {
        // Two stored spellings of one association. Both ids must keep working:
        // the file is human-editable, so the user still holds both, and a
        // dropped row would make one of them a bare `unknown_relation`.
        let one = Owned::new(1, "A", "todo").with_related(2, "B");
        let two = Owned::new(2, "B", "todo").with_related(1, "A");
        let owned = vec![one, two];
        let graph = graph_of(&owned, "done");
        let ids: Vec<String> = graph
            .all_relationships()
            .iter()
            .filter(|r| r.kind == RelationKind::Related)
            .map(|r| r.id.clone())
            .collect();
        assert_eq!(ids.len(), 2, "both stored rows are retained");
        for id in &ids {
            assert!(
                graph.find_relationship(id).is_some(),
                "stored id {id} must still resolve"
            );
            assert!(
                !graph
                    .validate_edit(id, None, None)
                    .has(DiagnosticKind::UnknownRelation),
                "editing by a stored id must not report it unknown"
            );
        }
    }

    #[test]
    fn a3_the_blocked_adjacency_does_not_repeat_a_neighbour() {
        // Redundant rows are kept as rows, but the adjacency is a set.
        let mut one = Owned::new(1, "A", "todo");
        for _ in 0..3 {
            one.push_block(2, "B");
        }
        let owned = vec![one, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");
        assert_eq!(graph.blocks(1), &[2], "no repeated neighbour");
        assert_eq!(graph.blocked_by(2), &[1], "no repeated blocker");
        assert_eq!(
            graph.blocked_state(2).blockers.len(),
            1,
            "one blocker is reported once, not once per stored row"
        );
    }

    #[test]
    fn c_an_unconfigured_done_column_fails_closed() {
        // With no `done_column`, no column means "finished", so a blocker with
        // an empty status must still block rather than read as completed.
        let mut one = Owned::new(1, "A", "");
        one.push_block(2, "B");
        let owned = vec![one, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "");
        assert!(
            graph.blocked_state(2).is_blocked,
            "an unconfigured completion column must not mark anything done"
        );
    }

    #[test]
    fn p1_duplicates_orientation_is_preserved() {
        // `duplicates` is directional: these are two distinct claims.
        assert_eq!(
            normalize_all([
                (1, 2, RelationKind::Duplicates),
                (2, 1, RelationKind::Duplicates),
            ])
            .len(),
            2
        );
    }

    #[test]
    fn p2_an_edit_cannot_land_on_a_triple_another_edge_occupies() {
        let mut a = Owned::new(1, "A", "todo");
        a.push_block(2, "B");
        a.relationships
            .push(Relationship::new(1, 2, RelationKind::Related, "B"));
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");
        let blocks_id = graph
            .relationships_for(1)
            .iter()
            .find(|r| r.kind == RelationKind::Blocks)
            .expect("a blocks edge")
            .id
            .clone();

        let res = graph.validate_edit(&blocks_id, None, Some(RelationKind::Related));
        assert!(
            res.has(DiagnosticKind::ConflictingEdge),
            "re-kinding onto an occupied triple must be rejected: {res:?}"
        );
        assert!(
            res.errors
                .iter()
                .any(|d| d.message.contains("would store a second one")),
            "the message must name the duplicate case: {res:?}"
        );
    }

    #[test]
    fn p2_creating_an_edge_that_already_exists_stays_idempotent() {
        // The create path must NOT reject a re-assertion: `tix link` run twice
        // has to be a no-op, not a failure (data-model §2).
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");
        assert!(
            graph.validate_create(1, 2, RelationKind::Blocks).is_clean(),
            "re-asserting an existing edge is the idempotent path"
        );
    }

    #[test]
    fn p3_p4_the_other_endpoint_is_returned_in_both_orientations() {
        // Edges authored from the far side, which is the case round 1 missed.
        let mut two = Owned::new(2, "B", "todo");
        two.relationships
            .push(Relationship::new(2, 1, RelationKind::Related, "A"));
        two.relationships
            .push(Relationship::new(2, 1, RelationKind::Duplicates, "A"));
        let owned = vec![Owned::new(1, "A", "todo"), two];
        let graph = graph_of(&owned, "done");

        // `related` is non-directional: both endpoints see each other.
        assert_eq!(graph.related_to(1), vec![2], "never the subject itself");
        assert_eq!(graph.related_to(2), vec![1]);
        // `duplicates` is directional, so a far-side edge contributes nothing.
        assert!(
            graph.duplicates_of(1).is_empty(),
            "a directional edge pointing at #1 does not mean #1 duplicates it: {:?}",
            graph.duplicates_of(1)
        );
        assert_eq!(graph.duplicates_of(2), vec![1]);
    }

    #[test]
    fn p5_the_blocked_adjacency_never_contains_the_subject() {
        // This is the invariant that makes the `blocker != subject` branch in
        // the resolution predicate unreachable. If a future change breaks it,
        // this fails rather than the branch silently carrying the load.
        let mut a = Owned::new(1, "A", "todo");
        a.relationships
            .push(Relationship::new(1, 1, RelationKind::Blocks, "A"));
        a.push_block(2, "B");
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");
        for number in [1, 2] {
            assert!(
                !graph.blocked_by(number).contains(&number),
                "issue #{number} must never appear in its own inbound blocks adjacency"
            );
        }
    }

    // -- review round 1 regressions ---------------------------------------

    #[test]
    fn r1_display_is_refreshed_when_the_target_is_renamed() {
        // The edge was created while #2 was titled "Old title".
        let a = Owned::new(1, "A", "todo").blocking(2, "Old title");
        let owned = vec![a, Owned::new(2, "New title", "todo")];
        let graph = graph_of(&owned, "done");
        assert_eq!(
            graph.relationships_for(1)[0].display,
            "blocks #2 New title",
            "a persisted display must not outlive the title it was built from"
        );
    }

    #[test]
    fn r1_a_dangling_edge_keeps_its_persisted_display() {
        // No target, so there is no title to rebuild the label from.
        let mut a = Owned::new(1, "A", "todo");
        a.relationships
            .push(Relationship::new(1, 404, RelationKind::Blocks, "gone"));
        let owned = vec![a];
        assert_eq!(
            graph_of(&owned, "done").relationships_for(1)[0].display,
            "blocks #404 gone"
        );
    }

    #[test]
    fn r2_a_self_link_is_reported_once_not_twice() {
        let mut a = Owned::new(1, "A", "todo");
        a.relationships
            .push(Relationship::new(1, 1, RelationKind::Blocks, "A"));
        let owned = vec![a];
        let graph = graph_of(&owned, "done");
        assert_eq!(graph.edge_count(), 1);
        assert_eq!(
            graph.relationships_for(1).len(),
            1,
            "a self-link has one endpoint, so it must be registered once"
        );
    }

    #[test]
    fn r3_an_issue_is_never_blocked_by_itself() {
        let mut a = Owned::new(1, "A", "todo");
        a.relationships
            .push(Relationship::new(1, 1, RelationKind::Blocks, "A"));
        let owned = vec![a];
        let graph = graph_of(&owned, "done");

        // Still visible as invalid data...
        assert!(graph.validate_snapshot().has(DiagnosticKind::SelfLink));
        // ...but never as a real edge, so it cannot make #1 its own blocker.
        assert_eq!(graph.blocks(1), [] as [u32; 0]);
        let state = graph.blocked_state(1);
        assert!(!state.is_blocked, "an issue must not block itself");
        assert_eq!(state.reason, "");
    }

    #[test]
    fn r4_validate_edit_does_not_hide_a_pre_existing_conflict() {
        // #1 -> #2 blocks, plus #1 -> #2 related: the data is already corrupt.
        let mut a = Owned::new(1, "A", "todo");
        a.push_block(2, "B");
        a.relationships
            .push(Relationship::new(1, 2, RelationKind::Related, "B"));
        let owned = vec![a, Owned::new(2, "B", "todo")];
        let graph = graph_of(&owned, "done");
        let blocks_id = graph
            .relationships_for(1)
            .iter()
            .find(|r| r.kind == RelationKind::Blocks)
            .expect("a blocks edge")
            .id
            .clone();

        assert!(
            graph
                .validate_snapshot()
                .has(DiagnosticKind::ConflictingEdge)
        );
        let edit = graph.validate_edit(&blocks_id, None, None);
        assert!(
            edit.has(DiagnosticKind::ConflictingEdge),
            "editing an unrelated field must not return a clean verdict on corrupt data: {edit:?}"
        );
    }

    #[test]
    fn r4_an_edit_does_not_conflict_with_itself() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let owned = vec![a, Owned::new(2, "B", "todo"), Owned::new(3, "C", "todo")];
        let graph = graph_of(&owned, "done");
        let id = graph.relationships_for(1)[0].id.clone();

        assert!(
            graph.validate_edit(&id, None, None).is_clean(),
            "an edge never conflicts with itself"
        );
        assert!(
            graph.validate_edit(&id, Some(3), None).is_clean(),
            "retargeting to an unrelated issue is not a conflict"
        );
    }

    // -- diagnostics --------------------------------------------------------

    #[test]
    fn every_contract_diagnostic_kind_exists_with_its_exact_name() {
        let names: Vec<&str> = [
            DiagnosticKind::SelfLink,
            DiagnosticKind::MissingTarget,
            DiagnosticKind::ConflictingEdge,
            DiagnosticKind::Cycle,
            DiagnosticKind::UnknownKind,
            DiagnosticKind::UnknownRelation,
            DiagnosticKind::RetiredLinksKey,
        ]
        .iter()
        .map(|k| k.as_str())
        .collect();
        assert_eq!(
            names,
            [
                "self_link",
                "missing_target",
                "conflicting_edge",
                "cycle",
                "unknown_kind",
                "unknown_relation",
                "retired_links_key"
            ]
        );
    }

    #[test]
    fn validate_snapshot_never_returns_an_err() {
        // The signature itself is the assertion: there is no Result to unwrap.
        let owned = vec![Owned::new(1, "A", "todo").with_retired_links_key()];
        let result: RelationshipValidationResult = graph_of(&owned, "done").validate_snapshot();
        assert!(result.blocking());
    }

    #[test]
    fn diagnostics_sort_deterministically() {
        let mut a = RelationshipValidationResult::with(Diagnostic::self_link(1));
        a.merge(RelationshipValidationResult::with(
            Diagnostic::unknown_relation("rel_x"),
        ));
        let mut b = a.clone();
        b.sort_diagnostics();
        a.sort_diagnostics();
        assert_eq!(a, b);
    }

    #[test]
    fn blocked_reason_is_shared_by_every_surface() {
        let single = vec![ChainNode::new(1, "A")];
        assert_eq!(blocked_reason(&single), "Blocked by #1 A");
        let many = vec![ChainNode::new(1, "A"), ChainNode::new(2, "B")];
        assert_eq!(blocked_reason(&many), "Blocked by 2 issues: #1 A, #2 B");
    }

    #[test]
    fn cycle_paths_are_reported_once_regardless_of_starting_node() {
        let a = Owned::new(1, "A", "todo").blocking(2, "B");
        let b = Owned::new(2, "B", "todo").blocking(3, "C");
        let c = Owned::new(3, "C", "todo").blocking(1, "A");
        let owned = vec![a, b, c];
        let result = graph_of(&owned, "done").validate_snapshot();
        let cycles: Vec<&Diagnostic> = result
            .errors
            .iter()
            .filter(|d| d.kind == DiagnosticKind::Cycle)
            .collect();
        assert_eq!(
            cycles.len(),
            1,
            "one distinct cycle, one diagnostic: {result:?}"
        );
    }

    #[test]
    fn hand_edited_blocked_by_persisted_edges_still_block() {
        // A hand-edited file that persisted the `blocked_by` spelling must not
        // silently drop out of blocked state. `from: 1, to: 2, blocked_by` is
        // "1 is blocked by 2", so it normalizes to 2 blocking 1.
        let mut owner = Owned::new(2, "B", "todo");
        owner.relationships.push(Relationship {
            id: "rel_hand".to_string(),
            from: 1,
            to: 2,
            kind: RelationKind::BlockedBy,
            display: String::new(),
        });
        let owned = vec![Owned::new(1, "A", "todo"), owner];
        let graph = graph_of(&owned, "done");
        assert!(
            graph.blocked_state(1).is_blocked,
            "the normalized adjacency must still carry the edge"
        );
        assert_eq!(graph.blocks(2), &[1], "stored in canonical blocks form");
    }
}