tix-tracker 0.6.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
//! `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::path::{Path, PathBuf};

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::board_store::BoardStore;
use crate::cycle_store::{CycleStore, is_implicit_default};
use crate::error::{Result, TixError};
use crate::keybindings::{EffectiveBindings, KeyBindings};
use crate::records::RecordStore;

/// 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>,
}

/// 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 `[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()
    }
}

/// 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).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, 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.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    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.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub card_order: Vec<String>,
    /// Ordering of cards within each rendered column. Default
    /// `created_at_desc` (most recently created first).
    pub order_by: OrderBy,
}

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

/// 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 `"done"`
    /// when present in `columns`, else the last configured column.
    pub fn effective_done_column(&self) -> Option<&str> {
        if let Some(done) = self.done_column.as_deref() {
            return Some(done);
        }
        if self.columns.iter().any(|c| c == "done") {
            Some("done")
        } 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`).
#[derive(Debug, Clone, PartialEq, Eq, 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>,
    /// 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]`).
    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,
    /// `[layout]`: configurable on-disk issue layout.
    #[serde(default, skip_serializing_if = "LayoutConfig::is_default")]
    pub layout: LayoutConfig,
    /// Allowed issue types.
    ///
    /// `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")]
    pub custom_types: Option<Vec<String>>,
}

/// 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`.
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`
fn is_true(value: &bool) -> bool {
    *value
}

/// The default issue types: what `tix init` writes into `custom_types`, and what
/// `tix lint` accepts when a repository carries no `custom_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",
];

/// 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(),
            filename: "{date}-{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(),
            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,
            layout: LayoutConfig::default(),
            custom_types: None,
        }
    }
}

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.custom_types = Some(DEFAULT_TYPES.iter().map(|s| (*s).to_string()).collect());
        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(),
            ));
        }
        // 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)?;
        }
        // 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)
    }

    /// 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");
    }

    /// 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 `custom_types`, or
    /// [`DEFAULT_TYPES`] when unset. Compared case-insensitively by callers.
    #[must_use]
    pub fn custom_types(&self) -> Vec<String> {
        self.custom_types
            .clone()
            .unwrap_or_else(|| DEFAULT_TYPES.iter().map(|s| (*s).to_string()).collect())
    }

    /// 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 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() {
                config.kanban = KanbanSection {
                    configurations: boards.into_iter().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| match e {
            TixError::Config(msg) => TixError::Config(format!("{}: {msg}", path.display())),
            other => other,
        })?;
        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(())
    }
}

/// 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.*]` and
/// `[teams.*]`. Names are unquoted when the header used a quoted key (e.g.
/// `[cycles."Cycle 1"]`).
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(())
}

/// 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(())
}

/// 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"
        )));
    }
    Ok(())
}

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

    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 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!(board.card_order.is_empty());
        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);
    }

    #[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 = 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(), 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"
        );
    }

    /// 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 = 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(), 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);

        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)"
        );
        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}");
    }
}