tix-tracker 0.10.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
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
//! `tix.toml` config schema, defaults, loading, saving and validation.
//!
//! Mirrors `contracts/tix-toml.md` and `data-model.md` §Config. The
//! [`Config`] type is the Serde surface for `tix.toml`; [`StateConfig`]
//! carries the legacy `[state].next_number` counter, which is tolerated on
//! load and never written back out (issue #52 — the issue number is
//! resolved at creation time by scanning the live issue set). Loading emits
//! a warning whenever a cleartext token is read from the file, and
//! [`Config::save`] never serializes tokens back to disk.

use std::collections::HashSet;
use std::hash::{BuildHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use indexmap::IndexMap;
use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};

use crate::board_store::BoardStore;
use crate::capacity::config::CapacityConfig;
use crate::cycle_store::{CycleStore, is_implicit_default};
use crate::error::{Result, TixError};
use crate::keybindings::{EffectiveBindings, KeyBindings};
use crate::records::RecordStore;
use crate::templates::registry::TemplateRegistry;

/// Remote tracker credentials/targets embedded in `tix.toml`.
///
/// `token` values are read-only: they are never serialized back out and are
/// never echoed in logs or errors. `base_url` may override the default
/// endpoint for self-hosted GitLab instances.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RemoteConfig {
    /// Optional cleartext token; prefer the `GITLAB_TOKEN`/`LINEAR_TOKEN`
    /// env vars. Never serialized back to disk.
    pub token: Option<String>,
    /// Optional base URL (e.g. self-hosted GitLab).
    pub base_url: Option<String>,
    /// GitLab project path (e.g. `acme/tix`) passed to `glab`.
    pub project: Option<String>,
    /// Linear team name passed to `linear-cli`.
    pub team: Option<String>,
}

/// The `[export]` section: per-target remote configuration.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ExportConfig {
    /// GitLab remote target.
    pub gitlab: Option<RemoteConfig>,
    /// Linear remote target.
    pub linear: Option<RemoteConfig>,
}

impl ExportConfig {
    /// Whether no remote target is configured, for `skip_serializing_if`.
    ///
    /// An empty `[export]` table is never written, so a legacy `tix.toml` gains
    /// no section on save (#1415).
    pub fn is_empty(&self) -> bool {
        self.gitlab.is_none() && self.linear.is_none()
    }
}

/// A named team (`[teams.<label>]` in `tix.toml`). The label lives as the
/// map key; `members` are free-form identities feeding the assignee/reviewer
/// pickers only (never constraining stored values, DM-01M311MRK517KRHR426QPNP6P7).
///
/// An absent/empty `[teams]` section means teams are disabled (today's
/// behavior), and an empty `[teams]` table is never written back out.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Team {
    /// Non-empty per team; unique within the team.
    pub members: Vec<String>,
}

/// A named cycle (`[cycles.<name>]` in `tix.toml`). The name lives as the
/// map key; `start_date`/`due_date` are optional `YYYY-MM-DD` strings with
/// `due_date >= start_date` when both are present.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PlanningCycle {
    /// Optional human description.
    pub description: Option<String>,
    /// Optional start date (`YYYY-MM-DD`).
    pub start_date: Option<String>,
    /// Optional due date (`YYYY-MM-DD`); must be `>= start_date`.
    pub due_date: Option<String>,
}

/// The rules every `tix.toml` registry key obeys.
///
/// `[projects.<project-id>]`, `[epics.<epic-id>]` and
/// `[initiatives.<initiative-id>]` are keyed by a **stable generated identifier**,
/// and the rules that keep such a key stable must not drift between the registries:
/// never blank, never padded, bounded in length, free of the TOML-structural
/// characters a table header cannot carry, and drawn from a shape that cannot hand
/// the same value out twice. Only the prefix and the words used in an error differ,
/// so those are the associated constants and everything else lives here once.
///
/// Hand-written ids are accepted when they pass [`StableId::new`], so a readable
/// handle such as `p-platform` and the generated shape coexist.
pub trait StableId: Sized {
    /// The generated prefix: `p-` for projects, `e-` for epics, `i-` for initiatives,
    /// `cs-` for cycle schedules.
    const PREFIX: &'static str;
    /// The human label used in messages, e.g. `project id`.
    const LABEL: &'static str;
    /// The indefinite article for [`Self::LABEL`]: `a` for a project, `an` for an epic.
    const ARTICLE: &'static str;
    /// The longest id a registry accepts. Long enough for a readable handle, short
    /// enough that a typo cannot turn into a paragraph in a table header.
    const MAX_LEN: usize = 128;

    /// Wrap an id that has already passed [`StableId::new`].
    fn from_validated(raw: String) -> Self;

    /// The id as written.
    fn as_str(&self) -> &str;

    /// Validate an explicit id.
    ///
    /// Ids are chosen by a caller (an `--project-id`/`--epic-id` flag) or generated.
    /// Either way the same rules apply, because the id ends up as a TOML table
    /// header: [`restore_section_order`] reads `[<section>.<id>]`, and an id
    /// containing `.` or a bracket would read as a nested table or a malformed
    /// document.
    fn new(raw: &str) -> Result<Self> {
        if raw.trim().is_empty() {
            return Err(TixError::Config(format!(
                "{} {} must not be blank",
                Self::ARTICLE,
                Self::LABEL
            )));
        }
        if raw.trim() != raw {
            return Err(TixError::Config(format!(
                "{} `{raw}` has leading or trailing whitespace",
                Self::LABEL
            )));
        }
        if raw.chars().count() > Self::MAX_LEN {
            return Err(TixError::Config(format!(
                "{} is {} characters; the limit is {}",
                Self::LABEL,
                raw.chars().count(),
                Self::MAX_LEN
            )));
        }
        if let Some(bad) = raw.chars().find(|c| is_structural_key_char(*c)) {
            return Err(TixError::Config(format!(
                "{} `{raw}` contains `{bad}`; use letters, digits, `-`, `_`, or `:`",
                Self::LABEL
            )));
        }
        Ok(Self::from_validated(raw.to_string()))
    }

    /// Allocate a new id: 64 mixed bits from the process hasher, [`Self::PREFIX`]-prefixed.
    ///
    /// No dependency and no counter stored in `tix.toml`, so there is no allocator
    /// whose state a deletion could reset. The never-reused guarantee rests on the
    /// **id shape** rather than on a persisted high-water mark: the value is drawn
    /// from 2^64 with the process id, a process-monotonic counter, and the wall
    /// clock mixed in, so two draws in one process differ with overwhelming
    /// probability (~2^-64 for a SipHash collision), and a re-draw after a deletion
    /// is as unlikely to repeat a previously handed-out value as any fresh draw is
    /// to collide. On top of that, [`Config::allocate_project_id`],
    /// [`Config::allocate_epic_id`] and [`Config::allocate_initiative_id`] redraw
    /// against the ids already stored, so a *stored* id is never handed out a second
    /// time — that half is exact, not probabilistic.
    #[must_use]
    fn generate() -> Self {
        static COUNTER: AtomicU64 = AtomicU64::new(0);

        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
        std::process::id().hash(&mut hasher);
        COUNTER.fetch_add(1, Ordering::Relaxed).hash(&mut hasher);
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |since| since.as_nanos())
            .hash(&mut hasher);
        let bits = hasher.finish();
        // The prefix plus 16 hex digits is a valid id by construction, so the private
        // wrapper is used directly rather than re-validating the format.
        Self::from_validated(format!("{}{bits:016x}", Self::PREFIX))
    }
}

/// A stable project identity (`[projects.<project-id>]` in `tix.toml`).
///
/// Never blank, never containing whitespace or a TOML-structural character, and
/// **never reused**. It is the registry key and every issue association points at
/// it, so a rename changes the display label only and leaves every association and
/// derived figure intact (C-002, SC-005). The type exists so "this string is an
/// id" is checked once, at the boundary, instead of at every lookup — the same
/// problem [`crate::views::registry::ViewId`] solves for views. The rules
/// themselves are shared with [`EpicId`] through [`StableId`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct ProjectId(String);

impl StableId for ProjectId {
    const PREFIX: &'static str = "p-";
    const LABEL: &'static str = "project id";
    const ARTICLE: &'static str = "a";

    fn from_validated(raw: String) -> Self {
        Self(raw)
    }

    fn as_str(&self) -> &str {
        &self.0
    }
}

impl ProjectId {
    /// The longest id the registry accepts (see [`StableId::MAX_LEN`]).
    pub const MAX_LEN: usize = <Self as StableId>::MAX_LEN;

    /// Validate an explicit id; see [`StableId::new`].
    pub fn new(raw: &str) -> Result<Self> {
        <Self as StableId>::new(raw)
    }

    /// Allocate a new id, `p-`-prefixed; see [`StableId::generate`] for the
    /// never-reused guarantee.
    #[must_use]
    pub fn generate() -> Self {
        <Self as StableId>::generate()
    }

    /// The id as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        <Self as StableId>::as_str(self)
    }
}

/// A stable epic identity (`[epics.<epic-id>]` in `tix.toml`).
///
/// The same rules as [`ProjectId`], shared through [`StableId`], with an `e-`
/// prefix: never blank, never padded, never carrying a TOML-structural character,
/// and **never reused**. It is the registry key and never a display name (C-003), so
/// a rename changes the label only and a deleted epic's id stays spent — a member
/// issue's dangling reference is then diagnosed and repaired, never silently
/// rebound to a new epic (C-005, NFR-002).
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct EpicId(String);

impl StableId for EpicId {
    const PREFIX: &'static str = "e-";
    const LABEL: &'static str = "epic id";
    const ARTICLE: &'static str = "an";

    fn from_validated(raw: String) -> Self {
        Self(raw)
    }

    fn as_str(&self) -> &str {
        &self.0
    }
}

impl EpicId {
    /// The longest id the registry accepts (see [`StableId::MAX_LEN`]).
    pub const MAX_LEN: usize = <Self as StableId>::MAX_LEN;

    /// Validate an explicit epic id; see [`StableId::new`].
    pub fn new(raw: &str) -> Result<Self> {
        <Self as StableId>::new(raw)
    }

    /// Allocate a new epic id, `e-`-prefixed; see [`StableId::generate`] for the
    /// never-reused guarantee.
    #[must_use]
    pub fn generate() -> Self {
        <Self as StableId>::generate()
    }

    /// The id as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        <Self as StableId>::as_str(self)
    }
}

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

impl TryFrom<String> for ProjectId {
    type Error = TixError;

    fn try_from(raw: String) -> Result<Self> {
        Self::new(&raw)
    }
}

impl From<ProjectId> for String {
    fn from(id: ProjectId) -> Self {
        id.0
    }
}

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

impl TryFrom<String> for EpicId {
    type Error = TixError;

    fn try_from(raw: String) -> Result<Self> {
        Self::new(&raw)
    }
}

impl From<EpicId> for String {
    fn from(id: EpicId) -> Self {
        id.0
    }
}

/// A stable initiative identity (`[initiatives.<initiative-id>]` in `tix.toml`).
///
/// The third [`StableId`], after [`ProjectId`] and [`EpicId`], with an `i-` prefix
/// and the same rules through the same trait: never blank, never padded, never
/// carrying a TOML-structural character, and **never reused**. It is the registry
/// key and an initiative's associations and derived values hang off it, so a rename
/// changes the display label only (C-002). A deleted initiative's id stays spent, so
/// nothing is silently rebound to a later record.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct InitiativeId(String);

impl StableId for InitiativeId {
    const PREFIX: &'static str = "i-";
    const LABEL: &'static str = "initiative id";
    const ARTICLE: &'static str = "an";

    fn from_validated(raw: String) -> Self {
        Self(raw)
    }

    fn as_str(&self) -> &str {
        &self.0
    }
}

impl InitiativeId {
    /// The longest id the registry accepts (see [`StableId::MAX_LEN`]).
    pub const MAX_LEN: usize = <Self as StableId>::MAX_LEN;

    /// Validate an explicit id; see [`StableId::new`].
    pub fn new(raw: &str) -> Result<Self> {
        <Self as StableId>::new(raw)
    }

    /// Allocate a new id, `i-`-prefixed; see [`StableId::generate`] for the
    /// never-reused guarantee.
    #[must_use]
    pub fn generate() -> Self {
        <Self as StableId>::generate()
    }

    /// The id as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        <Self as StableId>::as_str(self)
    }
}

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

impl TryFrom<String> for InitiativeId {
    type Error = TixError;

    fn try_from(raw: String) -> Result<Self> {
        Self::new(&raw)
    }
}

impl From<InitiativeId> for String {
    fn from(id: InitiativeId) -> Self {
        id.0
    }
}

/// Characters that cannot appear in a config table key: whitespace, and the
/// TOML/table syntax characters an id would otherwise be able to break out of.
fn is_structural_key_char(c: char) -> bool {
    c.is_whitespace()
        || matches!(c, '.' | '"' | '\'' | '[' | ']' | '#' | '=' | '\\')
        || c.is_control()
}

/// A project record (`[projects.<project-id>]` in `tix.toml`).
///
/// The stable [`ProjectId`] lives as the map key; `name` is a mutable display
/// label and is **not** the identity (C-002). The section is omitted entirely when
/// there are no projects, so a legacy `tix.toml` is byte-untouched (C-001).
///
/// `status` is project metadata and is deliberately a **free-form string**: it is
/// not the issue's board column, and workflow-*category* semantics belong to
/// source issue #183, so this section introduces no global category model (C-007).
/// `lead` is an identity **string** in the same shape the existing `assignee`
/// field tolerates (bare handle or `Name <email>`); it is not a user account, a
/// directory entry, or a team membership (C-007).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ProjectConfiguration {
    /// Display label. Required and unique within the registry, so interactive
    /// selection is unambiguous — but never the identity, which is the map key.
    pub name: String,
    /// Optional long-form context.
    pub description: Option<String>,
    /// Optional project status (free-form; not a board column, not a category).
    pub status: Option<String>,
    /// Optional lead identity string; no lookup, no user-identity concept.
    pub lead: Option<String>,
    /// Optional start date (`YYYY-MM-DD`).
    pub start_date: Option<String>,
    /// Optional due date (`YYYY-MM-DD`); must be `>= start_date`.
    pub due_date: Option<String>,
}

/// An epic record (`[epics.<epic-id>]` in `tix.toml`).
///
/// Mission `epics-work-items-01M3BYW4` (WP01). The stable [`EpicId`] lives as the
/// map key; `name` is a mutable display label and is **not** the identity (C-003),
/// so a rename leaves every member issue's reference and every derived figure
/// intact. The section is omitted entirely when there are no epics, so a legacy
/// `tix.toml` is byte-untouched (C-004).
///
/// `status` is epic metadata and is deliberately a **free-form string**, exactly
/// like [`ProjectConfiguration::status`]: it is not an issue's board column, and
/// workflow-*category* semantics belong to source issue #183, so no global category
/// model is introduced here. `owner` is an identity **string** in the same shape the
/// existing `assignee` field tolerates (bare handle or `Name <email>`); it is not a
/// user account, a directory entry, or a team membership (C-003).
///
/// `weight` is epic metadata used in epic rollups — a positive relative size. It is
/// **not** a size field on issues: `Issue.estimate` stays the free-form string it is,
/// and no typed size concept is introduced (research R3). A missing weight
/// contributes nothing to a weighted figure.
///
/// `parent` is an **epic id** and `projects` are **project ids**, while `milestone`
/// and `cycle` are the **name-keyed** references the existing registries use. That
/// asymmetry is deliberate — it matches how `Issue.cycles`/`Issue.milestones`
/// already work — and is recorded in `contracts/epic-registry.md` so it is not
/// "corrected" by accident.
///
/// References are validated for **shape** only. Whether a project, milestone, cycle,
/// or parent epic exists is resolved by the epic service and diagnosed by
/// `tix lint`; a dangling reference must stay loadable and repairable, exactly as a
/// view's project scope does (C-005).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct EpicConfiguration {
    /// Display label. Required and unique within the registry, so selection is
    /// unambiguous — but never the identity, which is the map key.
    pub name: String,
    /// Optional long-form context.
    pub description: Option<String>,
    /// Optional epic status (free-form; not a board column, not a category).
    pub status: Option<String>,
    /// Optional owner identity string; no lookup, no user-identity concept.
    pub owner: Option<String>,
    /// Optional start date (`YYYY-MM-DD`).
    pub start_date: Option<String>,
    /// Optional due date (`YYYY-MM-DD`); must be `>= start_date`.
    pub due_date: Option<String>,
    /// Optional positive relative size, used in epic rollups. Never an issue size.
    pub weight: Option<i64>,
    /// Optional parent epic **id**; shape is checked here, existence is not.
    pub parent: Option<String>,
    /// Project **ids** this epic concerns; shape is checked here, existence is not.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub projects: Vec<String>,
    /// Optional milestone **name** (the existing name-keyed reference).
    pub milestone: Option<String>,
    /// Optional cycle **name** (the existing name-keyed reference).
    pub cycle: Option<String>,
}

/// An initiative record (`[initiatives.<initiative-id>]` in `tix.toml`).
///
/// Mission `roadmap-initiatives-01M3C8SX` (WP01). The third stable-ID record, after
/// [`ProjectConfiguration`] and [`EpicConfiguration`]: the [`InitiativeId`] is the
/// map key and `name` is a mutable display label, so a rename leaves every
/// association and derived figure intact (C-002). The section is omitted entirely
/// when there are no initiatives, so a legacy `tix.toml` is byte-untouched (C-001).
///
/// # Preserved extensions — deliberately unlike its siblings
///
/// This record does **not** set `deny_unknown_fields`. The data model lists
/// `extensions` as preserved unknown data, so an unknown key is carried through
/// [`InitiativeExtensions`](crate::roadmap::registry::InitiativeExtensions) and
/// round-trips unchanged rather than making `tix.toml` unreadable. *The trade-off:
/// a typo'd key is preserved rather than refused here*, which is the cost of the
/// forward-compatibility guarantee — the siblings that deny unknown fields pay the
/// opposite cost.
///
/// # Metadata is not issue state
///
/// `status` and `priority` are initiative metadata, **not** an issue's board column
/// or priority: `status` is free-form exactly like [`ProjectConfiguration::status`],
/// and `priority` reuses [`crate::model::Priority`] because its serde shape is a
/// plain string that round-trips an unknown value verbatim (a known spelling is
/// normalized to lowercase, the same rule issues already use). `owner` is an
/// identity **string** with no lookup, never inferred from anything.
///
/// # Associations are explicit, shape-checked, and never resolved here
///
/// `projects` are project **ids**, `epics` are epic **ids**, and `milestones` are
/// the **names** the existing milestone registry uses — the same id/name asymmetry
/// the epic contract records. Every entry is validated for **shape** only: whether
/// its target exists is resolved by the service (WP03) and diagnosed by `tix lint`,
/// so a dangling reference stays loadable and repairable (C-005). A repeated entry
/// is idempotent (see [`crate::roadmap::registry`]).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct InitiativeConfiguration {
    /// Display label. Required and unique within the registry (case-folded), so
    /// selection is unambiguous — but never the identity, which is the map key.
    pub name: String,
    /// Optional strategic outcome.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub outcome: Option<String>,
    /// Optional owner identity **string**; no lookup, never inferred from anything.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner: Option<String>,
    /// Optional initiative status (free-form; not a board column, not a category).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// Optional initiative priority (see [`crate::model::Priority`]).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<crate::model::Priority>,
    /// Filterable labels; a repeat collapses to one on the write path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    /// Optional calendar target (`YYYY-MM-DD`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_date: Option<String>,
    /// Project **ids** this initiative concerns; shape checked here, existence not.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub projects: Vec<String>,
    /// Epic **ids** this initiative concerns; shape checked here, existence not.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub epics: Vec<String>,
    /// Milestone **names** this initiative concerns (the name-keyed reference).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub milestones: Vec<String>,
    /// Unknown metadata, preserved verbatim (see the type-level note).
    #[serde(flatten)]
    pub extensions: crate::roadmap::registry::InitiativeExtensions,
}

/// The `[planning]` section: the monotonic auto-cycle counter plus the
/// picker presets written by `tix init` (`contracts/tix-toml-planning.md`).
///
/// `cycle_number` is the next auto "Cycle N" number: it starts at 1, is bumped
/// on every unnamed cycle create, and never decrements (FR-003,
/// DM-01M311BJKMN3PPCR9GR9Y7ESD2). Contrary to the legacy `[state]` counter,
/// this section **is** serialized once mutated.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PlanningConfig {
    /// Monotonic next auto-cycle number; `>= 1`. Default `1`.
    pub cycle_number: u32,
    /// Optional picker preset naming a cycle.
    pub default_cycle: Option<String>,
    /// Optional picker preset naming a milestone.
    pub default_milestone: Option<String>,
    /// Optional picker preset naming a team.
    pub default_team: Option<String>,
}

impl PlanningConfig {
    /// Whether this section is untouched (all values at their defaults); such
    /// a section is not written to disk so legacy `tix.toml` files keep
    /// round-tripping byte-identically (NFR-003).
    pub fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

impl Default for PlanningConfig {
    fn default() -> Self {
        Self {
            cycle_number: 1,
            default_cycle: None,
            default_milestone: None,
            default_team: None,
        }
    }
}

/// A named new-issue template (`[templates.<name>]` in `tix.toml`).
///
/// The F4 New Issue mode (`tui-new-issue-mode`) lists these by name and, on
/// selection, pre-fills the form's rows from the fields the template sets.
/// Every field is optional, the section is absent by default, and an empty
/// `[templates]` table writes no key — so a project that never writes one pays
/// nothing and its `tix.toml` keeps round-tripping unchanged.
///
/// A template carries **content**, not identity: `number`, `created`,
/// `filename` and `History` are creation outputs rather than inputs, so they are
/// not fields here. `body` and `labels` are the two the mode's spec requires;
/// the rest exist because the form already has a row for them, and a template
/// that could not reach a row would only half-fill the form.
///
/// ```toml
/// [templates.bug]
/// labels = ["bug"]
/// body = "## Steps to reproduce\n\n"
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct IssueTemplate {
    /// Pre-filled title. Optional: a template that sets none leaves the title to
    /// the user, and the title stays required at submit either way.
    pub title: Option<String>,
    /// Pre-filled issue body (Markdown).
    pub body: Option<String>,
    /// Pre-filled labels.
    pub labels: Vec<String>,
    /// Pre-filled status column.
    pub status: Option<String>,
    /// Pre-filled priority.
    pub priority: Option<String>,
    /// Pre-filled assignee.
    pub assignee: Option<String>,
    /// Pre-filled estimate.
    pub estimate: Option<String>,
    /// Pre-filled reviewer.
    pub reviewer: Option<String>,
    /// Pre-filled cycles.
    pub cycles: Vec<String>,
    /// Pre-filled milestones.
    pub milestones: Vec<String>,
    /// Pre-filled start date (`YYYY-MM-DD`).
    pub start_date: Option<String>,
    /// Pre-filled due date (`YYYY-MM-DD`).
    pub due_date: Option<String>,
}

/// The `[state]` section — deprecated runtime bookkeeping that is still
/// tolerated on load for legacy `tix.toml` files but is never serialized.
///
/// The monotonic `next_number` counter this held was removed in issue #52:
/// issue numbers are now resolved at creation time by scanning the live
/// issue set, so [`Config::save`] writes no `[state]` section at all.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct StateConfig {
    /// Legacy monotonic issue-number counter (C-007). Read-only — kept so
    /// old `tix.toml` files with `[state].next_number` still load, and
    /// never persisted once saved again.
    #[serde(skip_serializing)]
    pub next_number: u32,
}

/// Card ordering for the rendered board (`[kanban.<name>].order_by`).
///
/// Applied per column in the board builders; the store's underlying order is
/// untouched so the CLI keeps its own sequencing (board-display FR-02).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum OrderBy {
    /// Most recently created issues first (the default).
    #[default]
    #[serde(rename = "created_at_desc")]
    CreatedAtDesc,
    /// Oldest issues first.
    #[serde(rename = "created_at_asc")]
    CreatedAtAsc,
    /// Preserve the underlying store (filename/created-date ascending) order.
    #[serde(rename = "none")]
    None,
}

impl OrderBy {
    /// The TOML spelling of this variant.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::CreatedAtDesc => "created_at_desc",
            Self::CreatedAtAsc => "created_at_asc",
            Self::None => "none",
        }
    }

    /// The next variant when cycling the setting in the TUI settings modal.
    pub fn next(self) -> Self {
        match self {
            Self::CreatedAtDesc => Self::CreatedAtAsc,
            Self::CreatedAtAsc => Self::None,
            Self::None => Self::CreatedAtDesc,
        }
    }
}

/// The fixed, global category vocabulary (C-002, contract §1).
///
/// One list, referenced by the config validator, the per-board mapping and the
/// service WP02 builds. A vocabulary spelled out in three places is a vocabulary
/// that disagrees with itself the first time one of them changes.
///
/// `TERMINAL` is the subset that ends the workflow. `canceled` is terminal but
/// **not** complete — `COMPLETE` is deliberately a separate one-element list rather
/// than `!TERMINAL.contains(...)`, because "terminal" and "complete" are different
/// claims and the contract makes conflating them an escalation.
pub const CATEGORY_KEYS: &[&str] = &[
    "backlog",
    "unstarted",
    "active",
    "blocked",
    "completed",
    "canceled",
];

/// Categories that end the workflow.
pub const TERMINAL_CATEGORIES: &[&str] = &["completed", "canceled"];

/// The **only** category that means done. `canceled` is terminal without being
/// complete, so this is a one-element list and not "everything terminal".
pub const COMPLETE_CATEGORY: &str = "completed";

/// The documented safe default for a column with no mapping (contract §4).
///
/// Non-terminal and non-complete, so an unmapped column is never silently counted
/// as done. A default that resolved to `completed` would change completion
/// meaning by accident, which the contract makes an escalation rather than a
/// convenience — [`validate_categories`] refuses one.
pub const SAFE_DEFAULT_CATEGORY: &str = "unstarted";

/// `[categories]`: the global vocabulary and the safe default.
///
/// Omitted from disk when untouched, so a legacy `tix.toml` round-trips
/// byte-identically and gains no new keys (NFR-003, C-007).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CategoryConfig {
    /// The vocabulary, in the project's preferred order for presentation.
    ///
    /// Defaults to [`CATEGORY_KEYS`]. A configured list is still validated
    /// against that vocabulary: a board maps columns *into* the global
    /// vocabulary, it does not define its own (C-002), so adding a key here is
    /// an `unknown_category` error rather than a new category.
    pub order: Vec<String>,
    /// The category an unmapped column resolves to. Must be in `order`, and must
    /// not be [`COMPLETE_CATEGORY`].
    pub default: String,
}

impl Default for CategoryConfig {
    fn default() -> Self {
        Self {
            order: CATEGORY_KEYS.iter().map(|k| (*k).to_string()).collect(),
            default: SAFE_DEFAULT_CATEGORY.to_string(),
        }
    }
}

impl CategoryConfig {
    /// Whether this section is untouched, and so is not written to disk.
    pub fn is_default(&self) -> bool {
        self == &Self::default()
    }

    /// Whether `key` is in the configured vocabulary.
    pub fn contains(&self, key: &str) -> bool {
        self.order.iter().any(|k| k == key)
    }
}

/// `[transitions]`: the workflow policy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TransitionConfig {
    /// Whether an issue in a terminal category refuses an ordinary move.
    ///
    /// Default `true`. "Ordinary" is load-bearing: the escape hatch WP02 settles is
    /// a *reasoned* transition out of a terminal category, not a silent
    /// reassignment, so this switch governs the second and not the first.
    pub terminal_locked: bool,
}

impl Default for TransitionConfig {
    fn default() -> Self {
        Self {
            terminal_locked: true,
        }
    }
}

impl TransitionConfig {
    pub fn is_default(&self) -> bool {
        self == &Self::default()
    }
}

/// The default number of lines a wrapped card title may occupy
/// ([`BoardConfiguration::title_lines`]). Named so the manual `Serialize` can
/// recognise it without repeating the literal (#1415).
const DEFAULT_TITLE_LINES: usize = 3;

/// The `done_column` a board gets when the key is absent.
///
/// `BoardConfiguration` is `#[serde(default)]` at the container level, so a
/// missing `done_column` is filled from [`BoardConfiguration::default`] — this
/// value, not an inference from `columns`. Named so the manual `Serialize` can
/// omit a `done_column` that already equals it (#1415).
const DEFAULT_DONE_COLUMN: &str = "done";

/// Health policy configuration (`[health]` in `tix.toml`; mission
/// `project-issue-health-status-01M3C8HX`, WP01 T002/T003).
///
/// One key, and that is the design: the only thing a repository *chooses* about
/// health is which **version** of the derivation policy it is on. The vocabulary
/// and the formula live in the build ([`crate::health::policy`]), because changing
/// either changes what every stored value means — an escalation with its own plan
/// (C-003), not a line in a config file. A version this build does not implement is
/// refused at load, by name.
///
/// Omitted when absent, so a repository that has never mentioned health gains no
/// section and a legacy `tix.toml` round-trips byte-identically.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HealthConfig {
    /// The policy version in force; absent means [`crate::health::HEALTH_POLICY_VERSION`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<String>,
}

impl HealthConfig {
    /// Whether nothing is configured: the state the schema omits on save.
    pub fn is_empty(&self) -> bool {
        self.policy.is_none()
    }

    /// The policy in force: the configured version, or the current one (T002).
    pub fn policy(&self) -> std::result::Result<crate::health::HealthPolicy, TixError> {
        match self.policy.as_deref() {
            Some(version) => crate::health::HealthPolicy::for_version(version)
                .map_err(|error| TixError::Config(error.render())),
            None => Ok(crate::health::HealthPolicy::v1()),
        }
    }
}

/// A named board configuration (`[kanban.<name>]` in `tix.toml`).
///
/// Carries the ordered column list plus per-configuration metadata: the done
/// column, columns hidden from the rendered board, and whether the computed
/// "Mismatched" pseudo-column is shown (C-002 / DM-01M2MH4D84NHG0JVWEPR6ZH4VR).
///
/// `Serialize` is written by hand (below) so every field equal to the value the
/// loader would supply is omitted on save, keeping a legacy `tix.toml`
/// byte-identical; `Deserialize` stays derived.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BoardConfiguration {
    /// Ordered, case-sensitive, non-empty, unique column names.
    pub columns: Vec<String>,
    /// The column treated as "done" (commit prompting). Defaults to `"done"`
    /// when that name is present in `columns`, else the last configured
    /// column (contracts/tix-toml.md field rules).
    ///
    /// **Its meaning is unchanged by this mission.** It remains the commit-prompt
    /// trigger and the legacy completion signal. WP02 reads the *category* for the
    /// completion decision; this field is not reinterpreted here, and a
    /// `category_map` does not change what it does.
    pub done_column: Option<String>,
    /// Column name → category key (contract §2). Omitted when empty, so a board
    /// without a mapping gains no key on save.
    ///
    /// A board with **no** map is a legacy board: its `done_column` resolves to
    /// `completed` and every other column to the safe default. See
    /// [`BoardConfiguration::category_for`], which is the single place that
    /// fallback lives — duplicating it in the service is how a board ends up with
    /// two notions of its own default.
    pub category_map: IndexMap<String, String>,
    /// Columns hidden from the rendered board. Must be a subset of `columns`;
    /// their cards stay in board state and remain reachable via filters/search.
    pub hidden_columns: Vec<String>,
    /// Whether the computed "Mismatched" pseudo-column is rendered. Default
    /// `false`. Never a configured column.
    pub show_mismatch: bool,
    /// Whether long card titles wrap onto multiple lines. Default `true`.
    pub wrap_titles: bool,
    /// The maximum number of lines a wrapped card may occupy. Default `3`;
    /// validated `>= 1` in [`validate_board`]. Ignored when `wrap_titles`
    /// is `false`.
    pub title_lines: usize,
    /// Sparse manual card order persisted by drag-and-drop reordering. When
    /// non-empty, this order takes precedence over [`order_by`] for the cards
    /// whose positions differ from the automatic ordering.
    pub card_order: Vec<String>,
    /// Ordering of cards within each rendered column. Default
    /// `created_at_desc` (most recently created first).
    pub order_by: OrderBy,
    /// Per-column work-in-progress limits and the estimate units they count in
    /// (mission `configurable-wip-limits-01M3C6WX`). Absent by default and omitted
    /// when empty, so a board that configures no limits gains no key on save — and
    /// **no status semantics change**: the columns, their categories and the done
    /// column mean exactly what they meant before (C-002).
    pub wip: crate::wip::WipConfig,
}

impl Default for BoardConfiguration {
    fn default() -> Self {
        Self {
            columns: ["todo", "in progress", "in review", "done"]
                .into_iter()
                .map(String::from)
                .collect(),
            done_column: Some(DEFAULT_DONE_COLUMN.to_string()),
            category_map: IndexMap::new(),
            hidden_columns: Vec::new(),
            show_mismatch: false,
            wrap_titles: true,
            title_lines: DEFAULT_TITLE_LINES,
            card_order: Vec::new(),
            order_by: OrderBy::default(),
            wip: crate::wip::WipConfig::default(),
        }
    }
}

impl Serialize for BoardConfiguration {
    /// Serialize a board as a `[kanban.<name>]` table, omitting **every field
    /// that already equals the value the loader would supply** (#1415).
    ///
    /// `columns` is always written — a board without columns is not a board —
    /// and `category_map`/`card_order` were already omitted when empty. The
    /// display and ordering keys (`hidden_columns`, `show_mismatch`,
    /// `wrap_titles`, `title_lines`, `order_by`) are omitted at their defaults,
    /// and `done_column` when it already equals [`DEFAULT_DONE_COLUMN`] — the
    /// value the loader fills in when the key is absent, since the container is
    /// `#[serde(default)]`. `Deserialize` stays derived, so the round trip is a
    /// fixed point: omitting a default writes nothing and loading a missing key
    /// restores the same value.
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let done = self
            .done_column
            .as_deref()
            .filter(|done| *done != DEFAULT_DONE_COLUMN);
        let order_by = (self.order_by != OrderBy::default()).then_some(self.order_by);

        let mut len = 1; // `columns` is always written.
        len += usize::from(done.is_some());
        len += usize::from(!self.category_map.is_empty());
        len += usize::from(!self.hidden_columns.is_empty());
        len += usize::from(self.show_mismatch);
        len += usize::from(!self.wrap_titles);
        len += usize::from(self.title_lines != DEFAULT_TITLE_LINES);
        len += usize::from(!self.card_order.is_empty());
        len += usize::from(order_by.is_some());
        len += usize::from(!self.wip.is_empty());

        let mut board = serializer.serialize_struct("BoardConfiguration", len)?;
        board.serialize_field("columns", &self.columns)?;
        if let Some(done) = done {
            board.serialize_field("done_column", done)?;
        }
        if !self.category_map.is_empty() {
            board.serialize_field("category_map", &self.category_map)?;
        }
        if !self.hidden_columns.is_empty() {
            board.serialize_field("hidden_columns", &self.hidden_columns)?;
        }
        if self.show_mismatch {
            board.serialize_field("show_mismatch", &self.show_mismatch)?;
        }
        if !self.wrap_titles {
            board.serialize_field("wrap_titles", &self.wrap_titles)?;
        }
        if self.title_lines != DEFAULT_TITLE_LINES {
            board.serialize_field("title_lines", &self.title_lines)?;
        }
        if !self.card_order.is_empty() {
            board.serialize_field("card_order", &self.card_order)?;
        }
        if let Some(order_by) = order_by {
            board.serialize_field("order_by", &order_by)?;
        }
        if !self.wip.is_empty() {
            board.serialize_field("wip", &self.wip)?;
        }
        board.end()
    }
}

/// The board a **new repository** starts with (`tix init`), rather than the bare
/// [`BoardConfiguration::default`] a config-less or partial file falls back to.
///
/// It carries the two columns the triage inbox needs: `triage` (where unreviewed work
/// lands — `[triage].entry_status`) and `wontfix` (where a decline goes; it has to
/// exist, because `declined_status` must resolve to the `canceled` category).
///
/// **Only those two are mapped**, and that is deliberate. The map is what makes a
/// board `explicit_policy`, and an explicit policy brings *adjacency*: a category may
/// move to itself or forward through the declared order, never backwards. Mapping the
/// working columns would have to call them `unstarted` or `active`, and then
/// `in progress -> todo` — a move people make every day when a review finds a problem
/// — would be refused outright, with no `--reason` to override it. Leaving them
/// unmapped resolves them all to the same safe default, so movement among them stays
/// free while `done`/`wontfix` are terminal, which is the discipline a new repository
/// can *opt into* later (`tix lint` names the unmapped columns and how to map them).
pub fn starter_board() -> BoardConfiguration {
    BoardConfiguration {
        columns: [
            "triage",
            "todo",
            "in progress",
            "in review",
            "done",
            "wontfix",
        ]
        .into_iter()
        .map(String::from)
        .collect(),
        category_map: IndexMap::from([
            ("done".to_string(), "completed".to_string()),
            ("wontfix".to_string(), "canceled".to_string()),
        ]),
        ..BoardConfiguration::default()
    }
}

impl BoardConfiguration {
    /// The category `column` resolves to, given the global configuration.
    ///
    /// The single place the fallback lives, and the seam WP02's service builds
    /// on. Three cases, in order:
    ///
    /// 1. An explicit `category_map` entry wins.
    /// 2. Otherwise, on a board with **no** map at all, `done_column` is
    ///    `completed` and every other column is the safe default.
    /// 3. Otherwise (a map exists but omits this column), the safe default.
    ///
    /// Case 2 is a reconciliation, and the contract's two rules collide without
    /// it: *"a board without a `category_map` inherits `[categories].default` for
    /// every column"* (§2) plus *"no column maps to `completed` is a configuration
    /// error"* (§3) would reject every legacy `tix.toml`, while §2 also requires
    /// that one to load unchanged (C-007). `done_column` is the resolution: it is
    /// always a configured column, it already means "this column completes work",
    /// and using it keeps a legacy board's completion behaviour exactly what it
    /// was. A board that *does* declare a map gets no such help — a map that
    /// forgot `completed` is a real mistake and is reported as one.
    pub fn category_for<'c>(&'c self, column: &str, categories: &'c CategoryConfig) -> &'c str {
        if let Some(mapped) = self.category_map.get(column) {
            return mapped;
        }
        if self.category_map.is_empty() && self.effective_done_column() == Some(column) {
            return COMPLETE_CATEGORY;
        }
        &categories.default
    }

    /// The resolved done column: the explicit `done_column`, else the one
    /// [`BoardConfiguration::inferred_done_column`] derives from `columns`.
    pub fn effective_done_column(&self) -> Option<&str> {
        self.done_column
            .as_deref()
            .or_else(|| self.inferred_done_column())
    }

    /// The `done_column` inferred from `columns` alone, for a board built in
    /// code rather than read from a file: `"done"` when that name is present,
    /// else the last configured column. `None` only for empty `columns` (which
    /// validation rejects).
    ///
    /// Split out of [`BoardConfiguration::effective_done_column`] so the
    /// inference lives in one place.
    fn inferred_done_column(&self) -> Option<&str> {
        if self.columns.iter().any(|c| c == DEFAULT_DONE_COLUMN) {
            Some(DEFAULT_DONE_COLUMN)
        } else {
            self.columns.last().map(String::as_str)
        }
    }
}

/// The `[kanban]` section: named configurations in declaration order.
///
/// `#[serde(transparent)]` maps the TOML table `[kanban.<name>]` straight
/// onto the [`IndexMap`]. The `toml` parser sorts table keys, so
/// [`Config::load_with_warning`] re-orders the map from the source
/// document's `[kanban.<name>]` header order via
/// [`restore_declaration_order`] (D-02: declaration order = tab order,
/// validated by the round-trip test). The map is never empty after load —
/// [`Config::load_with_warning`] synthesizes the shipped `default`
/// configuration when `tix.toml` omits the section.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, transparent)]
pub struct KanbanSection {
    /// Named configurations, keyed by name, in declaration order.
    pub configurations: IndexMap<String, BoardConfiguration>,
}

impl KanbanSection {
    /// Whether no board is configured. An empty section writes no `[kanban]`
    /// table, which is how a board-file project keeps its `tix.toml` free of
    /// board records.
    pub fn is_empty(&self) -> bool {
        self.configurations.is_empty()
    }
}

/// The project configuration file (`tix.toml`).
///
/// Not `Eq`, unlike each of the sections it holds: [`Config::views`] preserves
/// unknown view metadata as `toml::Value`, whose float variant includes `nan`, so
/// the reflexive equality `Eq` promises cannot be guaranteed for a config that
/// carries one. `PartialEq` is what every comparison in the tree needs — `save`
/// then `load` round-trip tests included.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    /// Named board configurations (`[kanban]`). Always ≥1 after load.
    #[serde(default, skip_serializing_if = "KanbanSection::is_empty")]
    pub kanban: KanbanSection,
    /// Directory holding issue files, relative to the repo root.
    pub issues_dir: PathBuf,
    /// Directory holding milestone markdown files, relative to the repo
    /// root. `None` → the default `docs/milestones`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub milestones_dir: Option<PathBuf>,
    /// Named teams (`[teams.<label>]`), in declaration order.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub teams: IndexMap<String, Team>,
    /// Named cycles (`[cycles.<name>]`), in declaration order.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub cycles: IndexMap<String, PlanningCycle>,
    /// Named new-issue templates (`[templates.<name>]`), in declaration order.
    ///
    /// Optional and absent by default: a project with no templates writes no
    /// section, and the F4 New Issue mode simply offers none.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub templates: IndexMap<String, IssueTemplate>,
    /// Saved view definitions (`[views.<view-id>]`), in declaration order.
    ///
    /// Mission `saved-issue-views-01M3C926` (WP01). Omitted when empty, so a
    /// repository that has never saved a view gains no key on save. The records
    /// are [`crate::views::registry::SavedView`]s: a stable id, a mutable display
    /// name, explicit scope metadata, the query plan, and preserved extension
    /// fields. Every write goes through
    /// [`crate::views::registry::ViewRegistry::commit`].
    #[serde(
        default,
        skip_serializing_if = "crate::views::registry::ViewRegistry::is_empty"
    )]
    pub views: crate::views::registry::ViewRegistry,
    /// Health policy configuration (`[health]`). Omitted when absent.
    #[serde(default, skip_serializing_if = "HealthConfig::is_empty")]
    pub health: HealthConfig,
    /// Stable-ID issue/form templates (`[issue_templates.<id>]`), in
    /// declaration order.
    ///
    /// As distinct from [`Self::templates`] as an ID is from a name: this is the
    /// registry behind `tix template` and `tix create --template`, keyed by an
    /// immutable ID with an explicit repository/board/team scope, typed defaults
    /// and prompts, typed references, and preserved unknown metadata
    /// ([`crate::templates::registry`]). The legacy name-keyed `templates` above
    /// only pre-fills the TUI New Issue form. Omitted when empty, so a project
    /// with no stable-ID templates gains no section and a legacy file
    /// round-trips byte-identically.
    #[serde(default, skip_serializing_if = "TemplateRegistry::is_empty")]
    pub issue_templates: TemplateRegistry,
    /// Planning presets and the auto-cycle counter (`[planning]`).
    #[serde(default, skip_serializing_if = "PlanningConfig::is_default")]
    pub planning: PlanningConfig,
    /// `[categories]`: the global vocabulary and safe default. Omitted when
    /// untouched, so a legacy file gains no key on save.
    #[serde(default, skip_serializing_if = "CategoryConfig::is_default")]
    pub categories: CategoryConfig,
    /// `[transitions]`: the workflow policy. Omitted when untouched.
    #[serde(default, skip_serializing_if = "TransitionConfig::is_default")]
    pub transitions: TransitionConfig,
    /// `[triage]`: the normal columns that make up the triage inbox.
    ///
    /// Mission `triage-inbox-review-flow-01M3C600`. The inbox is opt-in: `None` means
    /// no section, so no inbox, and every `tix triage` command refuses by naming the
    /// missing section. **`tix init` writes one**, with the board columns it needs, so
    /// a new repository starts with the inbox on; a legacy `tix.toml` gains no key on
    /// save. See [`crate::triage::config`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub triage: Option<crate::triage::TriageConfig>,
    /// Optional `$EDITOR` override for full-file editing.
    pub editor: Option<String>,
    /// Read-only viewer for the TUI's `v` key (tix #1507).
    ///
    /// `None` and `Some("auto")` both mean the built-in probe chain — `mdterm`,
    /// then `batcat`, `most`, `less`, `more` — and every other value names the
    /// program to run directly. Never written when unset, so a legacy file gains
    /// no key on save.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub viewer: Option<String>,
    /// Configured AI agent command (opencode, claude, etc.) launched with
    /// the issue body as its specification. Mirrors the `editor` resolution
    /// chain (explicit → `$TIX_AGENT` → `$AGENT` env → PATH fallback).
    pub agent: Option<String>,
    /// Persisted runtime state (`[state]`). Tolerated on load for legacy
    /// files, never written back to disk (issue #52).
    #[serde(skip_serializing)]
    pub state: StateConfig,
    /// External tracker targets (`[export]`). Omitted when empty, so a legacy
    /// file gains no section on save (#1415).
    #[serde(default, skip_serializing_if = "ExportConfig::is_empty")]
    pub export: ExportConfig,
    /// Sparse TUI keybinding overrides (`[keybindings]`).
    #[serde(default, skip_serializing_if = "KeyBindings::is_empty")]
    pub keybindings: KeyBindings,
    /// Top-level frontmatter keys this project uses on purpose (`[custom_attributes]`).
    ///
    /// #1361. `tix` preserves a frontmatter key it does not recognise and warns
    /// about it, because an unrecognised key is usually a typo (`titel:`) and a
    /// typo that round-trips silently is worse than one that is dropped. A project
    /// that *does* use a custom key declares it here once and stops being warned.
    ///
    /// **Top-level names only**, not dotted paths — the thing being declared is a
    /// top-level key, and accepting a path syntax here would imply nested
    /// declarations are checked, which they are not.
    #[serde(default, skip_serializing_if = "CustomAttributes::is_empty")]
    pub custom_attributes: CustomAttributes,
    /// Whether `tix lint` also lints the foreign repositories reachable from
    /// this store's `related_issues` path references and merges their warnings.
    ///
    /// Default `true`. Skipped when `true` so a `tix.toml` that does not set it
    /// round-trips byte-identically; only an explicit `false` is written.
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    pub lint_foreign_repositories: bool,
    /// Whether the TUI opens its "did you know?" tips modal on startup (tix #1632).
    ///
    /// Default `true`: a session that reaches the TUI shows one tip, then gets out
    /// of the way. `tix init` writes the key explicitly, so the setting is
    /// discoverable where the rest of the configuration lives, and the modal's `d`
    /// key writes `false` back. Skipped when `true` for the same reason
    /// [`Self::lint_foreign_repositories`] is, so a file that does not mention it
    /// round-trips byte-identically.
    #[serde(default = "default_true", skip_serializing_if = "is_true")]
    pub tips_on_startup: bool,
    /// `[mentions]`: durable `@handle` / `@email` mention tracking.
    ///
    /// OpenSpec change `issue-mentions`. Absent means the defaults — enabled, under
    /// `docs/mentions` — so no legacy file gains a key on save.
    #[serde(default, skip_serializing_if = "MentionsConfig::is_default")]
    pub mentions: MentionsConfig,
    /// `[layout]`: configurable on-disk issue layout.
    #[serde(default, skip_serializing_if = "LayoutConfig::is_default")]
    pub layout: LayoutConfig,
    /// Allowed issue `type:` values (tix #1530 renamed the key from
    /// `custom_types`; the old name is still accepted on read).
    ///
    /// `tix init` writes the default set (see [`DEFAULT_TYPES`]); `tix lint`
    /// accepts an issue's `type:` only from this list. `None` falls back to
    /// [`DEFAULT_TYPES`], so a repository that never configured it still gets a
    /// meaningful check.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "custom_types"
    )]
    pub types: Option<Vec<String>>,
    /// Extra known issue `labels` for this project, beyond the builtins.
    ///
    /// [`BUILTIN_LABELS`] are always resolved (see [`Self::labels`]), so this key
    /// is an **optional extension**: a project that wants to name its own
    /// additional labels lists them here. `tix init` does **not** write the key —
    /// a builtin needs no key, and emitting a brand-new key would make a fresh
    /// `tix.toml` unreadable to a released binary (`deny_unknown_fields`).
    /// Omitted when unset, so a legacy file gains no key on save.
    ///
    /// Unlike [`Self::types`], `tix lint` does **not** reject an undeclared
    /// label: labels are free-form across the ecosystem (tracker mirrors, import
    /// provenance), and a hard allow-list would flag every one of them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub labels: Option<Vec<String>>,
    /// Per-type accent colors (`[type_colors]`, tix #1530).
    ///
    /// Maps a type name to a color name. A type with no entry uses the shipped
    /// [`DEFAULT_TYPE_COLORS`]. Omitted when empty, so an untouched file gains
    /// no table on save.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub type_colors: IndexMap<String, String>,
    /// Directory holding tag definition files (`tags_dir`, tix #1530).
    ///
    /// Each `*.md` there names a tag and its `color:`; a tag colors the issue
    /// label of the same name in the TUI and the CLI. `None` → the default
    /// `docs/tags`. Absent by default, so a file gains no key on save.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags_dir: Option<PathBuf>,
    /// Child repositories this project coordinates (`[repos]`, tix #1529).
    ///
    /// A **parent-only** map: a project-management repository names the
    /// repositories it manages, one level deep, and each value is that child's
    /// project root (the directory holding its `tix.toml`), relative to this
    /// file. Absent by default, so a file gains no section on save. The TUI's
    /// Repos mode lists these and runs `tix` inside the chosen one.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub repos: IndexMap<String, PathBuf>,
    /// The parent repository, when this project is itself a managed child
    /// (tix #1529).
    ///
    /// Set here, the TUI's Repos mode offers a limb that runs `tix` in the
    /// parent. The parent also sets `TIX_PARENT_REPO` when it spawns a child, so
    /// the jump back works even without this key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_repo: Option<PathBuf>,
    /// Project records (`[projects.<project-id>]`), in declaration order.
    ///
    /// Mission `first-class-projects-01M3BYBW` (WP01). The map key is a stable
    /// generated [`ProjectId`] and never a display name (C-002), so renaming a
    /// project leaves every issue association and derived figure intact. Omitted
    /// entirely when empty, so a project-free repository gains no section on save
    /// and a legacy `tix.toml` round-trips byte-identically (C-001). Issue-side
    /// associations are the `projects` list in issue frontmatter; this registry is
    /// the only place a project's own record lives.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub projects: IndexMap<String, ProjectConfiguration>,
    /// Epic records (`[epics.<epic-id>]`), in declaration order.
    ///
    /// Mission `epics-work-items-01M3BYW4` (WP01). The registry key is a stable
    /// generated [`EpicId`] and never a display name (C-003), so renaming an epic
    /// leaves every member issue's reference and every derived figure intact.
    /// Omitted entirely when empty, so an epic-free repository gains no section on
    /// save and a legacy `tix.toml` round-trips byte-identically (C-004). Member
    /// issues point at an epic through the `epics` list in their frontmatter; this
    /// registry is the only place an epic's own record lives. Reference fields
    /// (`parent`, `projects`, `milestone`, `cycle`) are **shape**-checked only —
    /// resolution and diagnosis belong to the epic service and `tix lint` (C-005).
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub epics: IndexMap<String, EpicConfiguration>,
    /// Initiative records (`[initiatives.<initiative-id>]`), in declaration order.
    ///
    /// Mission `roadmap-initiatives-01M3C8SX` (WP01). The registry key is a stable
    /// generated [`InitiativeId`] and never a display name (C-002), so renaming an
    /// initiative leaves every association and derived figure intact. Omitted
    /// entirely when empty, so an initiative-free repository gains no section on save
    /// and a legacy `tix.toml` round-trips byte-identically (C-001). All writes go
    /// through the atomic boundary in [`crate::roadmap::registry`], which validates
    /// the whole change before [`Config::save`] touches the file; reference fields
    /// (`projects`, `epics`, `milestones`) are **shape**-checked only — resolution and
    /// diagnosis belong to the initiative service (WP03) and `tix lint` (C-005).
    ///
    /// Unlike its two siblings this record preserves unknown metadata rather than
    /// refusing it; see [`InitiativeConfiguration`].
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub initiatives: IndexMap<String, InitiativeConfiguration>,
    /// Cycle-schedule definitions (`[cycle_schedules.<schedule-id>]`), in
    /// declaration order.
    ///
    /// Mission `repeating-cycle-schedules-01M3C7W1` (WP01). A **schedule** is not a
    /// **cycle**: the legacy, name-keyed `[cycles.<name>]` registry above stays
    /// exactly as it is, and issue `cycles` references keep pointing at it (C-002).
    /// A schedule is the stable-ID *definition* — cadence, duration, start date,
    /// timezone, look-ahead, state — from which cycles are explicitly generated
    /// (WP04).
    ///
    /// The registry key is a stable generated [`crate::cycle_schedule::config::CycleScheduleId`]
    /// and never the display name (C-003), so a rename leaves every generated cycle,
    /// cursor and closed snapshot intact. Omitted entirely when empty, so a
    /// schedule-free repository gains no section on save and a legacy `tix.toml`
    /// round-trips byte-identically (C-001). Every field is validated by
    /// [`crate::cycle_schedule::config::validate_schedules`] before persistence, with
    /// a diagnostic that names the field (C-005).
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub cycle_schedules:
        IndexMap<String, crate::cycle_schedule::config::CycleScheduleConfiguration>,
    /// Capacity ceilings (`[capacity.<entry-id>]`), in declaration order.
    ///
    /// Mission `cycle-capacity-planning-01M3C85C` (WP01). Each entry names exactly one
    /// scope — a cycle, a team, or an assignee — and the ceiling it is allowed to commit
    /// to, in an estimate unit the WIP registry already declares (C-003, C-004). The
    /// entry's key is only a handle: the scope is a field of the record, so "which
    /// dimension is this?" is always stated rather than inferred from a table's shape,
    /// and [`crate::capacity::config::validate`] refuses an entry that names none or
    /// more than one.
    ///
    /// Omitted entirely when empty, so a capacity-free repository gains no section on
    /// save and a legacy `tix.toml` round-trips byte-identically (C-001), and unknown
    /// metadata inside an entry is preserved verbatim for a newer `tix`. A closed
    /// cycle's capacity is historical evidence: this section holds no snapshot state,
    /// and [`crate::capacity::config::ensure_cycle_editable`] is the seam that refuses a
    /// configuration edit aimed at a closed cycle (C-008).
    #[serde(default, skip_serializing_if = "CapacityConfig::is_empty")]
    pub capacity: CapacityConfig,
    /// How this repository talks to a [beads](https://github.com/gastownhall/beads)
    /// workspace (`[beads]`).
    ///
    /// Mission-tracking issues tix #1709/#1710. `off` (the default) writes no
    /// section, so a repository that never opts in is unchanged and round-trips
    /// byte-identically. `mirror` reads a beads workspace through the `bd` CLI
    /// without writing anything anywhere; `sync` keeps both sides in step through
    /// two one-way pipes. Every interaction is a `bd` CLI call — tix never opens
    /// the Dolt database. See [`crate::sync::beads`].
    #[serde(default, skip_serializing_if = "BeadsConfig::is_default")]
    pub beads: BeadsConfig,
}

/// The `[beads]` section: how this repository talks to a beads workspace.
///
/// The `binary` and `id_prefix` are stated rather than inferred so a workspace
/// that renames its `bd` binary, or wants its exported rows under a different
/// prefix, can say so without patching tix.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BeadsConfig {
    /// Whether tix talks to a beads workspace at all, and how.
    pub mode: BeadsMode,
    /// The binary shelled out to. Default `bd`.
    pub binary: String,
    /// The beads workspace to talk to, when it is not the one `bd` would find.
    ///
    /// Set into `BEADS_DIR` for every `bd` call, which is beads' own override.
    /// `None` means "wherever `bd` looks", which is what a beads workspace in
    /// this repository (or in a parent) needs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace: Option<PathBuf>,
    /// The prefix exported rows carry: issue `#1705` becomes `tix-1705`.
    ///
    /// Deterministic, which is what makes a re-export upsert rather than
    /// duplicate.
    pub id_prefix: String,
}

impl Default for BeadsConfig {
    fn default() -> Self {
        BeadsConfig {
            mode: BeadsMode::default(),
            binary: crate::sync::beads::DEFAULT_BINARY.to_string(),
            workspace: None,
            id_prefix: crate::sync::beads::DEFAULT_ID_PREFIX.to_string(),
        }
    }
}

impl BeadsConfig {
    /// Whether this section carries nothing worth writing: the default section is
    /// omitted, so a repository that never opted in gains no `[beads]` key on save
    /// — and an older binary (whose `Config` is `deny_unknown_fields`) can still
    /// read the file.
    #[must_use]
    pub fn is_default(&self) -> bool {
        *self == BeadsConfig::default()
    }
}

/// How tix talks to a beads workspace ([`BeadsConfig::mode`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BeadsMode {
    /// No beads interaction. The default, and what a repository without beads
    /// carries.
    #[default]
    Off,
    /// Read a beads workspace through `bd` for viewing only; tix writes nothing —
    /// neither to beads nor to an issue file.
    Mirror,
    /// Keep tix and beads in step through two one-way pipes
    /// (`tix` → `bd import`, and beads' own hooks → `tix beads pull`), joined by a
    /// watermark so neither side echoes the other's change back.
    Sync,
}

impl BeadsMode {
    /// The `--beads` spelling.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            BeadsMode::Off => "off",
            BeadsMode::Mirror => "mirror",
            BeadsMode::Sync => "sync",
        }
    }

    /// Parse the `--beads` spelling, or `None` for anything outside the vocabulary
    /// (which the caller reports rather than coercing).
    #[must_use]
    pub fn from_key(key: &str) -> Option<Self> {
        match key {
            "off" => Some(BeadsMode::Off),
            "mirror" => Some(BeadsMode::Mirror),
            "sync" => Some(BeadsMode::Sync),
            _ => None,
        }
    }

    /// Every mode, in the vocabulary's order.
    pub const ALL: [BeadsMode; 3] = [BeadsMode::Off, BeadsMode::Mirror, BeadsMode::Sync];
}

/// The `[custom_attributes]` section: top-level frontmatter keys this project
/// carries on purpose (#1361).
///
/// A **section** rather than a bare top-level array so there is somewhere to put
/// the next option, and so the declaration reads as a named decision rather than as
/// one more anonymous list in a file that is mostly named sections.
///
/// ```toml
/// [custom_attributes]
/// keys = ["build_id", "reviewed_by"]
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CustomAttributes {
    /// Top-level frontmatter key names. Names only — no dotted paths; the thing
    /// being declared is a top-level key, and a path syntax here would imply nested
    /// declarations are checked when they are not.
    pub keys: Vec<String>,
}

impl CustomAttributes {
    /// Whether anything is declared, for `skip_serializing_if`.
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }
}

/// Serde default for a boolean that defaults to `true`.
///
/// Shared with [`crate::capacity::config::CapacityEntry`], whose `enabled` follows the
/// same rule the WIP limits set: writing the default is not writing anything.
pub(crate) fn default_true() -> bool {
    true
}
/// `skip_serializing_if` for a boolean whose default is `true`: only an explicit
/// `false` is written to disk.
#[allow(clippy::trivially_copy_pass_by_ref)] // serde requires `fn(&bool) -> bool`
pub(crate) fn is_true(value: &bool) -> bool {
    *value
}

/// The default issue types: what `tix init` writes into `types`, and what
/// `tix lint` accepts when a repository carries no `types`.
///
/// `default` is the value an issue without a `type:` falls back to (in `[layout]`
/// and as an explicit option). `bug`, `open` and `duplicate` are the requested
/// baseline, with the usual companions.
pub const DEFAULT_TYPES: &[&str] = &[
    "default",
    "bug",
    "feature",
    "task",
    "improvement",
    "documentation",
    "question",
    "duplicate",
    "chore",
    "open",
];

/// Labels tix itself ships and always recognises — no configuration required.
///
/// `decision-pending` is the label behind the `DECISION:` convention: an open
/// question a human must settle before the issue can move. It is a **builtin**,
/// not a config default, so every repository resolves it whether or not its
/// `tix.toml` names it — and `tix init` does not write a `labels` key for it (a
/// new key would be rejected by an older binary's `deny_unknown_fields`).
pub const BUILTIN_LABELS: &[&str] = &["decision-pending"];

/// A shipped accent color per default type (tix #1530).
///
/// The color names are the ones [`crate::ui::color::parse`] understands. A type
/// absent here — and absent from `[type_colors]` — renders uncolored. `open` and
/// `default` are deliberately neutral (gray/white) so a type chip does not
/// compete with the priority and blocked markers beside it.
pub const DEFAULT_TYPE_COLORS: &[(&str, &str)] = &[
    ("default", "gray"),
    ("bug", "red"),
    ("feature", "green"),
    ("task", "blue"),
    ("improvement", "cyan"),
    ("documentation", "yellow"),
    ("question", "magenta"),
    ("duplicate", "dark_gray"),
    ("chore", "dark_gray"),
    ("open", "white"),
];

/// The `[mentions]` section: durable `@handle` / `@email` mention tracking.
///
/// Default **enabled**, unlike the opt-in `[triage]` section: the feature is a scan that runs
/// on an issue write that already happened, and its footprint is bounded on the other side —
/// a mention file is created lazily, only once a real mention is found, and a bare `user@host`
/// or a `@word` inside code is not a mention. Setting `enabled = false` is the off switch, and
/// it stops both the scan and every write.
///
/// Omitted from the file when it is the default, so a `tix.toml` that has never configured
/// mentions round-trips byte-identically and gains no key on save.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct MentionsConfig {
    /// Whether issue writes scan for mentions and record them.
    pub enabled: bool,
    /// Directory holding the per-target mention files, relative to the project root unless
    /// absolute. `None` is not a state: the default is [`DEFAULT_MENTIONS_DIR`].
    pub dir: PathBuf,
}

/// The directory mention files live in, relative to the project root.
pub const DEFAULT_MENTIONS_DIR: &str = "docs/mentions";

impl Default for MentionsConfig {
    fn default() -> Self {
        MentionsConfig {
            enabled: true,
            dir: PathBuf::from(DEFAULT_MENTIONS_DIR),
        }
    }
}

impl MentionsConfig {
    /// Whether this is the default, for `skip_serializing_if`.
    #[must_use]
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }

    /// The absolute directory the store reads and writes.
    ///
    /// A relative `dir` resolves against the **project root** — the directory holding
    /// `tix.toml` — not the invocation directory, the same rule `issues_dir` follows
    /// ([`crate::storage::Store::open`]).
    #[must_use]
    pub fn resolve_dir(&self, issues_dir: &Path) -> PathBuf {
        if self.dir.is_absolute() {
            return self.dir.clone();
        }
        match Config::project_root(issues_dir) {
            Some(root) => root.join(&self.dir),
            None => self.dir.clone(),
        }
    }
}

/// The `[layout]` section: configurable on-disk issue layout.
///
/// Tokens are validated at config load ([`crate::layout::validate`]). The
/// defaults reproduce the documented layout — `{assignee}/{type}/{status}` for
/// the directory, `{date}-{slug}.md` for the filename, moving files when a
/// templated value changes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LayoutConfig {
    /// Directory template, relative to `issues_dir`.
    pub directory: String,
    /// Filename template; must end in `.md`.
    pub filename: String,
    /// Relocate an issue when a templated value changes (status/assignee/type).
    pub move_on_change: bool,
}

impl Default for LayoutConfig {
    fn default() -> Self {
        LayoutConfig {
            directory: "{assignee}/{type}/{status}".to_string(),
            // Date first, then the id: a lexicographic listing of the directory
            // is then creation order, while the id keeps the name globally
            // unique across branches (and disambiguates same-day, same-title
            // issues). `number` is deliberately absent — it can collide across
            // branches and is not an identity.
            filename: "{date}-{id}-{slug}.md".to_string(),
            move_on_change: true,
        }
    }
}

impl LayoutConfig {
    /// Whether this is the default, for `skip_serializing_if`.
    #[must_use]
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            kanban: KanbanSection {
                configurations: IndexMap::from([(
                    "default".to_string(),
                    BoardConfiguration::default(),
                )]),
            },
            issues_dir: PathBuf::from("docs/issues"),
            milestones_dir: None,
            teams: IndexMap::new(),
            cycles: IndexMap::new(),
            templates: IndexMap::new(),
            views: crate::views::registry::ViewRegistry::new(),
            health: HealthConfig::default(),
            issue_templates: TemplateRegistry::default(),
            planning: PlanningConfig::default(),
            categories: CategoryConfig::default(),
            transitions: TransitionConfig::default(),
            // The bare default has no inbox, and that stays true: the mechanism is
            // opt-in, so a config with no `[triage]` section has no inbox and every
            // `tix triage` command refuses, naming the section. What changed is the
            // *starting point*: `tix init` writes the section (and the board columns it
            // needs), so a new repository begins with an inbox rather than with a
            // refusal. See [`crate::commands::init`].
            triage: None,
            editor: None,
            viewer: None,
            state: StateConfig::default(),
            export: ExportConfig::default(),
            agent: None,
            keybindings: KeyBindings::default(),
            custom_attributes: CustomAttributes::default(),
            lint_foreign_repositories: true,
            tips_on_startup: true,
            mentions: MentionsConfig::default(),
            layout: LayoutConfig::default(),
            types: None,
            labels: None,
            type_colors: IndexMap::new(),
            tags_dir: None,
            repos: IndexMap::new(),
            parent_repo: None,
            projects: IndexMap::new(),
            epics: IndexMap::new(),
            initiatives: IndexMap::new(),
            cycle_schedules: IndexMap::new(),
            capacity: CapacityConfig::new(),
            beads: BeadsConfig::default(),
        }
    }
}

impl Config {
    /// The configuration a **new repository** starts with — what `tix init` writes.
    ///
    /// Deliberately not [`Default`]: that is the fallback for a missing or partial
    /// `tix.toml` (and the base hundreds of tests build fixtures on), and it stays
    /// minimal. The *starting point* is a product decision: a new repository gets the
    /// board [`starter_board`] lays out and a working `[triage]` section, so
    /// `tix triage list` works on a fresh checkout instead of refusing and asking for
    /// configuration first.
    ///
    /// The three keys match the board: unreviewed work sits in `triage`, an accept
    /// lands in `todo`, a decline in `wontfix`. `deferred_status` is left unset
    /// because it defaults to `entry_status`, and a default that is never written is a
    /// default that cannot drift from the meaning it stands for.
    #[must_use]
    pub fn starter() -> Config {
        let mut config = Config::default();
        config
            .kanban
            .configurations
            .insert("default".to_string(), starter_board());
        config.triage = Some(crate::triage::TriageConfig {
            entry_status: Some("triage".to_string()),
            accepted_status: Some("todo".to_string()),
            declined_status: Some("wontfix".to_string()),
            deferred_status: None,
        });
        // `tix init` writes the default issue types explicitly, so a new project
        // sees and can edit them; a repository without the key falls back to the
        // same list at lint time.
        config.types = Some(DEFAULT_TYPES.iter().map(|s| (*s).to_string()).collect());
        // `labels` is deliberately NOT written: `decision-pending` is a builtin
        // (`BUILTIN_LABELS`), so no key is needed, and emitting a brand-new key
        // would make a fresh `tix.toml` unreadable to a released binary whose
        // `Config` denies unknown fields.
        // Ship the tag directory explicitly (tix #1530), so a new project has
        // somewhere to drop `docs/tags/*.md` without having to know the key.
        config.tags_dir = Some(PathBuf::from("docs/tags"));
        config
    }

    /// Validate the invariant rules from `contracts/tix-toml.md`, returning
    /// the `Config` error variant with a human message. Errors name the
    /// offending configuration as `kanban.<name>.<field>` (NFR-003).
    pub(crate) fn validate(&self) -> Result<()> {
        if self.issues_dir.as_os_str().is_empty() {
            return Err(TixError::Config("`issues_dir` must not be blank".into()));
        }
        if self.milestones_dir().as_os_str().is_empty() {
            return Err(TixError::Config(
                "`milestones_dir` must not be blank".into(),
            ));
        }
        if self.tags_dir().as_os_str().is_empty() {
            return Err(TixError::Config("`tags_dir` must not be blank".into()));
        }
        validate_repos(&self.repos)?;
        // The health policy version is a closed set, and a repository naming one
        // this build does not implement is refused here rather than at the first
        // rollup: a value derived under a formula nobody can name is worse than a
        // file that will not load.
        self.health.policy()?;
        if self
            .parent_repo
            .as_deref()
            .is_some_and(|p| p.as_os_str().is_empty())
        {
            return Err(TixError::Config("`parent_repo` must not be blank".into()));
        }
        // A blank `viewer` is a mistake with a clear spelling: the way to ask for
        // the probe chain is `auto` (or omitting the key). Rejected here rather
        // than silently treated as auto, so a typo cannot quietly change the
        // meaning of a saved file.
        if self.viewer.as_deref().is_some_and(|v| v.trim().is_empty()) {
            return Err(TixError::Config(
                "`viewer` must not be blank; use `auto` for the default chain".into(),
            ));
        }
        validate_planning(&self.planning)?;
        crate::layout::validate(&self.layout)?;
        validate_categories(&self.categories)?;
        self.effective_keybindings()?;
        if self.kanban.configurations.is_empty() {
            return Err(TixError::Config(
                "`[kanban]` must define at least one configuration".into(),
            ));
        }
        for (name, board) in &self.kanban.configurations {
            validate_board(name, board)?;
            validate_category_map(name, board, &self.categories)?;
        }
        for (label, team) in &self.teams {
            validate_team(label, team)?;
        }
        for (name, cycle) in &self.cycles {
            validate_cycle(name, cycle)?;
        }
        for (name, template) in &self.templates {
            validate_template(name, template)?;
        }
        // Project records: a valid stable id as the key, a non-blank unique display
        // name, present-but-blank optional text refused, and the shared date rules.
        // Project *resolution* (does a view/issue reference an existing project?) is
        // not `Config` validation, for the same reason view scopes are not: a
        // reference to a deleted project must stay loadable and diagnosable (C-005).
        validate_projects(&self.projects)?;
        // Epic records: the same structural rules as projects (a valid stable id as
        // the key, a non-blank unique display name, present-but-blank optional text
        // refused, the shared date rules), plus a positive `weight` and the
        // epic-specific reference *shapes*. Epic *resolution* — does a project,
        // milestone, cycle, or parent epic exist? — is deliberately not `Config`
        // validation, for the same reason project resolution is not: a dangling
        // reference caused by a deletion or a hand edit must stay loadable and
        // diagnosable (C-005).
        validate_epics(&self.epics)?;
        // Initiative records: the same structural rules as projects and epics (a
        // valid stable id as the key, a non-blank unique display name, the shared
        // calendar-date rule), plus the initiative-specific reference *shapes* —
        // project/epic ids for `projects`/`epics` and non-blank names for
        // `milestones`. Initiative *resolution* — does a referenced project, epic, or
        // milestone exist? — is deliberately not `Config` validation, for the same
        // reason project/epic resolution is not: a dangling reference caused by a
        // deletion or a hand edit must stay loadable and diagnosable (C-005).
        validate_initiatives(&self.initiatives)?;
        crate::cycle_schedule::config::validate_schedules(&self.cycle_schedules)?;
        // `[capacity]`'s rootless half — the entry handle, exactly one scope, the
        // ceiling, and the *declared unit* — is validated here, because every
        // validate-then-save path (`tix wip unit --remove`, the schedule registry, the MCP
        // write tools) validates with this method before it writes: without the unit check
        // there, removing a unit a ceiling names would persist a file the next load
        // refuses. The half that needs the cycle **records** — resolving a cycle reference
        // to a generated cycle's identity — is validated by the loader
        // (`Config::load_with_warning`) and by `crate::capacity::config::set_capacity`,
        // the only two gates with a project root; see `crate::capacity::config::validate`.
        crate::capacity::config::validate(&self.capacity, self)?;
        // View records are validated for *structure* here: a blank name, a scope
        // that contradicts itself, an id that disagrees with its table key. Project
        // *resolution* is deliberately not part of `Config` validation — it needs
        // the project registry, and a view pointing at a project that was deleted
        // must stay loadable (and diagnosable) rather than making `tix.toml`
        // unreadable. The write path refuses it instead
        // (`ViewRegistry::commit`, C-008).
        self.views
            .check_structure()
            .map_err(|refusal| TixError::Config(refusal.render()))?;
        // Stable-ID templates: scope binding, prompt shape, references and
        // preserved metadata. Field-aware errors name `issue_templates.<id>...`.
        self.issue_templates.validate(self)?;
        // Last, deliberately. `[triage]` names columns from the active board
        // *and* from that board's `category_map`, so it can only be judged once
        // both are; running it earlier would hand `workflow::resolution` an
        // unvalidated vocabulary, which is the `unreachable!` it documents
        // (C-002).
        crate::triage::config::validate(self)?;
        Ok(())
    }

    /// Resolve sparse user overrides over the built-in TUI registry.
    pub fn effective_keybindings(&self) -> Result<EffectiveBindings> {
        KeyBindings::resolve(&self.keybindings)
    }

    /// Allocate a [`ProjectId`] that is not already in the registry.
    ///
    /// Redraws against the stored ids, so a stored id is never handed out a second
    /// time. The rest of the never-reused guarantee is carried by the id shape
    /// itself (see [`StableId::generate`]); there is no counter persisted in
    /// `tix.toml`, so a deletion cannot reset an allocator — the id a deleted
    /// project carried stays spent because no draw can repeat one this process
    /// already produced.
    #[must_use]
    pub fn allocate_project_id(&self) -> ProjectId {
        self.allocate_project_id_with(ProjectId::generate)
    }

    /// [`Self::allocate_project_id`] with the draw injected, so the redraw loop
    /// itself is testable: a real generator collides so rarely that a test driving
    /// it can only ever observe the first iteration.
    fn allocate_project_id_with(&self, draw: impl FnMut() -> ProjectId) -> ProjectId {
        allocate_stable_id(&self.projects, draw)
    }

    /// Allocate an [`EpicId`] that is not already in the registry.
    ///
    /// Mirrors [`Self::allocate_project_id`]: the draw is redrawn against the stored
    /// ids, so a stored id is never handed out a second time, and the rest of the
    /// never-reused guarantee is carried by the id shape itself
    /// ([`StableId::generate`]) — a deleted epic's id stays spent, keeping a member
    /// issue's dangling reference diagnosable rather than silently rebound (C-005).
    #[must_use]
    pub fn allocate_epic_id(&self) -> EpicId {
        self.allocate_epic_id_with(EpicId::generate)
    }

    /// [`Self::allocate_epic_id`] with the draw injected, so the redraw loop itself
    /// is testable.
    fn allocate_epic_id_with(&self, draw: impl FnMut() -> EpicId) -> EpicId {
        allocate_stable_id(&self.epics, draw)
    }

    /// Allocate an [`InitiativeId`] that is not already in the registry.
    ///
    /// Mirrors [`Self::allocate_project_id`]: the draw is redrawn against the stored
    /// ids, so a stored id is never handed out a second time, and the rest of the
    /// never-reused guarantee is carried by the id shape itself
    /// ([`StableId::generate`]) — a deleted initiative's id stays spent, keeping the
    /// record's identity distinct from any later one.
    #[must_use]
    pub fn allocate_initiative_id(&self) -> InitiativeId {
        self.allocate_initiative_id_with(InitiativeId::generate)
    }

    /// [`Self::allocate_initiative_id`] with the draw injected, so the redraw loop
    /// itself is testable.
    fn allocate_initiative_id_with(&self, draw: impl FnMut() -> InitiativeId) -> InitiativeId {
        allocate_stable_id(&self.initiatives, draw)
    }

    /// Allocate a fresh [`crate::cycle_schedule::config::CycleScheduleId`].
    ///
    /// Mirrors [`Self::allocate_initiative_id`]: the draw is redrawn against the
    /// stored ids, so a stored id is never handed out a second time, and the rest of
    /// the never-reused guarantee is carried by the id shape itself
    /// ([`StableId::generate`]) — a deleted schedule's id stays spent, keeping the
    /// record's identity distinct from any later one (C-003).
    #[must_use]
    pub fn allocate_cycle_schedule_id(&self) -> crate::cycle_schedule::config::CycleScheduleId {
        self.allocate_cycle_schedule_id_with(
            crate::cycle_schedule::config::CycleScheduleId::generate,
        )
    }

    /// [`Self::allocate_cycle_schedule_id`] with the draw injected, so the redraw loop
    /// itself is testable: a real generator collides with a stored id so rarely that
    /// the loop is otherwise unverifiable.
    fn allocate_cycle_schedule_id_with(
        &self,
        draw: impl FnMut() -> crate::cycle_schedule::config::CycleScheduleId,
    ) -> crate::cycle_schedule::config::CycleScheduleId {
        allocate_stable_id(&self.cycle_schedules, draw)
    }

    /// Restore the canonical declaration order of named configurations,
    /// which the TOML parser loses (it sorts table keys). The order comes
    /// from `[kanban.<name>]` section headers in the source document.
    fn restore_declaration_order(&mut self, contents: &str) {
        crate::config::restore_section_order(&mut self.kanban.configurations, contents, "kanban");
        crate::config::restore_section_order(&mut self.cycles, contents, "cycles");
        crate::config::restore_section_order(&mut self.teams, contents, "teams");
        crate::config::restore_section_order(&mut self.templates, contents, "templates");
        self.views.restore_declaration_order(contents);
        crate::config::restore_section_order(
            &mut self.issue_templates.templates,
            contents,
            "issue_templates",
        );
        crate::config::restore_section_order(&mut self.projects, contents, "projects");
        crate::config::restore_section_order(&mut self.epics, contents, "epics");
        crate::config::restore_section_order(&mut self.initiatives, contents, "initiatives");
        crate::config::restore_section_order(
            &mut self.cycle_schedules,
            contents,
            "cycle_schedules",
        );
        self.capacity.restore_declaration_order(contents);
    }

    /// Declared custom top-level frontmatter keys, lowercased for comparison.
    ///
    /// Lowercased because YAML keys are case-sensitive but nobody has ever
    /// intended `Titel` and `titel` to be different keys, and a suppression list
    /// that silently fails to match is worse than no list at all.
    pub fn custom_attributes(&self) -> Vec<String> {
        self.custom_attributes
            .keys
            .iter()
            .map(|k| k.trim().to_ascii_lowercase())
            .collect()
    }

    /// The allowed issue types: the configured `types`, or [`DEFAULT_TYPES`]
    /// when unset. Compared case-insensitively by callers.
    #[must_use]
    pub fn types(&self) -> Vec<String> {
        self.types
            .clone()
            .unwrap_or_else(|| DEFAULT_TYPES.iter().map(|s| (*s).to_string()).collect())
    }

    /// The pre-#1530 name for [`Self::types`], kept so existing call sites and
    /// tests read the same list under the old spelling.
    #[must_use]
    pub fn custom_types(&self) -> Vec<String> {
        self.types()
    }

    /// The recognised issue labels: [`BUILTIN_LABELS`], plus any extra labels the
    /// project declares under `labels` in `tix.toml`.
    ///
    /// Builtins come first and are always present, so `decision-pending` resolves
    /// in a repository that never configured the key — which is why `tix init`
    /// does not write one.
    #[must_use]
    pub fn labels(&self) -> Vec<String> {
        let mut out: Vec<String> = BUILTIN_LABELS.iter().map(|s| (*s).to_string()).collect();
        if let Some(extra) = &self.labels {
            for label in extra {
                if !out.contains(label) {
                    out.push(label.clone());
                }
            }
        }
        out
    }

    /// The color name for issue `type`, from `[type_colors]` when set for it, else
    /// the shipped [`DEFAULT_TYPE_COLORS`] entry. `None` for a type with no color
    /// anywhere (an unknown type). Compared case-insensitively (tix #1530).
    #[must_use]
    pub fn type_color(&self, type_name: &str) -> Option<String> {
        let needle = type_name.trim().to_ascii_lowercase();
        self.type_colors
            .iter()
            .find(|(name, _)| name.to_ascii_lowercase() == needle)
            .map(|(_, color)| color.clone())
            .or_else(|| {
                DEFAULT_TYPE_COLORS
                    .iter()
                    .find(|(name, _)| *name == needle)
                    .map(|(_, color)| (*color).to_string())
            })
    }

    /// The attribute list shown and edited in the Config view: the declared
    /// `[custom_attributes].keys`, or the built-in attributes tix models when
    /// none are declared. Mirrors [`Self::custom_types`] (`configured-or-defaults`).
    #[must_use]
    pub fn attributes(&self) -> Vec<String> {
        if self.custom_attributes.keys.is_empty() {
            crate::model::KNOWN_FRONTMATTER_KEYS
                .iter()
                .filter(|key| **key != "links")
                .map(|key| (*key).to_string())
                .collect()
        } else {
            self.custom_attributes.keys.clone()
        }
    }

    /// The resolved milestones directory: the configured value, or the
    /// contract default `docs/milestones` when unset.
    pub fn milestones_dir(&self) -> &Path {
        self.milestones_dir
            .as_deref()
            .unwrap_or(Path::new("docs/milestones"))
    }

    /// The resolved tags directory: the configured `tags_dir`, or the contract
    /// default `docs/tags` when unset (tix #1530).
    pub fn tags_dir(&self) -> &Path {
        self.tags_dir.as_deref().unwrap_or(Path::new("docs/tags"))
    }

    /// The child repositories this project coordinates (`[repos]`, tix #1529).
    pub fn repos(&self) -> &IndexMap<String, PathBuf> {
        &self.repos
    }

    /// The parent repository, when this project is a managed child (tix #1529).
    pub fn parent_repo(&self) -> Option<&Path> {
        self.parent_repo.as_deref()
    }

    /// Absolutize the paths that are resolved against the project root:
    /// an explicitly configured `tags_dir`, every `[repos]` entry, and
    /// `parent_repo` (tix #1529/#1530).
    ///
    /// Only a **relative** configured value is rewritten, so an unset key stays
    /// `None` (and is not materialized on save) and an absolute one is left
    /// alone. `issues_dir`/`milestones_dir` are resolved elsewhere; this covers
    /// the newer keys so the TUI can spawn `tix` in a child from any working
    /// directory.
    pub fn resolve_repo_paths(&mut self, base: &Path) {
        if let Some(path) = self.tags_dir.as_ref() {
            if path.is_relative() {
                self.tags_dir = Some(base.join(path));
            }
        }
        for path in self.repos.values_mut() {
            if path.is_relative() {
                *path = base.join(&*path);
            }
        }
        if let Some(path) = self.parent_repo.clone() {
            if path.is_relative() {
                self.parent_repo = Some(base.join(path));
            }
        }
    }

    /// The configuration used by the CLI and other single-config surfaces:
    /// the one named `default` if present, else the first declared.
    pub fn default_config(&self) -> &BoardConfiguration {
        self.kanban
            .configurations
            .get("default")
            .or_else(|| self.kanban.configurations.first().map(|(_, board)| board))
            .expect("validate() guarantees at least one configuration")
    }

    /// Named configurations in declaration order (tab order = declaration
    /// order, D-02).
    pub fn configs(&self) -> impl Iterator<Item = (&str, &BoardConfiguration)> {
        self.kanban
            .configurations
            .iter()
            .map(|(name, board)| (name.as_str(), board))
    }

    /// Load a `tix.toml` at `path`, emitting a warning through `sink` for
    /// every cleartext token read from the file.
    ///
    /// Parse and validation failures surface as [`TixError::Config`] with
    /// the file's path and (where the TOML parser reports it) line.
    pub fn load_with_warning(path: &Path, mut sink: impl FnMut(&str)) -> Result<Config> {
        let contents = std::fs::read_to_string(path)
            .map_err(|e| TixError::Config(format!("{}: {e}", path.display())))?;
        let mut config: Config = toml::from_str(&contents)
            .map_err(|e| TixError::Config(format!("{}: {e}", path.display())))?;
        config.restore_declaration_order(&contents);
        // File stores win over the legacy tables whenever their directory
        // exists. Absent directories mean an existing project: its
        // `[kanban.*]`/`[cycles.*]` tables load exactly as before.
        let root = path
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        let board_store = BoardStore::new(root);
        if board_store.exists() {
            let boards = board_store
                .list()
                .map_err(|e| TixError::Config(format!("{}: {e}", path.display())))?;
            if !boards.is_empty() {
                // The board **files** own a board's shape — its columns, its
                // categories, its display — and `tix.toml` owns its **limits**:
                // C-001 puts the work-in-progress configuration there, and a
                // scaffolded repository (`tix init`) keeps its board in
                // `docs/boards/<name>.md`. Replacing the section wholesale, which is
                // what this did before limits existed, silently dropped them — so a
                // `tix wip set` on such a project wrote a limit that nothing ever
                // read (found by WP06's MCP test, whose `tix init` repository showed
                // no limit at all).
                let declared = std::mem::take(&mut config.kanban.configurations);
                config.kanban = KanbanSection {
                    configurations: boards
                        .into_iter()
                        .map(|(name, mut board)| {
                            if let Some(from_toml) = declared.get(&name) {
                                board.wip = from_toml.wip.clone();
                            }
                            (name, board)
                        })
                        .collect(),
                };
            }
        }
        let cycle_store = CycleStore::new(root);
        if cycle_store.exists() {
            let cycles = cycle_store
                .list()
                .map_err(|e| TixError::Config(format!("{}: {e}", path.display())))?;
            config.cycles = cycles
                .into_iter()
                .map(|record| (record.name.clone(), record.into()))
                .collect();
        }
        if config.kanban.configurations.is_empty() {
            config.kanban = KanbanSection {
                configurations: IndexMap::from([(
                    "default".to_string(),
                    BoardConfiguration::default(),
                )]),
            };
        }
        config.validate().map_err(|e| at_file(path, e))?;
        // The records' half of the capacity section's validation: a cycle reference
        // resolves against `docs/cycles/` (or the legacy `[cycles.<name>]` tables when there
        // is no store), and the records are what tell a generated cycle's name from a
        // hand-written one. `capacity::config::set_capacity` is the other gate, over the
        // same records, for every programmatic change (WP01).
        crate::capacity::config::validate_cycle_references(&config.capacity, &config, root)
            .map_err(|e| at_file(path, e))?;
        for remote in [config.export.gitlab.as_ref(), config.export.linear.as_ref()]
            .into_iter()
            .flatten()
        {
            if remote.token.is_some() {
                sink(
                    "Warning: token found in tix.toml — prefer GITLAB_TOKEN / LINEAR_TOKEN env vars",
                );
            }
        }
        Ok(config)
    }

    /// Load the config for a project root: `tix.toml` at the root if
    /// present, otherwise the defaults. An absent file is *not* an error —
    /// the CLI layer decides whether to nag about `tix init`.
    pub fn load(project_root: &Path) -> Result<Config> {
        let path = project_root.join("tix.toml");
        if !path.is_file() {
            return Ok(Config::default());
        }
        Self::load_with_warning(&path, |w| eprintln!("{w}"))
    }

    /// Find the project root for `cwd` by walking upward for a `tix.toml`.
    /// Returns `None` when no ancestor (including `cwd` itself) holds one.
    pub fn project_root(cwd: &Path) -> Option<PathBuf> {
        let mut dir = Some(cwd.to_path_buf());
        while let Some(current) = dir {
            if current.join("tix.toml").is_file() {
                return Some(current);
            }
            dir = current.parent().map(Path::to_path_buf);
        }
        None
    }

    /// A copy of this config with every token stripped, for writing.
    fn sanitized_for_disk(&self) -> Config {
        let mut copy = self.clone();
        if let Some(gitlab) = copy.export.gitlab.as_mut() {
            gitlab.token = None;
        }
        if let Some(linear) = copy.export.linear.as_mut() {
            linear.token = None;
        }
        copy
    }

    /// Write `tix.toml` atomically (temp file + rename in the same
    /// directory, with an `fsync` before the rename — NFR-006).
    ///
    /// Tokens are never written to disk, so a round-trip `load` → `save`
    /// drops any cleartext token (expected: prefer env vars).
    pub fn save(&self, path: &Path) -> Result<()> {
        let dir = match path.parent() {
            Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
            _ => PathBuf::from("."),
        };
        std::fs::create_dir_all(&dir)?;

        // A file store that exists is authoritative for its records: write
        // them there and leave them out of `tix.toml`. Every other setting
        // still round-trips through the TOML file.
        let board_store = BoardStore::new(&dir);
        let board_store_active = board_store.exists();
        if board_store_active {
            for (name, board) in &self.kanban.configurations {
                let filename = format!("{}.md", crate::slug::slugify(name));
                let body = RecordStore::new(board_store.dir()).body_of(&filename);
                board_store.save(name, board, body.as_deref())?;
            }
        }
        let cycle_store = CycleStore::new(&dir);
        let cycle_store_active = cycle_store.exists();
        if cycle_store_active {
            for (name, cycle) in &self.cycles {
                if is_implicit_default(name, cycle) {
                    continue;
                }
                let filename = format!("{}.md", crate::slug::slugify(name));
                let body = RecordStore::new(cycle_store.dir()).body_of(&filename);
                cycle_store.save(name, cycle, body.as_deref())?;
            }
        }

        let mut disk = self.sanitized_for_disk();
        if board_store_active {
            disk.kanban = KanbanSection::default();
        }
        if cycle_store_active {
            disk.cycles.clear();
        }
        let contents = toml::to_string_pretty(&disk)
            .map_err(|e| TixError::Config(format!("cannot serialize tix.toml: {e}")))?;

        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("tix.toml");
        let tmp = dir.join(format!("{file_name}.tmp-{}", std::process::id()));

        let write_result = (|| -> std::io::Result<()> {
            let mut f = std::fs::File::create(&tmp)?;
            use std::io::Write;
            f.write_all(contents.as_bytes())?;
            f.sync_all()?;
            Ok(())
        })();
        if let Err(e) = write_result {
            let _ = std::fs::remove_file(&tmp);
            return Err(TixError::Io(e));
        }

        if let Err(e) = std::fs::rename(&tmp, path) {
            let _ = std::fs::remove_file(&tmp);
            return Err(TixError::Io(e));
        }
        Ok(())
    }
}

/// Prefix a configuration error with the file it came from.
///
/// A load failure has to name its source: a program that coordinates repositories
/// (tix #1529) reads more than one `tix.toml`, and a message that does not say which one
/// was refused is a message nobody can act on. Shared by the two validation gates a load
/// runs, so both name the file the same way.
fn at_file(path: &Path, error: TixError) -> TixError {
    match error {
        TixError::Config(msg) => TixError::Config(format!("{}: {msg}", path.display())),
        other => other,
    }
}

/// Redraw a fresh id until it is not already a key of `registry`.
///
/// Shared by [`Config::allocate_project_id`] and [`Config::allocate_epic_id`]. It is
/// the exact half of the never-reused guarantee: a *stored* id is never handed out a
/// second time. A deletion cannot reset it, because the allocator holds no state a
/// removal could rewind — the remaining half is carried by the id shape itself
/// ([`StableId::generate`]).
pub(crate) fn allocate_stable_id<I: StableId, V>(
    registry: &IndexMap<String, V>,
    mut draw: impl FnMut() -> I,
) -> I {
    loop {
        let candidate = draw();
        if !registry.contains_key(candidate.as_str()) {
            return candidate;
        }
    }
}

/// Reorder a named-config `IndexMap` to the declaration order of its
/// `[<section>.<name>]` section headers in the source document (D-02:
/// declaration order = tab order). The `toml` crate sorts table keys on
/// deserialize, so the parser's order is not trustworthy; this returns to the
/// document's byte order. Applies to `[kanban.*]`, `[cycles.*]`, `[teams.*]`,
/// `[projects.*]`, `[epics.*]`, `[initiatives.*]`, `[cycle_schedules.*]` and
/// `[views.*]` (the last through
/// its own wrapper). Names are unquoted when the header used a quoted key (e.g.
/// `[cycles."Cycle 1"]`).
pub(crate) fn restore_section_order<V: Clone>(
    map: &mut IndexMap<String, V>,
    contents: &str,
    section: &str,
) {
    let mut order: Vec<String> = Vec::new();
    for line in contents.lines() {
        let line = line.trim();
        if let Some(rest) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']'))
            && let Some((head, key)) = rest.split_once('.')
            && head.trim() == section
            && !key.trim().contains('.')
            && let Some(name) = unquote_key(key.trim())
            && !order.iter().any(|n| n == name)
        {
            order.push(name.to_string());
        }
    }
    if order.is_empty() {
        return;
    }
    let mut ordered = IndexMap::new();
    for name in &order {
        if let Some(value) = map.shift_remove(name) {
            ordered.insert(name.clone(), value);
        }
    }
    ordered.extend(map.iter().map(|(n, v)| (n.clone(), (*v).clone())));
    *map = ordered;
}

/// Strip a single pair of surrounding single or double quotes from a TOML
/// table-header key, when present.
fn unquote_key(key: &str) -> Option<&str> {
    if let Some(inner) = key.strip_prefix('"').and_then(|k| k.strip_suffix('"')) {
        Some(inner)
    } else if let Some(inner) = key.strip_prefix('\'').and_then(|k| k.strip_suffix('\'')) {
        Some(inner)
    } else {
        Some(key)
    }
}

/// Validation for the `[planning]` section (NFR-003): the counter must be
/// positive once the section is present.
fn validate_planning(planning: &PlanningConfig) -> Result<()> {
    if planning.cycle_number == 0 {
        return Err(TixError::Config(
            "`planning.cycle_number` must be at least 1".into(),
        ));
    }
    Ok(())
}

/// `[repos]`: a name and a path, neither blank (tix #1529).
///
/// The depth rule is structural rather than a check here: a parent lists only
/// its own direct children, and a child reaches the parent through
/// `parent_repo`, so a two-level chain is two processes, never a nested walk.
fn validate_repos(repos: &IndexMap<String, PathBuf>) -> Result<()> {
    for (name, path) in repos {
        if name.trim().is_empty() {
            return Err(TixError::Config(
                "`[repos]` entry names must not be blank".into(),
            ));
        }
        if path.as_os_str().is_empty() {
            return Err(TixError::Config(format!(
                "`repos.{name}` must name the repository path"
            )));
        }
    }
    Ok(())
}

/// Per-team validation (NFR-003): non-blank label, non-empty members, unique
/// member identities.
fn validate_team(label: &str, team: &Team) -> Result<()> {
    if label.trim().is_empty() {
        return Err(TixError::Config("`teams.<label>` must not be blank".into()));
    }
    if team.members.is_empty() {
        return Err(TixError::Config(format!(
            "`teams.{label}.members` must not be empty"
        )));
    }
    let mut seen: HashSet<&str> = HashSet::new();
    for member in &team.members {
        if !seen.insert(member.as_str()) {
            return Err(TixError::Config(format!(
                "`teams.{label}.members` must be unique; found duplicate `{member}`"
            )));
        }
    }
    Ok(())
}

/// The key of a `[<section>.<id>]` registry must be a valid stable id.
///
/// Shared by `[projects.<project-id>]`, `[epics.<epic-id>]`,
/// `[initiatives.<initiative-id>]` and `[cycle_schedules.<schedule-id>]`: the rule
/// that keeps a rename from breaking a reference — and the key safe as a TOML table
/// header — lives on [`StableId`], so this only names the section the error belongs
/// to.
pub(crate) fn validate_registry_key<I: StableId>(section: &str, id: &str) -> Result<()> {
    I::new(id).map_err(|err| TixError::Config(format!("`{section}`: {err}")))?;
    Ok(())
}

/// The display-name rules shared by the named registries.
///
/// A name is required (an unnamed record cannot be selected), must not be padded (a
/// padded name selects differently from how it looks, exactly as a padded id does),
/// and must be unique within its registry, compared **case-folded**: the point is
/// that a user typing a name selects exactly one record, and a user does not tell
/// `Platform` from `platform`. The stored spelling is kept verbatim. `noun` is the
/// word the error uses for the kind of record (`project`, `epic`).
pub(crate) fn validate_display_name(
    section: &str,
    id: &str,
    name: &str,
    noun: &str,
    seen: &mut HashSet<String>,
) -> Result<()> {
    if name.trim().is_empty() {
        return Err(TixError::Config(format!(
            "`{section}.{id}.name` must not be blank"
        )));
    }
    if name.trim() != name {
        return Err(TixError::Config(format!(
            "`{section}.{id}.name` has leading or trailing whitespace"
        )));
    }
    if !seen.insert(name.to_lowercase()) {
        return Err(TixError::Config(format!(
            "`{section}.{id}.name` (`{name}`) must be unique; another {noun} already uses it"
        )));
    }
    Ok(())
}

/// Optional text that is present but blank is a typo, and silence about it is the one
/// thing a config loader should not offer. Shared by the named registries, including
/// the name-keyed reference fields (`lead`, `owner`, `milestone`, `cycle`).
fn validate_optional_text(section: &str, id: &str, fields: &[(&str, Option<&str>)]) -> Result<()> {
    for (field, value) in fields {
        if value.is_some_and(|v| v.trim().is_empty()) {
            return Err(TixError::Config(format!(
                "`{section}.{id}.{field}` must not be blank when present"
            )));
        }
    }
    Ok(())
}

/// The shared date rule for a registry record: `YYYY-MM-DD`, with
/// `due_date >= start_date`, via [`crate::model::validate_issue_dates`], wrapped so
/// the message names the record the way the rest of this module names its keys.
fn validate_record_dates(
    section: &str,
    id: &str,
    start_date: Option<&str>,
    due_date: Option<&str>,
) -> Result<()> {
    crate::model::validate_issue_dates(start_date, due_date)
        .map_err(|err| TixError::Config(format!("`{section}.{id}`: {err}")))
}

/// Per-project validation for `[projects.<project-id>]` (FR-001, C-001, C-002).
///
/// Every rule here is the shared one: the key must be a valid stable [`ProjectId`]
/// (that is what keeps a rename from breaking an association, and what keeps the key
/// safe as a TOML table header); the display `name` is required, unpadded and unique
/// within the registry, since a user types the name and two projects answering to one
/// name would be ambiguous; optional text fields are refused when present but blank;
/// dates go through the shared rule. See the helpers for the reasoning.
fn validate_projects(projects: &IndexMap<String, ProjectConfiguration>) -> Result<()> {
    let mut seen_names: HashSet<String> = HashSet::new();
    for (id, project) in projects {
        validate_registry_key::<ProjectId>("projects", id)?;
        validate_display_name("projects", id, &project.name, "project", &mut seen_names)?;
        validate_optional_text(
            "projects",
            id,
            &[
                ("description", project.description.as_deref()),
                ("status", project.status.as_deref()),
                ("lead", project.lead.as_deref()),
            ],
        )?;
        validate_record_dates(
            "projects",
            id,
            project.start_date.as_deref(),
            project.due_date.as_deref(),
        )?;
    }
    Ok(())
}

/// Per-epic validation for `[epics.<epic-id>]` (FR-001, FR-003, C-002, C-003, C-004).
///
/// The structural half is exactly the project registry's, through the shared helpers:
/// a valid stable [`EpicId`] key, a non-blank unique display name, present-but-blank
/// optional text refused, and the shared date rule — plus, new here, a **positive**
/// `weight`. A non-positive weight is a typo with a clear intent, and a relative size
/// has no meaning at or below zero.
///
/// The reference fields are validated for **shape** only. A `parent` must be a
/// well-formed [`EpicId`] and must not name the record's own key; every `projects`
/// entry must be a well-formed [`ProjectId`]; `milestone` and `cycle` must be
/// non-blank names — the same name-keyed references the existing registries use.
/// Whether those targets **exist** is deliberately not decided here: cross-record
/// resolution belongs to the epic service, and a parent that names an epic which was
/// deleted (or a project that never existed) must stay loadable and diagnosable
/// (C-005). A cycle across several parent records is likewise not checkable from a
/// single record; it belongs to the service and to `tix lint`.
fn validate_epics(epics: &IndexMap<String, EpicConfiguration>) -> Result<()> {
    let mut seen_names: HashSet<String> = HashSet::new();
    for (id, epic) in epics {
        validate_registry_key::<EpicId>("epics", id)?;
        validate_display_name("epics", id, &epic.name, "epic", &mut seen_names)?;
        validate_optional_text(
            "epics",
            id,
            &[
                ("description", epic.description.as_deref()),
                ("status", epic.status.as_deref()),
                ("owner", epic.owner.as_deref()),
                ("milestone", epic.milestone.as_deref()),
                ("cycle", epic.cycle.as_deref()),
            ],
        )?;
        validate_record_dates(
            "epics",
            id,
            epic.start_date.as_deref(),
            epic.due_date.as_deref(),
        )?;
        if let Some(weight) = epic.weight
            && weight <= 0
        {
            return Err(TixError::Config(format!(
                "`epics.{id}.weight` must be a positive integer; got {weight}"
            )));
        }
        if let Some(parent) = epic.parent.as_deref() {
            EpicId::new(parent)
                .map_err(|err| TixError::Config(format!("`epics.{id}.parent`: {err}")))?;
            if parent == id {
                return Err(TixError::Config(format!(
                    "`epics.{id}.parent` must not name the epic itself"
                )));
            }
        }
        for reference in &epic.projects {
            ProjectId::new(reference)
                .map_err(|err| TixError::Config(format!("`epics.{id}.projects`: {err}")))?;
        }
    }
    Ok(())
}

/// Every field name [`InitiativeConfiguration`] declares.
///
/// This is the set serde itself treats as **known** for the record — the fields that
/// survive through the typed struct rather than being swept into the flattened
/// `extensions` map. It must stay in step with `InitiativeConfiguration`: add a field
/// there and add it here, or a later shadowing check would let the new name through.
/// It is listed in one place, and checked in [`validate_initiatives`], because that is
/// the single validation every write goes through.
const INITIATIVE_KNOWN_FIELDS: &[&str] = &[
    "name",
    "outcome",
    "owner",
    "status",
    "priority",
    "labels",
    "target_date",
    "projects",
    "epics",
    "milestones",
];

/// Per-initiative validation for `[initiatives.<initiative-id>]` (FR-001, C-001, C-002).
///
/// The structural half is the project and epic registries' own, through the shared
/// helpers: a valid stable [`InitiativeId`] key, a non-blank unique (case-folded)
/// display name, present-but-blank optional text refused, and the shared calendar
/// rule for `target_date` ([`crate::model::validate_date`] — the same rule issues
/// use, so the format has one owner). Each `labels` entry must be non-blank.
///
/// The reference fields are validated for **shape** only. Every `projects` entry must
/// be a well-formed [`ProjectId`] and every `epics` entry a well-formed [`EpicId`],
/// because that is what a registry must hold to load; every `milestones` entry must
/// be a non-blank **name**, the name-keyed reference the existing milestone registry
/// uses. Whether those targets **exist** is deliberately not decided here:
/// cross-record resolution belongs to the initiative service (WP03) and `tix lint`,
/// and a dangling reference caused by a deletion must stay loadable and diagnosable
/// (C-005). Repeated entries are not refused here — the write path collapses them —
/// because identity is the concern, not redundancy.
///
/// A preserved extension key must not **shadow** a built-in field. A file can never
/// deliver one — serde matches the known field first, so the extension map is only
/// ever the leftovers — but the public write path can inject one through
/// [`crate::roadmap::registry::InitiativeExtensions`], and `toml` would then serialize
/// the same table key twice with no duplicate detection: the write would appear to
/// succeed while the next load failed on `duplicate key`, diverging the file from the
/// caller's in-memory config. Refusing it here is what keeps
/// "an accepted change persists the complete record" true.
fn validate_initiatives(initiatives: &IndexMap<String, InitiativeConfiguration>) -> Result<()> {
    let mut seen_names: HashSet<String> = HashSet::new();
    for (id, initiative) in initiatives {
        validate_registry_key::<InitiativeId>("initiatives", id)?;
        validate_display_name(
            "initiatives",
            id,
            &initiative.name,
            "initiative",
            &mut seen_names,
        )?;
        validate_optional_text(
            "initiatives",
            id,
            &[
                ("outcome", initiative.outcome.as_deref()),
                ("owner", initiative.owner.as_deref()),
                ("status", initiative.status.as_deref()),
            ],
        )?;
        for key in initiative.extensions.keys() {
            if INITIATIVE_KNOWN_FIELDS.contains(&key) {
                return Err(TixError::Config(format!(
                    "`initiatives.{id}.{key}` collides with a built-in field; rename the extension key"
                )));
            }
        }
        if let Some(date) = initiative.target_date.as_deref() {
            if !crate::model::validate_date(date) {
                return Err(TixError::Config(format!(
                    "`initiatives.{id}.target_date` (`{date}`) must be a `YYYY-MM-DD` calendar date"
                )));
            }
        }
        for label in &initiative.labels {
            if label.trim().is_empty() {
                return Err(TixError::Config(format!(
                    "`initiatives.{id}.labels` must not contain a blank value"
                )));
            }
        }
        for reference in &initiative.projects {
            ProjectId::new(reference)
                .map_err(|err| TixError::Config(format!("`initiatives.{id}.projects`: {err}")))?;
        }
        for reference in &initiative.epics {
            EpicId::new(reference)
                .map_err(|err| TixError::Config(format!("`initiatives.{id}.epics`: {err}")))?;
        }
        for reference in &initiative.milestones {
            if reference.trim().is_empty() {
                return Err(TixError::Config(format!(
                    "`initiatives.{id}.milestones` must not contain a blank value"
                )));
            }
        }
    }
    Ok(())
}

/// Per-cycle validation (NFR-003): non-blank name, parseable dates, and
/// `due_date >= start_date` when both are present.
fn validate_cycle(name: &str, cycle: &PlanningCycle) -> Result<()> {
    if name.trim().is_empty() {
        return Err(TixError::Config("`cycles.<name>` must not be blank".into()));
    }
    if let Some(start) = &cycle.start_date {
        if !crate::model::validate_date(start) {
            return Err(TixError::Config(format!(
                "`cycles.{name}.start_date` (`{start}`) must be a `YYYY-MM-DD` calendar date"
            )));
        }
    }
    if let Some(due) = &cycle.due_date {
        if !crate::model::validate_date(due) {
            return Err(TixError::Config(format!(
                "`cycles.{name}.due_date` (`{due}`) must be a `YYYY-MM-DD` calendar date"
            )));
        }
        if let Some(start) = &cycle.start_date
            && due.as_str() < start.as_str()
        {
            return Err(TixError::Config(format!(
                "`cycles.{name}.due_date` (`{due}`) must be `>= start_date` (`{start}`)"
            )));
        }
    }
    Ok(())
}

/// Per-template validation for `[templates.<name>]` (`tui-new-issue-mode`).
///
/// The rules exist because of how a template reaches the form: `labels`,
/// `cycles` and `milestones` are joined with `,` into their single text rows and
/// split again at submit, so a value that itself contains a comma would silently
/// become two values the user never typed. A blank label is refused for the same
/// reason the form filters blanks — a template that "sets" an empty label sets
/// nothing. Dates follow the cycle rules verbatim.
fn validate_template(name: &str, template: &IssueTemplate) -> Result<()> {
    if name.trim().is_empty() {
        return Err(TixError::Config(
            "`templates` must not contain a blank name".into(),
        ));
    }
    for (field, values) in [
        ("labels", &template.labels),
        ("cycles", &template.cycles),
        ("milestones", &template.milestones),
    ] {
        for value in values {
            if value.trim().is_empty() {
                return Err(TixError::Config(format!(
                    "`templates.{name}.{field}` must not contain a blank value"
                )));
            }
            if value.contains(',') {
                return Err(TixError::Config(format!(
                    "`templates.{name}.{field}` value `{value}` must not contain a comma \
                     — the form joins these with `,`"
                )));
            }
        }
    }
    if let Some(start) = &template.start_date
        && !crate::model::validate_date(start)
    {
        return Err(TixError::Config(format!(
            "`templates.{name}.start_date` (`{start}`) must be a `YYYY-MM-DD` calendar date"
        )));
    }
    if let Some(due) = &template.due_date {
        if !crate::model::validate_date(due) {
            return Err(TixError::Config(format!(
                "`templates.{name}.due_date` (`{due}`) must be a `YYYY-MM-DD` calendar date"
            )));
        }
        if let Some(start) = &template.start_date
            && due.as_str() < start.as_str()
        {
            return Err(TixError::Config(format!(
                "`templates.{name}.due_date` (`{due}`) must be `>= start_date` (`{start}`)"
            )));
        }
    }
    Ok(())
}

/// Per-configuration validation (NFR-003): non-empty unique non-blank
/// columns, `done_column` ⊆ columns, `hidden_columns` ⊆ columns.
/// The `[categories]` section's own rules (contract §2, §4).
///
/// Both are refusals of a *default*, which is the escalation the contract names:
/// a default naming a category outside the vocabulary is a typo, and a default
/// that resolves to `completed` would silently mark every unmapped column done.
fn validate_categories(categories: &CategoryConfig) -> Result<()> {
    if categories.order.is_empty() {
        return Err(TixError::Config(
            "`categories.order` must not be empty — it is the global vocabulary".into(),
        ));
    }
    for key in &categories.order {
        if !CATEGORY_KEYS.contains(&key.as_str()) {
            return Err(TixError::Config(format!(
                "unknown_category: `categories.order` names `{key}`, which is not in the \
                 global vocabulary ({}). The vocabulary is fixed and global (C-002); a \
                 board maps columns into it and does not define it.",
                CATEGORY_KEYS.join(", ")
            )));
        }
    }
    if !categories.contains(&categories.default) {
        return Err(TixError::Config(format!(
            "unknown_category: `categories.default` is `{}`, which is not in \
             `categories.order`",
            categories.default
        )));
    }
    if categories.default == COMPLETE_CATEGORY {
        return Err(TixError::Config(format!(
            "`categories.default` may not be `{COMPLETE_CATEGORY}`. Every column \
             without an explicit mapping would resolve to complete, which changes \
             completion meaning by accident. Map the completing column explicitly \
             instead."
        )));
    }
    Ok(())
}

/// Per-board mapping validation (contract §3).
///
/// A board either has a completion category or is an explicit configuration
/// error; there is no silent "nothing completes". A *missing* mapping is never an
/// error — it resolves by the safe default — because erroring would reject every
/// existing custom configuration (NFR-003, C-007).
fn validate_category_map(
    name: &str,
    board: &BoardConfiguration,
    categories: &CategoryConfig,
) -> Result<()> {
    for (column, key) in &board.category_map {
        if !board.columns.iter().any(|c| c == column) {
            return Err(TixError::Config(format!(
                "mapping_for_unknown_column: `kanban.{name}.category_map` maps \
                 `{column}`, which is not one of the board's columns ({})",
                board.columns.join(", ")
            )));
        }
        if !categories.contains(key) {
            return Err(TixError::Config(format!(
                "unknown_category: `kanban.{name}.category_map` maps `{column}` to \
                 `{key}`, which is not in the vocabulary ({})",
                categories.order.join(", ")
            )));
        }
    }
    // Only a board that *declares* a map is held to naming a completion column. A
    // board with no map gets `done_column` -> `completed` in `category_for`, so
    // counting completions here would reject every legacy config.
    if board.category_map.is_empty() {
        return Ok(());
    }
    let completers: Vec<&String> = board
        .category_map
        .iter()
        .filter(|(_, key)| key.as_str() == COMPLETE_CATEGORY)
        .map(|(column, _)| column)
        .collect();
    match completers.as_slice() {
        [] => Err(TixError::Config(format!(
            "missing_completion_category: `kanban.{name}.category_map` maps no column \
             to `{COMPLETE_CATEGORY}` ({} mapped). Without one, no card on this board \
             is ever complete — map exactly one column to it.",
            board.category_map.len()
        ))),
        [_only] => Ok(()),
        many => Err(TixError::Config(format!(
            "`kanban.{name}.category_map` maps {} columns to `{COMPLETE_CATEGORY}` \
             ({}); exactly one column may complete work",
            many.len(),
            many.iter()
                .map(|c| c.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ))),
    }
}

fn validate_board(name: &str, board: &BoardConfiguration) -> Result<()> {
    if board.columns.is_empty() {
        return Err(TixError::Config(format!(
            "`kanban.{name}.columns` must not be empty"
        )));
    }
    if board.columns.iter().any(|c| c.trim().is_empty()) {
        return Err(TixError::Config(format!(
            "`kanban.{name}.columns` must not contain blank names"
        )));
    }
    let mut seen: HashSet<&str> = HashSet::new();
    for column in &board.columns {
        if !seen.insert(column.as_str()) {
            return Err(TixError::Config(format!(
                "`kanban.{name}.columns` must be unique; found duplicate `{column}`"
            )));
        }
    }
    if let Some(done) = &board.done_column
        && !board.columns.contains(done)
    {
        return Err(TixError::Config(format!(
            "`kanban.{name}.done_column` (`{done}`) must be one of the configured columns"
        )));
    }
    for hidden in &board.hidden_columns {
        if !board.columns.contains(hidden) {
            return Err(TixError::Config(format!(
                "`kanban.{name}.hidden_columns` (`{hidden}`) must be a subset of `columns`"
            )));
        }
    }
    if board.title_lines == 0 {
        return Err(TixError::Config(format!(
            "`kanban.{name}.title_lines` must be at least 1"
        )));
    }
    // The WIP schema validates itself against this board's own columns, so a limit
    // can only ever be attached to a column the board declares (T001/T003).
    board.wip.validate(name, &board.columns)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use tempfile::TempDir;

    use crate::templates::{
        PromptKind, ReferenceKind, Template, TemplateDefaults, TemplatePrompt, TemplateReference,
        TemplateScope,
    };

    /// The canonical legacy `tix.toml`: `toml`'s pretty form, with no
    /// board field that already equals the loader's value and no empty
    /// `[export]`. A save must reproduce it byte-for-byte (#1415).
    const LEGACY_PRETTY_BOARD: &str = r#"issues_dir = "docs/issues"

[kanban.default]
columns = [
    "todo",
    "in progress",
    "in review",
    "done",
]
"#;

    fn write_toml(dir: &Path, contents: &str) -> PathBuf {
        let path = dir.join("tix.toml");
        std::fs::write(&path, contents).unwrap();
        path
    }

    #[test]
    fn starter_config_carries_a_working_inbox() {
        let config = Config::starter();
        config
            .validate()
            .expect("the config `tix init` writes must load");

        let board = config.default_config();
        for column in [
            "triage",
            "todo",
            "in progress",
            "in review",
            "done",
            "wontfix",
        ] {
            assert!(
                board.columns.iter().any(|c| c == column),
                "the starter board is missing `{column}`: {:?}",
                board.columns
            );
        }

        let triage = config
            .triage
            .as_ref()
            .expect("the starter config has an inbox");
        assert_eq!(triage.entry_status.as_deref(), Some("triage"));
        assert_eq!(triage.accepted_status.as_deref(), Some("todo"));
        assert_eq!(triage.declined_status.as_deref(), Some("wontfix"));
        // Left unset: the default *is* the entry column, and a default that is never
        // written cannot drift from the meaning it stands for.
        assert_eq!(triage.effective_deferred_status(), Some("triage"));

        // The one mapping triage requires, plus the completion column.
        assert_eq!(
            board.category_map.get("wontfix").map(String::as_str),
            Some("canceled")
        );
        assert_eq!(
            board.category_map.get("done").map(String::as_str),
            Some("completed")
        );
        // The working columns stay **unmapped** on purpose: declaring a map makes the
        // board an explicit policy, and adjacency then refuses a *backwards* move with
        // no override to offer — `in progress -> todo` is a move people make daily.
        // Left out, they all resolve to the same safe default, so movement among them
        // stays free while `done`/`wontfix` remain terminal facts.
        for column in ["triage", "todo", "in progress", "in review"] {
            assert!(
                !board.category_map.contains_key(column),
                "`{column}` must stay unmapped, or adjacency will refuse work moving back"
            );
        }
    }

    #[test]
    fn repos_and_parent_repo_load_round_trip_and_resolve() {
        let tmp = TempDir::new().unwrap();
        // `parent_repo` must precede the `[repos]` table, or TOML would file it
        // inside that table.
        let raw = "issues_dir = \"docs/issues\"\n\
                   parent_repo = \"../parent\"\n\n\
                   [repos]\n\
                   tix = \"../tix\"\n\
                   website = \"child/website\"\n";
        let path = write_toml(tmp.path(), raw);
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.repos.len(), 2);
        assert_eq!(cfg.repos["tix"], PathBuf::from("../tix"));
        assert_eq!(cfg.repos["website"], PathBuf::from("child/website"));
        assert_eq!(cfg.parent_repo(), Some(Path::new("../parent")));

        // A save keeps both, and they re-load identically.
        cfg.save(&path).unwrap();
        let reread = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reread.repos, cfg.repos, "repos round-trip");
        assert_eq!(
            reread.parent_repo(),
            cfg.parent_repo(),
            "parent round-trips"
        );

        // Relative paths resolve against a base, absolute ones are left alone.
        let mut resolved = cfg.clone();
        resolved.resolve_repo_paths(Path::new("/root"));
        assert_eq!(resolved.repos["tix"], PathBuf::from("/root/../tix"));
        assert_eq!(
            resolved.repos["website"],
            PathBuf::from("/root/child/website")
        );
        assert_eq!(resolved.parent_repo(), Some(Path::new("/root/../parent")));
        let mut absolute = Config::default();
        absolute.repos.insert("x".into(), PathBuf::from("/abs/x"));
        absolute.parent_repo = Some(PathBuf::from("/abs/parent"));
        absolute.resolve_repo_paths(Path::new("/root"));
        assert_eq!(absolute.repos["x"], PathBuf::from("/abs/x"));
        assert_eq!(absolute.parent_repo(), Some(Path::new("/abs/parent")));
    }

    #[test]
    fn types_rename_and_type_colors() {
        let tmp = TempDir::new().unwrap();
        // The pre-#1530 key still loads (serde alias) but serializes as `types`.
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\ncustom_types = [\"bug\", \"epic\"]\n",
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.types(), vec!["bug", "epic"]);
        cfg.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(after.contains("types = ["), "{after}");
        assert!(!after.contains("custom_types"), "{after}");

        // Every shipped type has a default color; `[type_colors]` overrides it,
        // matched case-insensitively. An unknown type has none.
        let defaults = Config::default();
        assert_eq!(defaults.type_color("bug").as_deref(), Some("red"));
        assert_eq!(defaults.type_color("BUG").as_deref(), Some("red"));
        assert_eq!(defaults.type_color("nonsense"), None);
        let mut overridden = Config::default();
        overridden.type_colors.insert("bug".into(), "cyan".into());
        assert_eq!(overridden.type_color("Bug").as_deref(), Some("cyan"));
    }

    #[test]
    fn a_blank_repo_path_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[repos]\ntix = \"\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("repos.tix"), "got {err}");
    }

    #[test]
    fn an_empty_repos_section_is_not_written() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"docs/issues\"\n");
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        cfg.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(
            !after.contains("[repos]") && !after.contains("parent_repo"),
            "an untouched config gains no repos keys on save: {after}"
        );
    }

    #[test]
    fn defaults_match_contract() {
        let c = Config::default();
        let board = c.default_config();
        assert_eq!(board.columns, ["todo", "in progress", "in review", "done"]);
        assert_eq!(board.done_column.as_deref(), Some("done"));
        assert_eq!(board.hidden_columns, Vec::<String>::new());
        assert!(!board.show_mismatch);
        assert!(board.wrap_titles);
        assert_eq!(board.title_lines, 3);
        assert_eq!(board.card_order, [] as [std::string::String; 0]);
        assert_eq!(board.order_by, OrderBy::CreatedAtDesc);
        assert_eq!(c.issues_dir, PathBuf::from("docs/issues"));
        assert_eq!(c.editor, None);
        assert_eq!(c.state.next_number, 0);
        assert_eq!(c.export.gitlab, None);
        assert_eq!(c.export.linear, None);
    }

    /// `decision-pending` is a builtin: it resolves with no `labels` key at all,
    /// and `tix init` writes no key for it.
    #[test]
    fn decision_pending_is_a_builtin_label_that_needs_no_key() {
        let bare = Config::default();
        assert_eq!(bare.labels, None);
        assert_eq!(bare.labels(), vec!["decision-pending".to_string()]);

        // The starting point does not declare it either, so `tix init` emits no
        // `labels` key.
        let starter = Config::starter();
        assert_eq!(starter.labels, None);
        assert_eq!(starter.labels(), vec!["decision-pending".to_string()]);
        for written in [
            toml::to_string_pretty(&bare).unwrap(),
            toml::to_string_pretty(&starter).unwrap(),
        ] {
            assert!(
                !written.contains("labels ="),
                "no labels key is written:\n{written}"
            );
        }

        // A project may declare extras; they follow the builtins, deduplicated.
        let configured = Config {
            labels: Some(vec!["decision-pending".into(), "spec-kitty".into()]),
            ..Config::default()
        };
        assert_eq!(
            configured.labels(),
            vec!["decision-pending".to_string(), "spec-kitty".to_string()]
        );
    }

    #[test]
    fn load_returns_defaults_when_file_absent() {
        let tmp = TempDir::new().unwrap();
        let cfg = Config::load(tmp.path()).unwrap();
        assert_eq!(cfg.state.next_number, 0);
        assert_eq!(cfg.default_config().columns.len(), 4);
    }

    #[test]
    fn load_synthesizes_default_config_when_kanban_section_missing() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"docs/issues\"\n");
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.kanban.configurations.len(), 1);
        assert!(cfg.kanban.configurations.contains_key("default"));
        assert_eq!(cfg.default_config().columns.len(), 4);
    }

    #[test]
    fn load_parses_state_and_keeps_editor_and_remote_targets() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "tickets"
editor = "nvim"

[kanban.default]
columns = ["todo", "done"]
done_column = "done"

[state]
next_number = 17

[export.gitlab]
project = "acme/tix"
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| panic!("no token, no warning")).unwrap();
        assert_eq!(
            cfg.kanban.configurations.get("default").unwrap().columns,
            ["todo", "done"]
        );
        assert_eq!(cfg.issues_dir, PathBuf::from("tickets"));
        assert_eq!(cfg.editor.as_deref(), Some("nvim"));
        assert_eq!(cfg.state.next_number, 17);
        assert_eq!(
            cfg.export.gitlab.unwrap().project.as_deref(),
            Some("acme/tix")
        );
        assert_eq!(cfg.export.linear, None);
    }

    #[test]
    fn viewer_is_parsed_and_blank_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"tickets\"\nviewer = \"less\"\n");
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.viewer.as_deref(), Some("less"));

        let blank = write_toml(tmp.path(), "issues_dir = \"tickets\"\nviewer = \"  \"\n");
        let err = Config::load_with_warning(&blank, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("viewer"), "{err}");
    }

    #[test]
    fn viewer_is_omitted_from_the_file_when_unset() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("tix.toml");
        let mut config = Config::default();
        config.save(&path).unwrap();
        assert!(
            !std::fs::read_to_string(&path).unwrap().contains("viewer"),
            "an unset viewer writes no key"
        );

        config.viewer = Some("less".to_string());
        config.save(&path).unwrap();
        assert!(
            std::fs::read_to_string(&path)
                .unwrap()
                .contains(r#"viewer = "less""#),
            "a set viewer round-trips"
        );
    }

    #[test]
    fn empty_columns_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "[kanban.scratch]\ncolumns = []\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("kanban.scratch.columns"));
    }

    #[test]
    fn duplicate_columns_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"todo\"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("duplicate"));
    }

    #[test]
    fn blank_column_name_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \" \"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
    }

    #[test]
    fn done_column_must_be_in_columns() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"in progress\"]\ndone_column = \"in review\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("kanban.scratch.done_column"));
    }

    #[test]
    fn hidden_columns_must_be_subset_of_columns() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\nhidden_columns = [\"nope\"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("kanban.scratch.hidden_columns"));
    }

    #[test]
    fn hidden_done_column_loads_fine() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\nhidden_columns = [\"done\"]\n",
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let board = cfg.kanban.configurations.get("scratch").unwrap();
        assert_eq!(board.done_column.as_deref(), Some("done"));
        assert_eq!(board.hidden_columns, ["done"]);
    }

    #[test]
    fn legacy_top_level_keys_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "columns = [\"todo\", \"done\"]\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("tix.toml"));
        assert!(err.to_string().contains("columns"));
    }

    #[test]
    fn token_warning_fires_once_per_remote_with_token() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"[export.gitlab]
project = "a/b"
token = "gl-secret"

[export.linear]
team = "Eng"
token = "lin-secret"
"#,
        );
        let mut warnings: Vec<String> = Vec::new();
        let cfg = Config::load_with_warning(&path, |w| warnings.push(w.to_string())).unwrap();
        assert_eq!(warnings.len(), 2);
        assert!(warnings[0].contains("GITLAB_TOKEN"));
        assert!(warnings[1].contains("LINEAR_TOKEN"));
        // token values must never leak into the warning
        for w in &warnings {
            assert!(!w.contains("secret"));
        }
        assert_eq!(
            cfg.export.gitlab.unwrap().token.as_deref(),
            Some("gl-secret")
        );
    }

    #[test]
    fn no_token_means_no_warning() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"docs/issues\"\n");
        let mut fired = false;
        Config::load_with_warning(&path, |_| fired = true).unwrap();
        assert!(!fired);
    }

    #[test]
    fn save_never_writes_the_state_section() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        // Simulate a legacy load: `[state].next_number` is kept in memory
        // but must never be written back out (issue #52).
        let mut cfg = Config::default();
        cfg.state.next_number = 42;
        cfg.save(&path).unwrap();

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.state.next_number, 0, "state is never persisted");
        assert_eq!(
            reloaded.default_config().columns,
            cfg.default_config().columns
        );

        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(
            !on_disk.contains("next_number"),
            "next_number leaked into tix.toml:\n{on_disk}"
        );
        assert!(
            !on_disk.contains("[state]"),
            "state section written:\n{on_disk}"
        );
    }

    #[test]
    fn multi_config_roundtrip_preserves_declaration_order() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.release]
columns = ["planned", "in progress", "done"]
done_column = "done"
show_mismatch = true

[kanban.personal]
columns = ["todo", "done"]
done_column = "done"
hidden_columns = ["done"]
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let names: Vec<&str> = cfg.configs().map(|(n, _)| n).collect();
        assert_eq!(names, ["release", "personal"]);

        // default_config falls back to the first declared when no "default".
        assert_eq!(
            cfg.default_config().columns,
            ["planned", "in progress", "done"]
        );

        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            cfg, reloaded,
            "order and values survive save/load round trip"
        );
        let names2: Vec<&str> = reloaded.configs().map(|(n, _)| n).collect();
        assert_eq!(names2, ["release", "personal"]);
    }

    #[test]
    fn save_never_serializes_tokens_back_out() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let mut cfg = Config::default();
        cfg.export.gitlab = Some(RemoteConfig {
            token: Some("secret".into()),
            project: Some("a/b".into()),
            ..RemoteConfig::default()
        });
        cfg.save(&path).unwrap();

        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(
            !on_disk.contains("secret"),
            "token leaked to disk:\n{on_disk}"
        );
        assert!(
            on_disk.contains("a/b"),
            "non-secret fields survive:\n{on_disk}"
        );

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.export.gitlab.unwrap().token, None);
    }

    #[test]
    fn save_is_atomic_and_leaves_no_temp_file() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        Config::default().save(&path).unwrap();
        let entries: Vec<_> = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].file_name().to_string_lossy(), "tix.toml");
    }

    #[test]
    fn default_loadwrites_are_idempotent() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let cfg = Config::default();
        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg, reloaded);
    }

    #[test]
    fn effective_done_column_falls_back_to_last() {
        let board = BoardConfiguration {
            columns: vec!["todo".into(), "later".into()],
            done_column: None,
            ..Default::default()
        };
        assert_eq!(board.effective_done_column(), Some("later"));

        let with_done = BoardConfiguration {
            columns: vec!["todo".into(), "done".into(), "later".into()],
            done_column: None,
            ..Default::default()
        };
        assert_eq!(with_done.effective_done_column(), Some("done"));
    }

    #[test]
    fn project_root_walks_up_the_tree() {
        let tmp = TempDir::new().unwrap();
        let nested = tmp.path().join("a").join("b");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::write(tmp.path().join("tix.toml"), "issues_dir = \"tix\"\n").unwrap();

        assert_eq!(
            Config::project_root(&nested),
            Some(tmp.path().to_path_buf())
        );
        assert_eq!(
            Config::project_root(tmp.path()),
            Some(tmp.path().to_path_buf())
        );
    }

    #[test]
    fn project_root_is_none_when_no_toml_exists() {
        let tmp = TempDir::new().unwrap();
        assert_eq!(Config::project_root(tmp.path()), None);
    }

    #[test]
    fn order_by_parses_all_names_and_defaults_to_desc() {
        let tmp = TempDir::new().unwrap();
        for name in ["created_at_desc", "created_at_asc", "none"] {
            let path = write_toml(
                tmp.path(),
                &format!(
                    "[kanban.x]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\norder_by = \"{name}\"\n"
                ),
            );
            let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
            let board = cfg.kanban.configurations.get("x").unwrap();
            assert_eq!(board.order_by.as_str(), name);
        }
        assert_eq!(OrderBy::default(), OrderBy::CreatedAtDesc);
        assert_eq!(OrderBy::CreatedAtDesc.next(), OrderBy::CreatedAtAsc);
        assert_eq!(OrderBy::CreatedAtAsc.next(), OrderBy::None);
        assert_eq!(OrderBy::None.next(), OrderBy::CreatedAtDesc);
    }

    #[test]
    fn zero_title_lines_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\ntitle_lines = 0\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(
            err.to_string().contains("kanban.scratch.title_lines"),
            "error names the offending field: {err}"
        );
    }

    #[test]
    fn unknown_order_by_rejected_as_config_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.scratch]\ncolumns = [\"todo\", \"done\"]\ndone_column = \"done\"\norder_by = \"bogus\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
    }

    #[test]
    fn board_without_display_keys_loads_default_display_settings() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[kanban.default]\ncolumns = [\"todo\", \"done\"]\n",
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let board = cfg.default_config();
        assert!(board.wrap_titles);
        assert_eq!(board.title_lines, 3);
        assert_eq!(board.order_by, OrderBy::CreatedAtDesc);
    }

    #[test]
    fn display_settings_roundtrip_through_save() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let mut cfg = Config::default();
        {
            let board = cfg.kanban.configurations.get_mut("default").unwrap();
            board.wrap_titles = false;
            board.title_lines = 5;
            board.order_by = OrderBy::None;
        }
        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded, cfg,
            "display settings survive save/load round trip"
        );
        let on_disk = std::fs::read_to_string(&path).unwrap();
        for key in ["wrap_titles", "title_lines", "order_by"] {
            assert!(on_disk.contains(key), "missing `{key}` in:\n{on_disk}");
        }
    }

    #[test]
    fn manual_card_order_roundtrips_through_save() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let mut cfg = Config::default();
        {
            let board = cfg.kanban.configurations.get_mut("default").unwrap();
            board.card_order = vec!["a.md".into(), "b.md".into()];
        }
        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded
                .kanban
                .configurations
                .get("default")
                .unwrap()
                .card_order,
            vec!["a.md".to_string(), "b.md".to_string()]
        );
        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(
            on_disk.contains("card_order"),
            "missing card_order in:\n{on_disk}"
        );
    }

    #[test]
    fn planning_defaults_match_contract() {
        let c = Config::default();
        assert_eq!(c.planning.cycle_number, 1);
        assert_eq!(c.planning.default_cycle, None);
        assert_eq!(c.planning.default_milestone, None);
        assert_eq!(c.planning.default_team, None);
        assert!(c.teams.is_empty());
        assert!(c.cycles.is_empty());
        assert_eq!(c.milestones_dir, None);
        assert_eq!(c.milestones_dir(), Path::new("docs/milestones"));
    }

    #[test]
    fn planning_sections_roundtrip_and_preserve_declaration_order() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"
milestones_dir = "docs/milestones"

[planning]
cycle_number = 1
default_cycle = "Cycle 1"
default_milestone = "Backlog"
default_team = "default"

[cycles."Cycle 1"]

[cycles."Cycle 2"]
start_date = "2026-09-21"
due_date = "2026-09-30"

[teams.default]
members = ["Herb Mason <herb@example.com>", "@alice"]

[teams.platform]
members = ["bob"]
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.planning.cycle_number, 1);
        assert_eq!(cfg.planning.default_cycle.as_deref(), Some("Cycle 1"));
        assert_eq!(cfg.planning.default_milestone.as_deref(), Some("Backlog"));
        assert_eq!(cfg.planning.default_team.as_deref(), Some("default"));
        assert_eq!(cfg.milestones_dir(), Path::new("docs/milestones"));

        // Names are map keys; declaration order is restored from headers.
        let cycles: Vec<&str> = cfg.cycles.keys().map(String::as_str).collect();
        assert_eq!(cycles, ["Cycle 1", "Cycle 2"]);
        let cycle2 = cfg.cycles.get("Cycle 2").unwrap();
        assert_eq!(cycle2.start_date.as_deref(), Some("2026-09-21"));
        assert_eq!(cycle2.due_date.as_deref(), Some("2026-09-30"));
        assert_eq!(cycle2.description, None);

        let teams: Vec<&str> = cfg.teams.keys().map(String::as_str).collect();
        assert_eq!(teams, ["default", "platform"]);
        assert_eq!(
            cfg.teams.get("default").unwrap().members,
            ["Herb Mason <herb@example.com>", "@alice"]
        );

        // Save then reload: order + values survive the round trip (NFR-002).
        cfg.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg, reloaded);
        assert_eq!(
            reloaded
                .cycles
                .keys()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            ["Cycle 1", "Cycle 2"]
        );
        assert_eq!(
            reloaded
                .teams
                .keys()
                .map(String::as_str)
                .collect::<Vec<_>>(),
            ["default", "platform"]
        );
    }

    // ---------------------------------------------------------------------
    // WP01 / T001-T005 — the category vocabulary and mapping
    // ---------------------------------------------------------------------

    const FULL_CATEGORIES: &str = r#"issues_dir = "docs/issues"

[categories]
order = ["backlog", "unstarted", "active", "blocked", "completed", "canceled"]
default = "unstarted"

[transitions]
terminal_locked = true

[kanban.default]
columns = ["triage", "wip", "review", "shipped"]
done_column = "shipped"
category_map = { triage = "backlog", wip = "active", review = "active", shipped = "completed" }

[export]
"#;

    #[test]
    fn category_sections_parse_and_default_sensibly() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), FULL_CATEGORIES);
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.categories.order, CATEGORY_KEYS);
        assert_eq!(cfg.categories.default, "unstarted");
        assert!(cfg.transitions.terminal_locked);

        let board = cfg.default_config();
        assert_eq!(
            board.category_map.get("shipped").map(String::as_str),
            Some("completed")
        );
        assert_eq!(
            board.category_map.get("triage").map(String::as_str),
            Some("backlog")
        );
    }

    #[test]
    fn category_sections_default_when_absent() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"docs/issues\"\n");
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        // A config omitting `[categories]` still works, off the built-in
        // vocabulary — T001's "sensible defaults".
        assert_eq!(cfg.categories, CategoryConfig::default());
        assert_eq!(cfg.transitions, TransitionConfig::default());
        assert!(cfg.categories.is_default(), "and is not written back");
        assert!(cfg.transitions.is_default());
    }

    #[test]
    fn deny_unknown_fields_rejects_an_unknown_key_in_each_new_section() {
        let tmp = TempDir::new().unwrap();
        let bad_categories = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[categories]\nnope = 1\n",
        );
        let err = Config::load_with_warning(&bad_categories, |_| {})
            .expect_err("an unknown key in [categories] must be refused");
        assert!(err.to_string().contains("unknown field"), "got: {err}");

        let tmp2 = TempDir::new().unwrap();
        let bad_transitions = write_toml(
            tmp2.path(),
            "issues_dir = \"docs/issues\"\n\n[transitions]\nnope = 1\n",
        );
        let err = Config::load_with_warning(&bad_transitions, |_| {})
            .expect_err("an unknown key in [transitions] must be refused");
        assert!(err.to_string().contains("unknown field"), "got: {err}");
    }

    #[test]
    fn a_configured_vocabulary_naming_an_unknown_key_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[categories]\norder = [\"backlog\", \"wontfix\"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .expect_err("the vocabulary is global and fixed; a new key is not a default");
        assert!(err.to_string().contains("unknown_category"), "got: {err}");
    }

    /// The escalation the contract names: a default that resolves to `completed`
    /// would mark every unmapped column done.
    #[test]
    fn a_default_of_completed_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[categories]\ndefault = \"completed\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .expect_err("a completion-changing default must be an escalation");
        let msg = err.to_string();
        assert!(msg.contains("may not be `completed`"), "got: {msg}");
    }

    #[test]
    fn a_default_outside_the_vocabulary_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[categories]\ndefault = \"wontfix\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).expect_err("got: none");
        assert!(err.to_string().contains("unknown_category"), "got: {err}");
    }

    /// The contract's central invariant: a board either has a completion category
    /// or is an explicit configuration error. There is no silent "nothing
    /// completes".
    #[test]
    fn a_mapped_board_with_no_completion_column_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["triage", "wip", "shipped"]
done_column = "shipped"
category_map = { triage = "backlog", wip = "active" }
"#,
        );
        let err = Config::load_with_warning(&path, |_| {}).expect_err("got: none");
        assert!(
            err.to_string().contains("missing_completion_category"),
            "got: {err}"
        );
    }

    #[test]
    fn a_board_with_two_completion_columns_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["shipped", "cancelled"]
done_column = "shipped"
category_map = { shipped = "completed", cancelled = "completed" }
"#,
        );
        let err = Config::load_with_warning(&path, |_| {}).expect_err("got: none");
        let msg = err.to_string();
        assert!(
            msg.contains("exactly one column may complete"),
            "got: {msg}"
        );
    }

    #[test]
    fn a_mapping_for_a_column_the_board_does_not_configure_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["triage", "shipped"]
done_column = "shipped"
category_map = { triage = "backlog", shipped = "completed", nope = "active" }
"#,
        );
        let err = Config::load_with_warning(&path, |_| {}).expect_err("got: none");
        assert!(
            err.to_string().contains("mapping_for_unknown_column"),
            "got: {err}"
        );
    }

    #[test]
    fn a_mapping_to_a_category_outside_the_vocabulary_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["triage", "shipped"]
done_column = "shipped"
category_map = { triage = "wontfix", shipped = "completed" }
"#,
        );
        let err = Config::load_with_warning(&path, |_| {}).expect_err("got: none");
        assert!(err.to_string().contains("unknown_category"), "got: {err}");
    }

    /// T003 step 5, and the boundary that keeps NFR-003 satisfiable: a configured
    /// column with **no** mapping is valid. It resolves by the safe default, and
    /// erroring here would reject every existing custom configuration.
    #[test]
    fn an_unmapped_column_is_accepted_and_resolves_by_the_safe_default() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["triage", "wip", "shipped"]
done_column = "shipped"
category_map = { shipped = "completed" }
"#,
        );
        let cfg =
            Config::load_with_warning(&path, |_| {}).expect("an unmapped column is not an error");
        let board = cfg.default_config();
        assert_eq!(board.category_for("triage", &cfg.categories), "unstarted");
        assert_eq!(board.category_for("wip", &cfg.categories), "unstarted");
        assert_eq!(board.category_for("shipped", &cfg.categories), "completed");
    }

    /// The legacy reconciliation, and the reason `missing_completion_category`
    /// cannot fire for a board with no map. Without it, a board with no
    /// `category_map` would map nothing to `completed` and be rejected — which
    /// would reject every legacy `tix.toml` the contract requires to load
    /// unchanged.
    #[test]
    fn a_legacy_board_with_no_map_takes_done_column_as_completed() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["todo", "in progress", "in review", "done"]
done_column = "done"
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {})
            .expect("a legacy board must load, and it does");
        let board = cfg.default_config();
        assert!(board.category_map.is_empty());
        assert_eq!(board.category_for("done", &cfg.categories), "completed");
        assert_eq!(board.category_for("todo", &cfg.categories), "unstarted");
        assert_eq!(
            board.category_for("in review", &cfg.categories),
            "unstarted",
            "and nothing else is silently complete"
        );
    }

    /// NFR-003 / C-007: the strongest guard. A defaulted configuration must not
    /// materialize — otherwise a default that writes new keys is exactly the
    /// "silent change" the requirement forbids.
    #[test]
    fn a_defaulted_config_gains_no_new_keys_on_save() {
        let tmp = TempDir::new().unwrap();
        let legacy = LEGACY_PRETTY_BOARD;
        let path = write_toml(tmp.path(), legacy);
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        cfg.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            after, legacy,
            "no `[categories]`, no `[transitions]`, no `category_map` may appear"
        );
    }

    /// An explicitly-defaulted board is **normalized**: every field equal to the
    /// loader's value is dropped on save, so the file converges on the canonical
    /// legacy form (#1415) rather than carrying redundant keys forever.
    #[test]
    fn explicit_default_board_keys_are_normalized_away_by_save() {
        let tmp = TempDir::new().unwrap();
        let explicit = r#"issues_dir = "docs/issues"

[kanban.default]
columns = [
    "todo",
    "in progress",
    "in review",
    "done",
]
done_column = "done"
hidden_columns = []
show_mismatch = false
wrap_titles = true
title_lines = 3
order_by = "created_at_desc"

[export]
"#;
        let path = write_toml(tmp.path(), explicit);
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        cfg.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            after, LEGACY_PRETTY_BOARD,
            "a redundant explicit default collapses to the canonical form"
        );
        for key in [
            "done_column",
            "hidden_columns",
            "show_mismatch",
            "wrap_titles",
            "title_lines",
            "order_by",
            "[export]",
        ] {
            assert!(!after.contains(key), "`{key}` must be omitted:\n{after}");
        }
        assert_eq!(
            cfg,
            Config::load_with_warning(&path, |_| {}).unwrap(),
            "and the collapsed form reloads to the same config"
        );
    }

    /// A board mapping with **no** `[categories]` section loads on the built-in
    /// vocabulary, and saving it back does not materialize the section.
    #[test]
    fn a_board_mapping_without_a_categories_section_uses_the_built_in_vocabulary() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["triage", "shipped"]
done_column = "shipped"
category_map = { triage = "backlog", shipped = "completed" }

[export]
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.categories, CategoryConfig::default());
        cfg.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(
            !after.contains("[categories]"),
            "the section must stay unmaterialized: {after}"
        );
        assert!(
            after.contains("category_map"),
            "while the board's own mapping survives: {after}"
        );
    }

    /// What round-trips is the **values** and the `order` vector, not the raw
    /// bytes: `category_map` serializes as a `[kanban.<name>.category_map]`
    /// sub-table with its keys emitted in whatever order the TOML writer chooses,
    /// so the authored inline form
    /// `category_map = { triage = "backlog", ... }` is *not* what comes back.
    ///
    /// That is a contract/code mismatch, and the WP's rule is to fix the
    /// contract in the same change rather than let the two disagree — so the
    /// contract's example is corrected alongside this.
    ///
    /// The order that *does* matter, `[categories].order`, is a `Vec` and
    /// round-trips exactly. The mapping's key order has no semantic effect: it
    /// maps a column to a category, and the columns' presentation order comes
    /// from `columns`.
    #[test]
    fn a_full_category_config_round_trips_with_its_values_and_order() {
        let tmp = TempDir::new().unwrap();
        // A **non-default** vocabulary, so `[categories]` is written at all.
        // `FULL_CATEGORIES` spells out the built-in vocabulary verbatim, which
        // makes `CategoryConfig::is_default()` true and the section is then
        // *correctly* omitted on save — which is the property the other test
        // asserts. Using it here would have tested nothing about the round trip.
        let authored = r#"issues_dir = "docs/issues"

[categories]
order = ["backlog", "active", "completed", "canceled"]
default = "backlog"

[transitions]
terminal_locked = false

[kanban.default]
columns = ["triage", "wip", "shipped"]
done_column = "shipped"
category_map = { triage = "backlog", wip = "active", shipped = "completed" }

[export]
"#;
        let path = write_toml(tmp.path(), authored);
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        cfg.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();

        assert_eq!(
            reloaded.categories, cfg.categories,
            "the vocabulary and its default survive"
        );
        assert_eq!(
            reloaded.categories.order,
            vec!["backlog", "active", "completed", "canceled"],
            "and `order` is a Vec, so the declared order is preserved exactly"
        );

        assert_eq!(
            reloaded.default_config().category_map,
            cfg.default_config().category_map,
            "the mapping's contents survive, in whatever order they are written"
        );
        // Both new sections are written, since neither is at its default.
        // Both new sections are written — and only because neither is at its
        // default. The first version of this fixture set `terminal_locked = true`,
        // which **is** the default, so `[transitions]` was correctly omitted and
        // the round trip had nothing to prove. Omitted-when-defaulted is the
        // NFR-003 trade this WP makes deliberately, so a fixture that pins the
        // default is a fixture that tests nothing.
        assert!(after.contains("[categories]"), "after: {after}");
        assert!(after.contains("[transitions]"), "after: {after}");
        assert!(
            !reloaded.transitions.terminal_locked,
            "and the value survives"
        );

        // **Save is idempotent.** The top-level section order is the serializer's
        // (struct field) order, not the authored order — the first version of this
        // assertion expected the authored order and failed on a correctly-saved
        // file. What actually has to hold is that a second save changes nothing,
        // which is the property a diff and a merge depend on. The authored order
        // that *is* load-bearing is preserved by the two assertions above.
        let reloaded_again = Config::load_with_warning(&path, |_| {}).unwrap();
        reloaded_again.save(&path).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            after,
            "a second save must be a no-op"
        );
    }

    /// Two boards with different column names, one mapped and one not — the
    /// intake's first acceptance scenario.
    #[test]
    fn two_boards_with_different_columns_map_to_the_same_categories() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.alpha]
columns = ["triage", "wip", "review", "shipped"]
done_column = "shipped"
category_map = { triage = "backlog", wip = "active", review = "active", shipped = "completed" }

[kanban.beta]
columns = ["new", "doing", "merged"]
done_column = "merged"

[export]
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let alpha = &cfg.kanban.configurations["alpha"];
        let beta = &cfg.kanban.configurations["beta"];
        // Different column names, same categories: `shipped` and `merged` both
        // complete, and both boards' working columns are `active`/`unstarted`.
        assert_eq!(alpha.category_for("shipped", &cfg.categories), "completed");
        assert_eq!(beta.category_for("merged", &cfg.categories), "completed");
        assert_eq!(alpha.category_for("wip", &cfg.categories), "active");
        assert_eq!(beta.category_for("doing", &cfg.categories), "unstarted");
        assert!(beta.category_map.is_empty());
    }

    /// The vocabulary's load-bearing distinction, asserted directly: `canceled` is
    /// terminal and **not** complete. Treating it as complete would change
    /// completion meaning, which the contract makes an escalation.
    #[test]
    fn canceled_is_terminal_but_not_complete() {
        assert!(TERMINAL_CATEGORIES.contains(&"canceled"));
        assert!(TERMINAL_CATEGORIES.contains(&"completed"));
        assert_eq!(
            COMPLETE_CATEGORY, "completed",
            "completion is defined by this category alone"
        );
        assert_ne!(COMPLETE_CATEGORY, "canceled");
        // And a board may map a column to `canceled` — the category exists and is
        // mappable, it simply is not the completing one.
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["triage", "dropped", "shipped"]
done_column = "shipped"
category_map = { triage = "backlog", dropped = "canceled", shipped = "completed" }
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let board = cfg.default_config();
        assert_eq!(board.category_for("dropped", &cfg.categories), "canceled");
        assert_ne!(
            board.category_for("dropped", &cfg.categories),
            COMPLETE_CATEGORY
        );
    }

    /// `blocked` as a category is a workflow column position, not the derived
    /// blocked state owned by issue 169's mission. Asserted as distinctness, since
    /// conflating them is a named rejected alternative.
    #[test]
    fn blocked_as_a_category_is_mappable_and_is_its_own_key() {
        assert!(CATEGORY_KEYS.contains(&"blocked"));
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            r#"issues_dir = "docs/issues"

[kanban.default]
columns = ["wip", "on hold", "shipped"]
done_column = "shipped"
category_map = { wip = "active", "on hold" = "blocked", shipped = "completed" }
"#,
        );
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        let board = cfg.default_config();
        assert_eq!(board.category_for("on hold", &cfg.categories), "blocked");
        // The derived blocked state lives in the relationship graph, not here.
        assert!(
            !cfg.default_config()
                .category_map
                .values()
                .any(|v| v.contains("state")),
            "a category is a position, never a derived state"
        );
    }

    #[test]
    fn legacy_file_roundtrips_byte_identical() {
        let tmp = TempDir::new().unwrap();
        // A pre-mission tix.toml in the canonical toml pretty form. The save
        // path must not add, drop, or reorder any pre-existing key (NFR-003):
        // maximum already-pretty formatting proves a true byte-stable save.
        let legacy = LEGACY_PRETTY_BOARD;
        let path = write_toml(tmp.path(), legacy);
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg.planning, PlanningConfig::default());
        assert!(cfg.teams.is_empty());
        assert!(cfg.cycles.is_empty());
        assert_eq!(cfg.milestones_dir, None);
        // Behavior the omitted keys would have carried is unchanged: the
        // `done_column` is still the loader's `"done"` and ordering keeps its
        // default (#1415).
        assert_eq!(
            cfg.default_config().columns,
            ["todo", "in progress", "in review", "done"]
        );
        assert_eq!(cfg.default_config().effective_done_column(), Some("done"));
        assert_eq!(cfg.default_config().order_by, OrderBy::CreatedAtDesc);
        assert_eq!(
            cfg.default_config().hidden_columns,
            [] as [std::string::String; 0]
        );
        assert!(!cfg.default_config().show_mismatch);
        assert!(cfg.default_config().wrap_titles);
        assert_eq!(cfg.default_config().title_lines, DEFAULT_TITLE_LINES);
        assert!(!cfg.default_config().category_map.contains_key("done"));

        cfg.save(&path).unwrap();
        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            on_disk, legacy,
            "legacy tix.toml must save byte-identical (NFR-003)"
        );
        assert!(
            !on_disk.contains("[export]"),
            "an empty `[export]` table must not be materialized:\n{on_disk}"
        );
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(cfg, reloaded);
    }

    #[test]
    fn legacy_file_in_any_layout_never_gains_planning_keys() {
        let tmp = TempDir::new().unwrap();
        // Hand-written single-line arrays (typical of real repos) parse fine;
        // the pretty re-serializer may reformat them, but must never add a
        // planning/teams/cycles/milestones key.
        let legacy = r#"issues_dir = "docs/issues"
[kanban.default]
columns = ["todo", "in progress", "in review", "done"]
done_column = "done"
"#;
        let path = write_toml(tmp.path(), legacy);
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        cfg.save(&path).unwrap();
        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(!on_disk.contains("milestones_dir"));
        assert!(!on_disk.contains("[planning]"));
        assert!(!on_disk.contains("[teams]"));
        assert!(!on_disk.contains("[cycles"));
    }

    #[test]
    fn planning_default_section_with_partial_keys_loads() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "[planning]\ndefault_cycle = \"Cycle 1\"\n");
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            cfg.planning.cycle_number, 1,
            "counter defaults when omitted"
        );
        assert_eq!(cfg.planning.default_cycle.as_deref(), Some("Cycle 1"));
        assert_eq!(cfg.planning.default_milestone, None);
        assert_eq!(cfg.planning.default_team, None);
    }

    #[test]
    fn planning_rejects_unknown_keys() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "[planning]\ncounter = 5\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("counter"));
    }

    #[test]
    fn planning_rejects_zero_cycle_number() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "[planning]\ncycle_number = 0\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("cycle_number"));
    }

    #[test]
    fn cycle_dates_are_validated_and_compared() {
        let tmp = TempDir::new().unwrap();
        // parsing failure
        let bad = write_toml(tmp.path(), "[cycles.x]\nstart_date = \"2026-13-01\"\n");
        let err = Config::load_with_warning(&bad, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("start_date"));

        // ordering failure
        let ordered = write_toml(
            tmp.path(),
            "[cycles.x]\nstart_date = \"2026-09-30\"\ndue_date = \"2026-09-01\"\n",
        );
        let err = Config::load_with_warning(&ordered, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("due_date"));
        assert!(err.to_string().contains("start_date"));
    }

    #[test]
    fn cycles_reject_unknown_keys() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "[cycles.X]\nbogus = 1\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("bogus"));
    }

    #[test]
    fn cycle_without_dates_loads_fine() {
        let tmp = TempDir::new().unwrap();
        let ok = write_toml(tmp.path(), "[cycles.Alpha]\ndescription = \"a\"\n");
        let cfg = Config::load_with_warning(&ok, |_| {}).unwrap();
        assert_eq!(
            cfg.cycles.get("Alpha").unwrap().description.as_deref(),
            Some("a")
        );
    }

    #[test]
    fn teams_validate_members_nonempty_and_unique() {
        let tmp = TempDir::new().unwrap();
        let empty = write_toml(tmp.path(), "[teams.dev]\nmembers = []\n");
        let err = Config::load_with_warning(&empty, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("members"));

        let dup = write_toml(
            tmp.path(),
            "[teams.dev]\nmembers = [\"alice\", \"alice\"]\n",
        );
        let err = Config::load_with_warning(&dup, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("unique"));
    }

    #[test]
    fn empty_teams_table_is_disabled_not_error() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "[teams]\n");
        let cfg = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(cfg.teams.is_empty());
        // An empty [teams] is never written back out.
        cfg.save(&path).unwrap();
        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(!on_disk.contains("[teams]"));
    }

    #[test]
    fn blank_milestones_dir_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "milestones_dir = \"\"\n");
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("milestones_dir"));
    }

    #[test]
    fn sparse_keybindings_roundtrip_without_defaults() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[keybindings.board]\nnew_issue = [\"ctrl+n\", \"f4\"]\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        config.save(&path).unwrap();
        let contents = std::fs::read_to_string(&path).unwrap();
        assert!(contents.contains("[keybindings.board]"));
        assert!(!contents.contains("move_left"));
        assert_eq!(Config::load_with_warning(&path, |_| {}).unwrap(), config);
    }

    #[test]
    fn omitted_keybindings_retain_effective_defaults() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), "issues_dir = \"docs/issues\"\n");
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        let bindings = config.effective_keybindings().unwrap();
        assert_eq!(
            bindings.label(
                crate::keybindings::InputContext::Board,
                crate::keybindings::TuiAction::NewIssue
            ),
            "n"
        );
    }

    /// `[keybindings.edit_conflict]` is a real table (tix #1510): an override lands
    /// on the conflict prompt's decisions and nothing else moves. Without this the
    /// `edit_conflict` rows in `docs/key-bindings.md` would be documentation for a
    /// setting that cannot be written.
    #[test]
    fn edit_conflict_keybindings_override_the_prompt() {
        use crate::keybindings::{InputContext, TuiAction};
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[keybindings.edit_conflict]\nconfirm = [\"ctrl+k\"]\nignore = [\"escape\"]\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        let bindings = config.effective_keybindings().unwrap();

        assert_eq!(
            bindings.label(InputContext::EditConflict, TuiAction::Confirm),
            "Ctrl+k"
        );
        assert_eq!(
            bindings.action(
                InputContext::EditConflict,
                KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL)
            ),
            Some(TuiAction::Confirm)
        );
        assert_eq!(
            bindings.action(
                InputContext::EditConflict,
                KeyEvent::new(KeyCode::Char('o'), KeyModifiers::NONE)
            ),
            None,
            "an override replaces the action's whole alias list"
        );
        // The actions that were not overridden keep their defaults.
        assert_eq!(
            bindings.action(
                InputContext::EditConflict,
                KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)
            ),
            Some(TuiAction::Reedit)
        );
        assert_eq!(
            bindings.action(
                InputContext::EditConflict,
                KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)
            ),
            Some(TuiAction::Ignore)
        );
    }

    #[test]
    fn keybindings_reject_unknown_fields_and_empty_actions() {
        let tmp = TempDir::new().unwrap();
        let unknown = write_toml(tmp.path(), "[keybindings.board]\nbogus = [\"x\"]\n");
        assert!(
            Config::load_with_warning(&unknown, |_| {})
                .unwrap_err()
                .to_string()
                .contains("bogus")
        );
        let empty = write_toml(tmp.path(), "[keybindings.board]\nnew_issue = []\n");
        assert!(
            Config::load_with_warning(&empty, |_| {})
                .unwrap_err()
                .to_string()
                .contains("new_issue")
        );
    }

    /// The mode switches are configurable under `[keybindings.shell]`: an
    /// override moves the key *and* the label the rail renders, an unknown action
    /// name is refused, and an unparsable chord names the key it came from.
    #[test]
    fn shell_mode_switches_are_configurable() {
        use crate::keybindings::{InputContext, TuiAction};
        use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "[keybindings.shell]\nswitch_to_milestones = [\"g\"]\nswitch_to_board = [\"f3\", \"b\"]\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        let bindings = config.effective_keybindings().unwrap();

        // The label is what the rail renders (`nav::render` reads it back).
        assert_eq!(
            bindings.label(InputContext::Shell, TuiAction::SwitchToMilestones),
            "g"
        );
        assert_eq!(
            bindings.label(InputContext::Shell, TuiAction::SwitchToBoard),
            "F3 / b"
        );
        // The key resolves, and the default F5 no longer does.
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE)
            ),
            Some(TuiAction::SwitchToMilestones)
        );
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::F(5), KeyModifiers::NONE)
            ),
            None,
            "an override replaces the action's whole alias list"
        );
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::Char('b'), KeyModifiers::NONE)
            ),
            Some(TuiAction::SwitchToBoard),
            "a second alias keeps working"
        );

        // An unknown action name is a load error naming the key.
        let unknown = write_toml(
            tmp.path(),
            "[keybindings.shell]\nswitch_to_nowhere = [\"g\"]\n",
        );
        let error = Config::load_with_warning(&unknown, |_| {})
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("switch_to_nowhere"),
            "the error names the offending key: {error:?}"
        );

        // An unparsable chord is a load error naming the action and the chord.
        let bad_chord = write_toml(
            tmp.path(),
            "[keybindings.shell]\nswitch_to_milestones = [\"ctrl+nosuchkey\"]\n",
        );
        let error = Config::load_with_warning(&bad_chord, |_| {})
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("switch_to_milestones") && error.contains("nosuchkey"),
            "the error names the key and the chord: {error:?}"
        );
    }

    // --- new-issue templates (tui-new-issue-mode, task 6.2) ---

    #[test]
    fn templates_round_trip_through_save_and_load() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let mut config = Config::starter();
        config.templates.insert(
            "bug".into(),
            IssueTemplate {
                title: Some("Bug: ".into()),
                body: Some("## Steps\n".into()),
                labels: vec!["bug".into(), "urgent".into()],
                status: Some("todo".into()),
                cycles: vec!["Default".into()],
                start_date: Some("2026-01-01".into()),
                due_date: Some("2026-01-02".into()),
                ..IssueTemplate::default()
            },
        );
        config.validate().expect("the fixture is a valid config");
        config.save(&path).unwrap();

        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(raw.contains("[templates.bug]"), "{raw}");
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.templates, config.templates);
        let bug = &reloaded.templates["bug"];
        assert_eq!(bug.labels, ["bug".to_string(), "urgent".to_string()]);
        assert_eq!(bug.body.as_deref(), Some("## Steps\n"));
        assert_eq!(bug.due_date.as_deref(), Some("2026-01-02"));
    }

    #[test]
    fn a_config_without_templates_writes_no_section() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        Config::default().save(&path).unwrap();
        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(
            !raw.contains("templates"),
            "an absent section must not appear on disk:\n{raw}"
        );
        assert!(
            Config::load_with_warning(&path, |_| {})
                .unwrap()
                .templates
                .is_empty()
        );
    }

    #[test]
    fn a_template_value_with_a_comma_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[templates.bug]\nlabels = [\"bug,urgent\"]\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(
            err.to_string().contains("must not contain a comma"),
            "got {err}"
        );
    }

    #[test]
    fn a_template_with_a_backwards_date_range_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[templates.bug]\n\
             start_date = \"2026-02-01\"\ndue_date = \"2026-01-01\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(err.to_string().contains(">= start_date"), "got {err}");
    }

    #[test]
    fn an_unknown_template_key_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[templates.bug]\ntitel = \"typo\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {}).unwrap_err();
        assert!(err.to_string().contains("unknown field"), "got {err}");
    }

    // --- stable-ID issue templates (issue-form-templates, WP01) ---

    #[test]
    fn issue_templates_round_trip_through_save_and_load() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        let mut config = Config::starter();
        config
            .issue_templates
            .insert(
                "bug",
                Template {
                    name: Some("Bug report".to_string()),
                    defaults: TemplateDefaults {
                        labels: vec!["bug".to_string()],
                        priority: Some("high".to_string()),
                        ..TemplateDefaults::default()
                    },
                    prompts: vec![TemplatePrompt {
                        key: "priority".to_string(),
                        label: Some("Priority".to_string()),
                        kind: PromptKind::Select,
                        required: true,
                        default: None,
                        options_ref: Some("priorities".to_string()),
                    }],
                    references: vec![TemplateReference {
                        kind: ReferenceKind::Label,
                        value: "bug".to_string(),
                        required: true,
                    }],
                    ..Template::default()
                },
            )
            .unwrap();
        config.validate().expect("the fixture is a valid config");
        config.save(&path).unwrap();

        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(raw.contains("[issue_templates.bug]"), "{raw}");
        assert!(raw.contains("[[issue_templates.bug.prompts]]"), "{raw}");

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.issue_templates, config.issue_templates);
        let bug = reloaded.issue_templates.get("bug").unwrap();
        assert_eq!(bug.name.as_deref(), Some("Bug report"));
        assert_eq!(bug.defaults.labels, ["bug".to_string()]);
        assert_eq!(bug.prompts[0].kind, PromptKind::Select);
        assert!(bug.prompts[0].required);
        assert_eq!(bug.references[0].kind, ReferenceKind::Label);
    }

    #[test]
    fn a_config_without_issue_templates_writes_no_section() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("tix.toml");
        Config::default().save(&path).unwrap();
        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(
            !raw.contains("issue_templates"),
            "an absent section must not appear on disk:\n{raw}"
        );
        assert!(
            Config::load_with_warning(&path, |_| {})
                .unwrap()
                .issue_templates
                .is_empty()
        );
    }

    #[test]
    fn a_legacy_config_gains_no_issue_templates_section() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), LEGACY_PRETTY_BOARD);
        let before = std::fs::read_to_string(&path).unwrap();
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(
            config.issue_templates.is_empty(),
            "a legacy config has no stable-ID registry"
        );
        config.save(&path).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            before,
            "a legacy config must round-trip byte-identically"
        );
    }

    #[test]
    fn issue_template_declaration_order_is_restored() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [issue_templates.zeta]\nname = \"Zeta\"\n\n\
             [issue_templates.alpha]\nname = \"Alpha\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            config.issue_templates.ids().collect::<Vec<_>>(),
            ["zeta", "alpha"],
            "declaration order is the display order"
        );
        config.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded.issue_templates.ids().collect::<Vec<_>>(),
            ["zeta", "alpha"]
        );
    }

    #[test]
    fn a_rejected_template_write_leaves_tix_toml_unchanged() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[issue_templates.bug]\nname = \"Bug report\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        let before = std::fs::read(&path).unwrap();

        // A scope naming a board that does not exist is a validation error, so
        // the caller never reaches `Config::save`.
        let mut rejected = config.clone();
        rejected.issue_templates.get_mut("bug").unwrap().scope =
            TemplateScope::board("no-such-board");
        let err = rejected.validate().unwrap_err().to_string();
        assert!(
            err.contains("issue_templates.bug.scope") && err.contains("no-such-board"),
            "{err}"
        );
        assert_eq!(
            std::fs::read(&path).unwrap(),
            before,
            "a rejected write must not touch tix.toml"
        );

        // A duplicate identity is refused before any save, leaving both the
        // file and the loaded registry untouched.
        let mut duplicate = config.clone();
        let err = duplicate
            .issue_templates
            .insert("bug", Template::default())
            .unwrap_err();
        assert!(err.to_string().contains("already exists"), "{err}");
        assert_eq!(duplicate.issue_templates, config.issue_templates);
        assert_eq!(std::fs::read(&path).unwrap(), before);
    }

    #[test]
    fn unknown_issue_template_metadata_round_trips_byte_stably() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [issue_templates.bug]\nname = \"Bug report\"\n\
             reporter_hint = \"include the build id\"\n\n\
             [issue_templates.bug.future]\nlevel = 3\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        let bug = config.issue_templates.get("bug").unwrap();
        assert_eq!(
            bug.extensions
                .get("reporter_hint")
                .and_then(toml::Value::as_str),
            Some("include the build id")
        );
        assert!(bug.extensions.get("future").is_some());

        config.save(&path).unwrap();
        let first = std::fs::read(&path).unwrap();
        let text = String::from_utf8(first.clone()).unwrap();
        assert!(
            text.contains("reporter_hint") && text.contains("future"),
            "unknown metadata must survive a save:\n{text}"
        );

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        reloaded.save(&path).unwrap();
        assert_eq!(
            std::fs::read(&path).unwrap(),
            first,
            "a second round trip must be byte-identical"
        );
    }

    /// A `tix.toml` that configures limits must survive a save byte-for-byte, and
    /// the resolved view of it must be the one the file states (T005).
    #[test]
    fn wip_config_round_trips_byte_stably_and_resolves() {
        let tmp = TempDir::new().unwrap();
        let configured = "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\n    \"todo\",\n    \"in progress\",\n    \"done\",\n]\n\n\
             [kanban.default.wip.units]\nd = 1\nw = 5\n\n\
             [kanban.default.wip.limits.\"in progress\"]\nmax_items = 3\n\
             max_estimate = 10\nunit = \"d\"\npolicy = \"block\"\n";
        let path = write_toml(tmp.path(), configured);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();

        let board = config.default_config();
        let limit = board
            .wip
            .effective_limit("in progress")
            .expect("the configured limit is in force");
        assert_eq!(limit.max_items, Some(3));
        assert_eq!(limit.max_estimate, Some(10));
        assert_eq!(limit.unit.as_deref(), Some("d"));
        assert_eq!(limit.policy, Some(crate::wip::LimitPolicy::Block));
        assert_eq!(board.wip.factor("w"), Some(5));
        assert!(
            board.wip.effective_limit("done").is_none(),
            "a column without a limit has none"
        );

        config.save(&path).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            configured,
            "a configured board must round trip byte-for-byte"
        );
    }

    /// The limits live inside the board table, so a limit aimed at a column the
    /// board does not declare is refused at load, by name.
    #[test]
    fn wip_config_limit_on_an_unknown_column_is_refused() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [kanban.default.wip.limits.\"in progress\"]\nmax_items = 3\n\
             policy = \"warn\"\n",
        );
        let error = Config::load_with_warning(&path, |_| {})
            .expect_err("an unknown column is refused")
            .to_string();
        assert!(
            error.contains("kanban.default.wip.limits.`in progress`"),
            "{error}"
        );
    }

    /// Limits are absent unless declared: the legacy board keeps its exact bytes
    /// and gains no `wip` key (T005).
    #[test]
    fn wip_config_absent_limits_add_no_key() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), LEGACY_PRETTY_BOARD);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(config.default_config().wip.is_empty());
        config.save(&path).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            LEGACY_PRETTY_BOARD,
            "a board without limits must not gain a `wip` key"
        );
    }

    // --- WP01: the `[projects.<project-id>]` registry (FR-001, C-001, C-002) ---

    const TWO_PROJECTS: &str = "issues_dir = \"docs/issues\"\n\n\
        [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
        [projects.\"p-3f9a2c\"]\n\
        name = \"Platform hardening\"\n\
        description = \"Reduce operational risk across the sync path.\"\n\
        status = \"active\"\n\
        lead = \"Alice <alice@example.com>\"\n\
        start_date = \"2026-09-01\"\n\
        due_date = \"2026-12-31\"\n\n\
        [projects.\"p-7b1e04\"]\n\
        name = \"Docs refresh\"\n";

    #[test]
    fn project_registry_parses_every_contract_field() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), TWO_PROJECTS);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();

        let platform = &config.projects["p-3f9a2c"];
        assert_eq!(platform.name, "Platform hardening");
        assert_eq!(
            platform.description.as_deref(),
            Some("Reduce operational risk across the sync path.")
        );
        assert_eq!(platform.status.as_deref(), Some("active"));
        assert_eq!(platform.lead.as_deref(), Some("Alice <alice@example.com>"));
        assert_eq!(platform.start_date.as_deref(), Some("2026-09-01"));
        assert_eq!(platform.due_date.as_deref(), Some("2026-12-31"));

        // The key is the id; a record that omits every optional field carries no
        // empty value.
        let docs = &config.projects["p-7b1e04"];
        assert_eq!(docs.name, "Docs refresh");
        assert!(docs.description.is_none() && docs.status.is_none() && docs.lead.is_none());
        assert!(docs.start_date.is_none() && docs.due_date.is_none());
    }

    #[test]
    fn project_registry_rejects_an_unknown_field() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [projects.\"p-1\"]\nname = \"One\"\nownr = \"typo\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("ownr"), "got {err}");
    }

    #[test]
    fn project_declaration_order_is_restored() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [projects.\"p-zeta\"]\nname = \"Zeta\"\n\n\
             [projects.\"p-alpha\"]\nname = \"Alpha\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            config.projects.keys().collect::<Vec<_>>(),
            ["p-zeta", "p-alpha"],
            "declaration order is the display order"
        );
        config.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded.projects.keys().collect::<Vec<_>>(),
            ["p-zeta", "p-alpha"],
            "declaration order survives a save/reload through the ordered map"
        );
    }

    #[test]
    fn a_legacy_tix_toml_gains_no_projects_section() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), LEGACY_PRETTY_BOARD);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(config.projects.is_empty());
        config.save(&path).unwrap();
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            LEGACY_PRETTY_BOARD,
            "a repository with no projects must round-trip byte-identically"
        );
    }

    #[test]
    fn an_empty_project_record_writes_no_optional_keys() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [projects.\"p-1\"]\nname = \"One\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        config.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        for key in ["description", "status", "lead", "start_date", "due_date"] {
            assert!(
                !after.contains(key),
                "an absent optional field must not be written: {key} in {after}"
            );
        }
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded, config);
    }

    #[test]
    fn a_blank_project_name_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[projects.\"p-1\"]\nname = \"  \"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("projects.p-1.name"), "got {err}");
    }

    #[test]
    fn duplicate_project_names_are_rejected() {
        // `Same`/`Same` and `Same`/`same` are both refusals: the point of the rule
        // is that a name a user types selects exactly one project, and a user does
        // not tell the two spellings apart.
        for second in ["Same", "same"] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n\
                     [projects.\"p-1\"]\nname = \"Same\"\n\n\
                     [projects.\"p-2\"]\nname = \"{second}\"\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains("must be unique"), "got {err}");
        }
    }

    #[test]
    fn a_padded_project_name_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[projects.\"p-1\"]\nname = \" One \"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("leading or trailing whitespace"), "got {err}");
    }

    #[test]
    fn a_blank_project_id_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[projects.\"\"]\nname = \"No id\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("must not be blank"), "got {err}");
    }

    #[test]
    fn a_project_id_with_a_structural_character_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[projects.\"p.1\"]\nname = \"Dotted\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("contains"), "got {err}");
    }

    #[test]
    fn blank_optional_project_text_is_rejected() {
        for key in ["description", "status", "lead"] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n\
                     [projects.\"p-1\"]\nname = \"One\"\n{key} = \"\"\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains(&format!("projects.p-1.{key}")), "got {err}");
        }
    }

    #[test]
    fn a_bad_or_inverted_project_date_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let bad = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [projects.\"p-1\"]\nname = \"One\"\nstart_date = \"2026-13-01\"\n",
        );
        let err = Config::load_with_warning(&bad, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("projects.p-1"), "got {err}");

        let inverted = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [projects.\"p-1\"]\nname = \"One\"\n\
             start_date = \"2026-12-01\"\ndue_date = \"2026-01-01\"\n",
        );
        let err = Config::load_with_warning(&inverted, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("projects.p-1"), "got {err}");
    }

    #[test]
    fn a_valid_project_date_pair_passes() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), TWO_PROJECTS);
        Config::load_with_warning(&path, |_| {}).expect("a valid registry must load");
    }

    /// The shape the allocator produces: `p-` plus 16 hex digits, distinct draws.
    #[test]
    fn allocated_project_ids_have_the_generated_shape_and_successive_draws_differ() {
        let mut config = Config::default();
        let first = config.allocate_project_id();
        config.projects.insert(
            first.to_string(),
            ProjectConfiguration {
                name: "One".into(),
                ..ProjectConfiguration::default()
            },
        );
        let second = config.allocate_project_id();
        assert_ne!(first, second, "two allocations must be distinct");
        assert_eq!(first.as_str().len(), 18, "`p-` plus 16 hex digits");
        assert!(first.as_str().starts_with("p-"));

        // From the never-reused rule's second half: a deleted project's id is
        // spent. With the real generator this is observed as "a fresh draw is a
        // different id"; the redraw half is pinned exactly by
        // `allocation_redraws_past_a_stored_id`.
        config.projects.shift_remove(first.as_str());
        let third = config.allocate_project_id();
        assert_ne!(
            third, first,
            "a deleted project's id must not be handed out"
        );
        assert_ne!(third, second);
    }

    /// The exact half of the never-reused rule: allocation redraws past an id that
    /// is already stored. The draw is injected, because a real generator collides
    /// so rarely that the redraw loop is otherwise untestable.
    #[test]
    fn allocation_redraws_past_a_stored_id() {
        let mut config = Config::default();
        config.projects.insert(
            "p-aaaa".into(),
            ProjectConfiguration {
                name: "Stored".into(),
                ..ProjectConfiguration::default()
            },
        );
        let scripted = ["p-aaaa", "p-bbbb"];
        let mut draws = 0;
        let allocated = config.allocate_project_id_with(|| {
            let drawn = scripted[draws];
            draws += 1;
            ProjectId::new(drawn).unwrap()
        });
        assert_eq!(allocated.as_str(), "p-bbbb");
        assert_eq!(draws, 2, "the stored id must have been drawn and redrawn");
    }

    /// The same exact half, for the schedule registry: allocation redraws past an id
    /// that is already stored. The draw is injected for the same reason — a fresh
    /// `cs-` id cannot collide with a stored one, so the real generator cannot exercise
    /// the loop.
    #[test]
    fn schedule_allocation_redraws_past_a_stored_id() {
        let mut config = Config::default();
        config.cycle_schedules.insert(
            "cs-aaaa".into(),
            crate::cycle_schedule::config::CycleScheduleConfiguration {
                name: "Stored".into(),
                ..crate::cycle_schedule::config::CycleScheduleConfiguration::default()
            },
        );
        let scripted = ["cs-aaaa", "cs-bbbb"];
        let mut draws = 0;
        let allocated = config.allocate_cycle_schedule_id_with(|| {
            let drawn = scripted[draws];
            draws += 1;
            crate::cycle_schedule::config::CycleScheduleId::new(drawn).unwrap()
        });
        assert_eq!(allocated.as_str(), "cs-bbbb");
        assert_eq!(draws, 2, "the stored id must have been drawn and redrawn");
    }

    #[test]
    fn a_hand_written_project_id_loads_and_is_never_allocated_again() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [projects.\"p-ffffffffffffffff\"]\nname = \"Hand written\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(config.projects.contains_key("p-ffffffffffffffff"));
        // The stored id is never returned, however many times a draw scripted to
        // produce it is asked.
        let mut draws = 0;
        let allocated = config.allocate_project_id_with(|| {
            draws += 1;
            if draws < 3 {
                ProjectId::new("p-ffffffffffffffff").unwrap()
            } else {
                ProjectId::new("p-0000000000000000").unwrap()
            }
        });
        assert_eq!(allocated.as_str(), "p-0000000000000000");
        assert_eq!(draws, 3);
    }

    #[test]
    fn a_rename_changes_the_label_and_never_the_key() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), TWO_PROJECTS);
        let mut config = Config::load_with_warning(&path, |_| {}).unwrap();
        config.projects["p-3f9a2c"].name = "Platform hardening (renamed)".into();
        config.save(&path).unwrap();

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(
            reloaded.projects.contains_key("p-3f9a2c"),
            "the id is the key and must survive a rename"
        );
        assert_eq!(
            reloaded.projects["p-3f9a2c"].name,
            "Platform hardening (renamed)"
        );
    }

    #[test]
    fn project_id_validation_accepts_handles_and_rejects_junk() {
        assert!(ProjectId::new("p-platform").is_ok());
        assert!(ProjectId::new("p-3f9a2c").is_ok());
        assert!(ProjectId::new("").is_err());
        assert!(ProjectId::new(" p-1").is_err(), "surrounding whitespace");
        assert!(ProjectId::new("p 1").is_err(), "inner whitespace");
        assert!(ProjectId::new("p.1").is_err(), "structural `.`");
        assert!(ProjectId::new(&"x".repeat(ProjectId::MAX_LEN + 1)).is_err());
    }

    // --- WP01: the `[epics.<epic-id>]` registry (FR-001, FR-003, C-002, C-003, C-004) ---

    const TWO_EPICS: &str = "issues_dir = \"docs/issues\"\n\n\
        [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
        [epics.\"e-7c4a91\"]\n\
        name = \"Harden the sync path\"\n\
        description = \"Reduce operational risk across every tracker adapter.\"\n\
        status = \"active\"\n\
        owner = \"Alice <alice@example.com>\"\n\
        start_date = \"2026-09-01\"\n\
        due_date = \"2026-12-31\"\n\
        weight = 5\n\
        parent = \"e-2b8f30\"\n\
        projects = [\"p-3f9a2c\"]\n\
        milestone = \"2026-Q4\"\n\
        cycle = \"October 2026\"\n\n\
        [epics.\"e-2b8f30\"]\n\
        name = \"Q4 reliability\"\n";

    #[test]
    fn epic_registry_parses_every_contract_field() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), TWO_EPICS);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();

        let sync = &config.epics["e-7c4a91"];
        assert_eq!(sync.name, "Harden the sync path");
        assert_eq!(
            sync.description.as_deref(),
            Some("Reduce operational risk across every tracker adapter.")
        );
        assert_eq!(sync.status.as_deref(), Some("active"));
        assert_eq!(sync.owner.as_deref(), Some("Alice <alice@example.com>"));
        assert_eq!(sync.start_date.as_deref(), Some("2026-09-01"));
        assert_eq!(sync.due_date.as_deref(), Some("2026-12-31"));
        assert_eq!(sync.weight, Some(5));
        assert_eq!(sync.parent.as_deref(), Some("e-2b8f30"));
        assert_eq!(sync.projects, ["p-3f9a2c"]);
        assert_eq!(sync.milestone.as_deref(), Some("2026-Q4"));
        assert_eq!(sync.cycle.as_deref(), Some("October 2026"));

        // The key is the id; a record that omits every optional field carries no
        // value — and no empty `projects` list.
        let q4 = &config.epics["e-2b8f30"];
        assert_eq!(q4.name, "Q4 reliability");
        assert!(q4.description.is_none() && q4.status.is_none() && q4.owner.is_none());
        assert!(q4.start_date.is_none() && q4.due_date.is_none());
        assert!(q4.weight.is_none() && q4.parent.is_none() && q4.milestone.is_none());
        assert!(q4.cycle.is_none());
        assert_eq!(q4.projects, [] as [std::string::String; 0]);
    }

    #[test]
    fn epic_registry_rejects_an_unknown_field() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [epics.\"e-1\"]\nname = \"One\"\nownr = \"typo\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("ownr"), "got {err}");
    }

    /// `weight` is epic metadata and there is **no** size field on the record:
    /// `Issue.estimate` stays the free-form string it is (research R3).
    #[test]
    fn an_epic_record_takes_weight_but_never_an_estimate_field() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [epics.\"e-1\"]\nname = \"One\"\nestimate = \"2\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("estimate"), "got {err}");
    }

    #[test]
    fn epic_declaration_order_is_restored() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [epics.\"e-zeta\"]\nname = \"Zeta\"\n\n\
             [epics.\"e-alpha\"]\nname = \"Alpha\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            config.epics.keys().collect::<Vec<_>>(),
            ["e-zeta", "e-alpha"],
            "declaration order is the display order"
        );
        config.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded.epics.keys().collect::<Vec<_>>(),
            ["e-zeta", "e-alpha"],
            "declaration order survives a save/reload through the ordered map"
        );
    }

    #[test]
    fn a_legacy_tix_toml_gains_no_epics_section() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), LEGACY_PRETTY_BOARD);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(config.epics.is_empty());
        config.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            after, LEGACY_PRETTY_BOARD,
            "a repository with no epics must round-trip byte-identically"
        );
        assert!(
            !after.contains("[epics"),
            "an empty registry writes no section: {after}"
        );
    }

    /// The two registries coexist: a config with `[projects]` and no `[epics]`
    /// round-trips cleanly, and one with both keeps each section.
    #[test]
    fn epics_and_projects_registries_coexist() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), TWO_PROJECTS);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(config.epics.is_empty(), "no `[epics]` means no epics");
        config.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        assert!(!after.contains("[epics"), "got {after}");
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.projects, config.projects);
        assert!(reloaded.epics.is_empty());

        let both_dir = TempDir::new().unwrap();
        let both = write_toml(
            both_dir.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [projects.\"p-3f9a2c\"]\nname = \"Platform\"\n\n\
             [epics.\"e-1\"]\nname = \"Harden\"\nprojects = [\"p-3f9a2c\"]\n",
        );
        let config = Config::load_with_warning(&both, |_| {}).unwrap();
        assert_eq!(config.projects.keys().collect::<Vec<_>>(), ["p-3f9a2c"]);
        assert_eq!(config.epics.keys().collect::<Vec<_>>(), ["e-1"]);
        config.save(&both).unwrap();
        let reloaded = Config::load_with_warning(&both, |_| {}).unwrap();
        assert_eq!(reloaded.projects, config.projects);
        assert_eq!(reloaded.epics, config.epics);
    }

    #[test]
    fn an_empty_epic_record_writes_no_optional_keys() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [epics.\"e-1\"]\nname = \"One\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        config.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        for key in [
            "description",
            "status",
            "owner",
            "start_date",
            "due_date",
            "weight",
            "parent",
            "projects",
            "milestone",
            "cycle",
        ] {
            assert!(
                !after.contains(key),
                "an absent optional field must not be written: {key} in {after}"
            );
        }
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded, config);
    }

    #[test]
    fn a_blank_epic_name_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[epics.\"e-1\"]\nname = \"  \"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("epics.e-1.name"), "got {err}");
    }

    #[test]
    fn duplicate_epic_names_are_rejected() {
        for second in ["Same", "same"] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n\
                     [epics.\"e-1\"]\nname = \"Same\"\n\n\
                     [epics.\"e-2\"]\nname = \"{second}\"\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains("must be unique"), "got {err}");
        }
    }

    #[test]
    fn a_padded_epic_name_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[epics.\"e-1\"]\nname = \" One \"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("leading or trailing whitespace"), "got {err}");
    }

    #[test]
    fn a_blank_epic_id_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[epics.\"\"]\nname = \"No id\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("must not be blank"), "got {err}");
    }

    #[test]
    fn an_epic_id_with_a_structural_character_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[epics.\"e.1\"]\nname = \"Dotted\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("contains"), "got {err}");
    }

    #[test]
    fn blank_optional_epic_text_is_rejected() {
        for key in ["description", "status", "owner", "milestone", "cycle"] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n\
                     [epics.\"e-1\"]\nname = \"One\"\n{key} = \"\"\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains(&format!("epics.e-1.{key}")), "got {err}");
        }
    }

    #[test]
    fn a_bad_or_inverted_epic_date_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let bad = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [epics.\"e-1\"]\nname = \"One\"\nstart_date = \"2026-13-01\"\n",
        );
        let err = Config::load_with_warning(&bad, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("epics.e-1"), "got {err}");

        let inverted = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [epics.\"e-1\"]\nname = \"One\"\n\
             start_date = \"2026-12-01\"\ndue_date = \"2026-01-01\"\n",
        );
        let err = Config::load_with_warning(&inverted, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("epics.e-1"), "got {err}");
    }

    #[test]
    fn a_non_positive_or_unparseable_weight_is_rejected() {
        for body in ["weight = 0", "weight = -3"] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n[epics.\"e-1\"]\nname = \"One\"\n{body}\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains("positive integer"), "{body}: got {err}");
            assert!(err.contains("epics.e-1.weight"), "{body}: got {err}");
        }

        // Unparseable: the field is an integer, so the TOML parser refuses a string.
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[epics.\"e-1\"]\nname = \"One\"\nweight = \"big\"\n",
        );
        let err = Config::load_with_warning(&path, |_| {})
            .unwrap_err()
            .to_string();
        assert!(err.contains("weight"), "got {err}");
    }

    /// Config-layer validation is about the **shape** of a reference, never its
    /// resolution: a project, milestone, cycle, or parent epic that does not exist
    /// must stay loadable and repairable (C-005). Resolution and diagnosis belong to
    /// the epic service (WP02) and to `tix lint`.
    #[test]
    fn epic_references_are_shape_checked_but_never_resolved() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [epics.\"e-1\"]\nname = \"Child\"\n\
             parent = \"e-missing\"\nprojects = [\"p-missing\"]\n\
             milestone = \"2026-Q4\"\ncycle = \"No such cycle\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {})
            .expect("a dangling reference must stay loadable");
        let epic = &config.epics["e-1"];
        assert_eq!(epic.parent.as_deref(), Some("e-missing"));
        assert_eq!(epic.projects, ["p-missing"]);
        assert_eq!(epic.milestone.as_deref(), Some("2026-Q4"));
        assert_eq!(epic.cycle.as_deref(), Some("No such cycle"));

        // Shape, however, is this layer's business.
        for (body, needle) in [
            ("parent = \"e.1\"", "epics.e-1.parent"),
            ("parent = \"\"", "epics.e-1.parent"),
            ("parent = \"e-1\"", "must not name the epic itself"),
            ("projects = [\"p.1\"]", "epics.e-1.projects"),
        ] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n[epics.\"e-1\"]\nname = \"One\"\n{body}\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains(needle), "{body}: got {err}");
        }
    }

    /// The shape the allocator produces: `e-` plus 16 hex digits, distinct draws.
    #[test]
    fn allocated_epic_ids_have_the_generated_shape_and_successive_draws_differ() {
        let mut config = Config::default();
        let first = config.allocate_epic_id();
        config.epics.insert(
            first.to_string(),
            EpicConfiguration {
                name: "One".into(),
                ..EpicConfiguration::default()
            },
        );
        let second = config.allocate_epic_id();
        assert_ne!(first, second, "two allocations must be distinct");
        assert_eq!(first.as_str().len(), 18, "`e-` plus 16 hex digits");
        assert!(first.as_str().starts_with("e-"));

        // A deleted epic's id is spent: the never-reused rule is what keeps a member
        // issue's dangling reference diagnosable instead of silently rebound (C-005).
        config.epics.shift_remove(first.as_str());
        let third = config.allocate_epic_id();
        assert_ne!(third, first, "a deleted epic's id must not be handed out");
        assert_ne!(third, second);
    }

    /// The exact half of the never-reused rule: allocation redraws past an id that is
    /// already stored. The draw is injected, because a real generator collides so
    /// rarely that the redraw loop is otherwise untestable.
    #[test]
    fn epic_allocation_redraws_past_a_stored_id() {
        let mut config = Config::default();
        config.epics.insert(
            "e-aaaa".into(),
            EpicConfiguration {
                name: "Stored".into(),
                ..EpicConfiguration::default()
            },
        );
        let scripted = ["e-aaaa", "e-bbbb"];
        let mut draws = 0;
        let allocated = config.allocate_epic_id_with(|| {
            let drawn = scripted[draws];
            draws += 1;
            EpicId::new(drawn).unwrap()
        });
        assert_eq!(allocated.as_str(), "e-bbbb");
        assert_eq!(draws, 2, "the stored id must have been drawn and redrawn");
    }

    #[test]
    fn a_hand_written_epic_id_loads_and_is_never_allocated_again() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [epics.\"e-ffffffffffffffff\"]\nname = \"Hand written\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(config.epics.contains_key("e-ffffffffffffffff"));
        // The stored id is never returned, however many times a draw scripted to
        // produce it is asked. A hand-written handle coexists with the generated shape.
        let mut draws = 0;
        let allocated = config.allocate_epic_id_with(|| {
            draws += 1;
            if draws < 3 {
                EpicId::new("e-ffffffffffffffff").unwrap()
            } else {
                EpicId::new("e-0000000000000000").unwrap()
            }
        });
        assert_eq!(allocated.as_str(), "e-0000000000000000");
        assert_eq!(draws, 3);
    }

    #[test]
    fn an_epic_rename_changes_the_label_and_never_the_key() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(tmp.path(), TWO_EPICS);
        let mut config = Config::load_with_warning(&path, |_| {}).unwrap();
        config.epics["e-7c4a91"].name = "Harden the sync path (renamed)".into();
        config.save(&path).unwrap();

        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert!(
            reloaded.epics.contains_key("e-7c4a91"),
            "the id is the key and must survive a rename"
        );
        assert_eq!(
            reloaded.epics["e-7c4a91"].name,
            "Harden the sync path (renamed)"
        );
    }

    #[test]
    fn epic_id_validation_accepts_handles_and_rejects_junk() {
        assert!(EpicId::new("e-platform").is_ok());
        assert!(EpicId::new("e-7c4a91").is_ok());
        assert!(EpicId::new("").is_err());
        assert!(EpicId::new(" e-1").is_err(), "surrounding whitespace");
        assert!(EpicId::new("e 1").is_err(), "inner whitespace");
        assert!(EpicId::new("e.1").is_err(), "structural `.`");
        assert!(EpicId::new(&"x".repeat(EpicId::MAX_LEN + 1)).is_err());
    }

    /// The two registries share one rule for a key, not two: the checks are the same
    /// and the message differs only in the prefix words. The project strings are
    /// asserted exactly, because they are the ones issue #178 shipped.
    #[test]
    fn the_two_registries_share_the_id_rules() {
        assert_eq!(
            ProjectId::new("").unwrap_err().to_string(),
            "config error: a project id must not be blank"
        );
        assert_eq!(
            EpicId::new("").unwrap_err().to_string(),
            "config error: an epic id must not be blank"
        );
        assert_eq!(
            ProjectId::new(" p-1").unwrap_err().to_string(),
            "config error: project id ` p-1` has leading or trailing whitespace"
        );
        assert_eq!(
            EpicId::new("e-1 ").unwrap_err().to_string(),
            "config error: epic id `e-1 ` has leading or trailing whitespace"
        );
        assert_eq!(ProjectId::MAX_LEN, EpicId::MAX_LEN);

        // A handle that is valid for one kind is valid for the other, and the same
        // junk is refused by both.
        for handle in ["x-y", "a_b", "a:b", "a-1"] {
            assert!(ProjectId::new(handle).is_ok(), "{handle}");
            assert!(EpicId::new(handle).is_ok(), "{handle}");
        }
        for junk in ["", " a", "a b", "a.b", "a[b", "a\"b"] {
            assert!(ProjectId::new(junk).is_err(), "{junk}");
            assert!(EpicId::new(junk).is_err(), "{junk}");
        }
    }

    const ONE_INITIATIVE: &str = "issues_dir = \"docs/issues\"\n\n\
        [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
        [initiatives.\"i-1\"]\nname = \"Grow the platform\"\n";

    #[test]
    fn initiative_id_validation_accepts_handles_and_rejects_junk() {
        assert!(InitiativeId::new("i-outcome").is_ok());
        assert!(InitiativeId::new("i-7c4a91").is_ok());
        assert!(InitiativeId::new("").is_err());
        assert!(InitiativeId::new(" i-1").is_err(), "surrounding whitespace");
        assert!(InitiativeId::new("i 1").is_err(), "inner whitespace");
        assert!(InitiativeId::new("i.1").is_err(), "structural `.`");
        assert!(InitiativeId::new(&"x".repeat(InitiativeId::MAX_LEN + 1)).is_err());
    }

    /// The third registry shares the same key rule, worded for its own kind: the
    /// project/epic assertions above pin the rule; this pins the third spelling.
    #[test]
    fn the_three_registries_share_the_id_rules() {
        assert_eq!(
            InitiativeId::new("").unwrap_err().to_string(),
            "config error: an initiative id must not be blank"
        );
        assert_eq!(
            InitiativeId::new(" i-1").unwrap_err().to_string(),
            "config error: initiative id ` i-1` has leading or trailing whitespace"
        );
        assert_eq!(InitiativeId::MAX_LEN, ProjectId::MAX_LEN);
        assert_eq!(InitiativeId::MAX_LEN, EpicId::MAX_LEN);
    }

    #[test]
    fn allocated_initiative_ids_have_the_generated_shape_and_successive_draws_differ() {
        let mut config = Config::default();
        let first = config.allocate_initiative_id();
        config.initiatives.insert(
            first.to_string(),
            InitiativeConfiguration {
                name: "One".into(),
                ..InitiativeConfiguration::default()
            },
        );
        let second = config.allocate_initiative_id();
        assert_ne!(first, second, "two allocations must be distinct");
        assert_eq!(first.as_str().len(), 18, "`i-` plus 16 hex digits");
        assert!(first.as_str().starts_with("i-"));

        // A deleted initiative's id is spent: a later record must not be able to
        // masquerade as the one that was removed.
        config.initiatives.shift_remove(first.as_str());
        let third = config.allocate_initiative_id();
        assert_ne!(
            third, first,
            "a deleted initiative's id must not be handed out"
        );
        assert_ne!(third, second);
    }

    #[test]
    fn initiative_allocation_redraws_past_a_stored_id() {
        let mut config = Config::default();
        config.initiatives.insert(
            "i-aaaa".into(),
            InitiativeConfiguration {
                name: "Stored".into(),
                ..InitiativeConfiguration::default()
            },
        );
        let scripted = ["i-aaaa", "i-bbbb"];
        let mut draws = 0;
        let allocated = config.allocate_initiative_id_with(|| {
            let drawn = scripted[draws];
            draws += 1;
            InitiativeId::new(drawn).unwrap()
        });
        assert_eq!(allocated.as_str(), "i-bbbb");
        assert_eq!(draws, 2, "the stored id must have been drawn and redrawn");
    }

    /// An absent `[initiatives]` section gains no key on save (C-001), and a record
    /// with only a name writes no optional key — the "empty record" round trip.
    #[test]
    fn an_absent_initiatives_section_and_an_empty_record_write_nothing_extra() {
        let tmp = TempDir::new().unwrap();
        let legacy = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n[kanban.default]\ncolumns = [\"todo\", \"done\"]\n",
        );
        let config = Config::load_with_warning(&legacy, |_| {}).unwrap();
        assert!(config.initiatives.is_empty());
        config.save(&legacy).unwrap();
        assert!(
            !std::fs::read_to_string(&legacy)
                .unwrap()
                .contains("[initiatives"),
            "a legacy file gains no section"
        );

        let path = write_toml(tmp.path(), ONE_INITIATIVE);
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        config.save(&path).unwrap();
        let after = std::fs::read_to_string(&path).unwrap();
        for key in [
            "outcome",
            "owner",
            "status",
            "priority",
            "labels",
            "target_date",
            "projects",
            "epics",
            "milestones",
        ] {
            assert!(
                !after.contains(key),
                "an absent optional field must not be written: {key} in {after}"
            );
        }
        assert_eq!(Config::load_with_warning(&path, |_| {}).unwrap(), config);
    }

    /// The record deliberately preserves unknown metadata: unlike `[projects]`/
    /// `[epics]`, a key this schema does not know round-trips instead of making the
    /// file unreadable. This is the trade-off the type-level doc records.
    #[test]
    fn an_initiative_preserves_unknown_metadata_through_a_round_trip() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [initiatives.\"i-1\"]\nname = \"One\"\ncustom_field = \"keep me\"\n\
             nested = { answer = 42 }\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        let extensions = &config.initiatives["i-1"].extensions;
        assert_eq!(extensions.len(), 2);
        assert_eq!(
            extensions.get("custom_field").and_then(toml::Value::as_str),
            Some("keep me")
        );
        config.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(reloaded.initiatives["i-1"].extensions, *extensions);
    }

    #[test]
    fn initiative_validation_refuses_blank_names_bad_dates_and_bad_references() {
        for (body, needle) in [
            ("name = \"  \"", "initiatives.i-1.name"),
            ("name = \" One \"", "leading or trailing whitespace"),
            (
                "name = \"One\"\ntarget_date = \"2026-13-01\"",
                "initiatives.i-1.target_date",
            ),
            (
                "name = \"One\"\ntarget_date = \"not a date\"",
                "initiatives.i-1.target_date",
            ),
            (
                "name = \"One\"\nprojects = [\"p.1\"]",
                "initiatives.i-1.projects",
            ),
            ("name = \"One\"\nepics = [\"e.1\"]", "initiatives.i-1.epics"),
            (
                "name = \"One\"\nmilestones = [\"\"]",
                "initiatives.i-1.milestones",
            ),
            (
                "name = \"One\"\nlabels = [\"  \"]",
                "initiatives.i-1.labels",
            ),
            ("name = \"One\"\nowner = \"\"", "initiatives.i-1.owner"),
        ] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n[kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
                     [initiatives.\"i-1\"]\n{body}\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains(needle), "{body}: got {err}");
        }
    }

    #[test]
    fn duplicate_initiative_names_are_rejected_case_folded() {
        for second in ["Same", "same"] {
            let tmp = TempDir::new().unwrap();
            let path = write_toml(
                tmp.path(),
                &format!(
                    "issues_dir = \"docs/issues\"\n\n\
                     [initiatives.\"i-1\"]\nname = \"Same\"\n\n\
                     [initiatives.\"i-2\"]\nname = \"{second}\"\n"
                ),
            );
            let err = Config::load_with_warning(&path, |_| {})
                .unwrap_err()
                .to_string();
            assert!(err.contains("must be unique"), "got {err}");
        }
    }

    /// Shape is this layer's business; existence never is: a dangling reference must
    /// stay loadable and repairable (C-005).
    #[test]
    fn initiative_references_are_shape_checked_but_never_resolved() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [initiatives.\"i-1\"]\nname = \"One\"\n\
             projects = [\"p-missing\"]\nepics = [\"e-missing\"]\nmilestones = [\"2026-Q4\"]\n",
        );
        let config = Config::load_with_warning(&path, |_| {})
            .expect("a dangling reference must stay loadable");
        let initiative = &config.initiatives["i-1"];
        assert_eq!(initiative.projects, ["p-missing"]);
        assert_eq!(initiative.epics, ["e-missing"]);
        assert_eq!(initiative.milestones, ["2026-Q4"]);
    }

    /// The three stable-ID registries keep declaration order through save/reload
    /// (the map is an `IndexMap` and the session restores the header order the TOML
    /// parser loses).
    #[test]
    fn initiative_declaration_order_survives_a_save_and_reload() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [kanban.default]\ncolumns = [\"todo\", \"done\"]\n\n\
             [initiatives.\"i-zulu\"]\nname = \"Zulu\"\n\n\
             [initiatives.\"i-alpha\"]\nname = \"Alpha\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            config.initiatives.keys().collect::<Vec<_>>(),
            ["i-zulu", "i-alpha"]
        );
        config.save(&path).unwrap();
        let written = std::fs::read_to_string(&path).unwrap();
        assert!(
            written.find("[initiatives.i-zulu]").unwrap()
                < written.find("[initiatives.i-alpha]").unwrap(),
            "declaration order is preserved on write:\n{written}"
        );
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            reloaded.initiatives.keys().collect::<Vec<_>>(),
            ["i-zulu", "i-alpha"]
        );
    }

    /// `priority` reuses the shared [`crate::model::Priority`]: a known spelling is
    /// normalized by the same rule issues use, and an unknown value round-trips
    /// verbatim.
    #[test]
    fn an_initiative_priority_uses_the_shared_shape() {
        let tmp = TempDir::new().unwrap();
        let path = write_toml(
            tmp.path(),
            "issues_dir = \"docs/issues\"\n\n\
             [initiatives.\"i-1\"]\nname = \"Known\"\npriority = \"HIGH\"\n\n\
             [initiatives.\"i-2\"]\nname = \"Unknown\"\npriority = \"urgent-ish\"\n",
        );
        let config = Config::load_with_warning(&path, |_| {}).unwrap();
        assert_eq!(
            config.initiatives["i-1"].priority,
            Some(crate::model::Priority::High)
        );
        assert_eq!(
            config.initiatives["i-2"].priority,
            Some(crate::model::Priority::Other("urgent-ish".into()))
        );
        config.save(&path).unwrap();
        let reloaded = Config::load_with_warning(&path, |_| {}).unwrap();
        let written = std::fs::read_to_string(&path).unwrap();
        assert!(written.contains("priority = \"high\""), "{written}");
        assert!(written.contains("priority = \"urgent-ish\""), "{written}");
        assert_eq!(reloaded.initiatives, config.initiatives);
    }

    /// The preserved-extension map must not shadow a built-in field: `toml` would
    /// write the key twice with no duplicate detection, so an "accepted" write would
    /// make the next load fail. The check runs inside `validate_initiatives`, which
    /// every write path already goes through.
    #[test]
    fn a_shadowing_extension_key_is_refused_by_validation() {
        for key in INITIATIVE_KNOWN_FIELDS {
            let mut extensions = crate::roadmap::registry::InitiativeExtensions::default();
            extensions.insert(*key, toml::Value::String("evil".into()));
            let mut config = Config::default();
            config.initiatives.insert(
                "i-1".into(),
                InitiativeConfiguration {
                    name: "One".into(),
                    extensions,
                    ..InitiativeConfiguration::default()
                },
            );
            let err = config.validate().unwrap_err().to_string();
            assert!(
                err.contains("collides with a built-in field"),
                "{key}: got {err}"
            );
        }

        // The list is the record's own field set, kept in step by this check: a
        // field missing from it would be shadowable, and an extra name would refuse
        // a harmless extension.
        let mut config = Config::default();
        config.initiatives.insert(
            "i-1".into(),
            InitiativeConfiguration {
                name: "One".into(),
                ..InitiativeConfiguration::default()
            },
        );
        config.validate().unwrap();
    }
}