tix-tracker 0.10.0

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

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::{Result, TixError};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InputContext {
    Board,
    /// The batch modal (WP07). Its own context so a key means one thing there and
    /// is not borrowed from the board's — `space` marks a card in a batch and is not
    /// a board action, and `y` confirms in a batch and is not a board action either.
    BulkModal,
    /// The triage inbox and its decision modal (WP06, T029/T031).
    ///
    /// Its own context for the reason `BulkModal`'s doc gives:
    /// `a`/`d`/`u`/`f` decide here and would be board actions there, and the
    /// inbox is keyboard-driven all the way down. It carries **free text** (a
    /// decline reason, a duplicate target), so `cancel` is `esc` and *only*
    /// `esc` — `q` stays a typeable letter for the same reason `LinkPrompt`
    /// keeps it.
    Triage,
    /// The F3 Cycle mode (tui-cycle-mode).
    ///
    /// Its own context for the reason `Triage`'s doc gives: `m` opens planning
    /// management here and would be a board action there, `j`/`k` walk the cycle
    /// rows, and the mode carries no free text, so `q`/`esc` may close it.
    Cycle,
    /// The F5 Milestones mode.
    ///
    /// Its own context for the reason `Cycle`'s doc gives: `m` opens planning
    /// management here, `j`/`k` walk the rows, and it carries no free text, so
    /// `q`/`esc` may close it.
    Milestones,
    /// The F6 Repos mode (tix #1529).
    ///
    /// Its own context for the reason `Cycle`'s doc gives: `j`/`k` walk the
    /// repository rows, `Enter` runs tix in the selected one, and it carries no
    /// free text, so `q`/`esc` may close it.
    Repos,
    /// The `F7` Stats page (mission `project-issue-health-status-01M3C8HX`, WP06;
    /// the **Time** tab added by `per-issue-time-tracking-01M3C9A4`, WP05).
    ///
    /// Its own context for the reason `Repos`'s doc gives: `Tab`/`Shift+Tab` switch
    /// between the page's two tabs, `j`/`k` walk the active tab's rows, `Enter` opens
    /// the selected row's issue, and the Time tab's `a`/`e`/`x`/`f`/`s`/`h` act on its
    /// entries and its scope. It carries no free text, so `q`/`esc` may close it. The
    /// mutations are the Time tab's forms, which are routed through the shared time
    /// service.
    Stats,
    /// The F8 Schedule page (tix #1593, mission `recurring-issues-01M3C7G7`).
    ///
    /// Its own context for the reason `Cycle`'s doc gives: `j`/`k` walk the series
    /// rows, `g`/`p`/`r`/`x`/`s`/`d`/`i` act on the selected series, and it carries
    /// no free text, so `q`/`esc` may close it.
    Schedule,
    /// The F11 Library page (tix #1593).
    ///
    /// Its own context for the reason `Cycle`'s doc gives: `Tab` switches between
    /// its two registries rather than moving a board field, `Enter` applies the
    /// selected view, and `j`/`k` walk rows. It carries no free text, so
    /// `q`/`esc` may close it.
    Library,
    /// The F10 **Portfolio** page (WP06, tix #1593).
    ///
    /// Its own context for the reason `Cycle`'s doc gives: `Tab`/`Shift+Tab` switch
    /// between the Projects and Epics registries, `j`/`k` walk the active tab's rows,
    /// `h`/`l` walk the selected epic's members on the Epics tab, `Enter` opens the
    /// selected member issue's detail directly (FR-004), and `q`/`esc` may close it
    /// because it carries no free text.
    Portfolio,
    Rollover,
    Detail,
    Form,
    FormPicker,
    ConfirmDelete,
    MoveIntoDone,
    /// The blocked-move acknowledgement prompt (WP04). Its own context so the
    /// command bar can advertise `y`/`esc` and nothing else.
    ConfirmBlockedMove,
    Help,
    /// The keybindings overlay's `/` input line (tix #1496).
    ///
    /// Its own context for the reason [`InputContext::Filter`] is one: it reads **free
    /// text**. Keeping the list mode's `q`/`?` bound to cancel here would rewrite them
    /// to `esc` before the handler saw them, and a query could never contain a `q` —
    /// the same trap the free-text modes below document.
    HelpSearch,
    ContextMenu,
    /// The detail pane's `related_issues` picker (#1513).
    ///
    /// Its own context so the picker's `Enter` selects a related entry and does
    /// not borrow any detail-pane key. It carries no free text, so `cancel` is
    /// `Esc`; an unbound letter is a no-op rather than a filter character.
    RelatedPicker,
    Filter,
    FilterModal,
    Settings,
    SettingsPrompt,
    PlanningManagement,
    PlanningConfirm,
    PlanningForm,
    DatePicker,
    Comment,
    Asset,
    /// The editor round trip's repair prompt (tix #1506).
    ///
    /// Its own context: every key here is a decision about a file the editor just
    /// produced — apply the proposed fix, declare the key, reopen the editor on
    /// the retained copy, acknowledge and keep it, or discard it behind a second
    /// confirmation. It is the successor to #1506's `edit_warning` context, which
    /// the same prompt grew out of; there is deliberately only one such prompt.
    EditRepair,
    /// The edit-conflict prompt (tix #1510).
    ///
    /// Its own context for the reason [`InputContext::EditRepair`] has one: it is
    /// a modal decision with three distinct outcomes, and one of them — *compare* —
    /// reopens the editor, which no board key does. It carries no free text, so a
    /// letter could close it — but only `Esc` (bound to `ignore`) does, because the
    /// prompt closes through a decision and nothing else. `q` stays unbound.
    EditConflict,
    /// The two-step create/edit relationship prompt (#1359).
    ///
    /// Free text, so `cancel` is `Esc` and **only** `Esc` — see the note on the
    /// `Asset`/`Comment`/`Filter` group for why binding `q` here would be a real
    /// defect rather than a preference: a title fragment containing `q` is ordinary.
    LinkPrompt,
    /// The top-level mode shell (tui-mode-navigation).
    ///
    /// It binds only the five mode switches and the navigation toggle. It is
    /// consulted **after** the active top-level context (Board, Triage,
    /// PlanningManagement, Settings, Form) declines the pressed key, so a
    /// context that binds the key locally always wins — which is what keeps
    /// `F2` as `open_picker` inside a form and the `F(12)` sentinel untouched
    /// for a truly unbound key.
    Shell,
    /// The saved-views modal (WP05, T024–T027).
    ///
    /// Its own context for the reason `Settings` has one: `n`, `e`, `u`, `d`, and
    /// `x` mean "new view", "rename", "update from live", "duplicate", and
    /// "delete view" in this modal and something else on the board. Nothing in the
    /// list is typeable, so ordinary letters are free to be commands.
    Views,
    /// The saved-views modal's inline name prompt (WP05, T027).
    ///
    /// A separate context because it carries **free text**: a view named `dense`
    /// must be a name and not a "duplicate" command, and a name containing `q`
    /// must not close the prompt. Only `submit` and `cancel` are bound, which is
    /// what leaves every other key a letter — the same arrangement, for the same
    /// reason, as `SettingsPrompt`.
    ViewsPrompt,
}

impl InputContext {
    pub const ALL: &'static [Self] = &[
        Self::Board,
        Self::Rollover,
        Self::Detail,
        Self::Form,
        Self::FormPicker,
        Self::ConfirmDelete,
        Self::MoveIntoDone,
        Self::ConfirmBlockedMove,
        Self::Help,
        Self::HelpSearch,
        Self::ContextMenu,
        // Walked like every other context so the overlay's completeness guard
        // sees the related picker's keys too (#1513).
        Self::RelatedPicker,
        Self::Filter,
        Self::FilterModal,
        Self::BulkModal,
        Self::Triage,
        Self::Cycle,
        Self::Milestones,
        // Walked like every other context so the overlay's guard sees the Repos
        // mode's keys too (tix #1529).
        Self::Repos,
        // Walked like every other context so the guard sees the Stats page's keys
        // too (mission `project-issue-health-status-01M3C8HX`).
        Self::Stats,
        // Walked like every other context so the guard sees the Schedule page's
        // keys too (tix #1593).
        Self::Schedule,
        // Walked like every other context so the overlay's guard sees the
        // Library page's keys too (tix #1593).
        Self::Library,
        // Walked like every other context so the guard sees the Portfolio page's
        // keys too (WP06). A context the guard does not walk is a context whose
        // keys can go undocumented.
        Self::Portfolio,
        Self::Settings,
        Self::SettingsPrompt,
        Self::PlanningManagement,
        Self::PlanningConfirm,
        Self::PlanningForm,
        Self::DatePicker,
        Self::Comment,
        Self::Asset,
        Self::EditRepair,
        // Walked like every other context so the overlay's completeness guard
        // sees the conflict prompt's keys too (tix #1510).
        Self::EditConflict,
        // Free text like the others, and missing from this list until the overlay's
        // completeness guard needed it: a context the guard does not walk is a context
        // whose keys can go undocumented.
        Self::LinkPrompt,
        // The mode shell's switches, walked like every other context so the
        // completeness guard can see them.
        Self::Shell,
        Self::Views,
        Self::ViewsPrompt,
    ];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Board => "board",
            Self::Rollover => "rollover",
            Self::Detail => "detail",
            Self::Form => "form",
            Self::FormPicker => "form_picker",
            Self::ConfirmDelete => "confirm_delete",
            Self::ConfirmBlockedMove => "confirm_blocked_move",
            Self::MoveIntoDone => "move_into_done",
            Self::Help => "help",
            Self::HelpSearch => "help_search",
            Self::ContextMenu => "context_menu",
            Self::RelatedPicker => "related_picker",
            Self::Filter => "filter",
            Self::FilterModal => "filter_modal",
            Self::BulkModal => "bulk_modal",
            Self::Settings => "settings",
            Self::SettingsPrompt => "settings_prompt",
            Self::PlanningManagement => "planning_management",
            Self::PlanningConfirm => "planning_confirm",
            Self::PlanningForm => "planning_form",
            Self::DatePicker => "date_picker",
            Self::Comment => "comment",
            Self::Asset => "asset",
            Self::EditRepair => "edit_repair",
            Self::EditConflict => "edit_conflict",
            Self::LinkPrompt => "link_prompt",
            Self::Views => "views",
            Self::ViewsPrompt => "views_prompt",
            Self::Triage => "triage",
            Self::Cycle => "cycle",
            Self::Milestones => "milestones",
            Self::Repos => "repos",
            Self::Stats => "stats",
            Self::Schedule => "schedule",
            Self::Library => "library",
            Self::Portfolio => "portfolio",
            Self::Shell => "shell",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TuiAction {
    MoveUp,
    MoveDown,
    MoveLeft,
    MoveRight,
    NextBoard,
    PreviousBoard,
    Open,
    Edit,
    Agent,
    /// Open the selected issue in a read-only viewer (tix #1507).
    ///
    /// `v` was free on both the board and the detail pane. Read-only by
    /// construction: the viewer runs on the issue file and never writes back.
    View,
    ToggleColumn,
    FilterModal,
    BulkModal,
    /// Open the triage inbox (WP06, T029). Its own action rather than a chord
    /// bolted onto another one, so `t` can be rebound from `keybindings.board`
    /// like every other board key and the help overlay can name it.
    Triage,
    /// Open the mentions view (OpenSpec change `issue-mentions`): every pending
    /// `@mention` the local user holds, across issues.
    ///
    /// Its own action rather than a chord bolted onto another one, for the reason
    /// `Triage`'s is: the chord is a rebindable board key, the help overlay can name
    /// it, and the bottom indicator row reads it back out of the effective bindings
    /// so the row cannot advertise a key the user has rebound away.
    ///
    /// The default is `i`, which was free on the board — `t` is the triage inbox, `v`
    /// the saved views, `f` the filter, and the board's letters are its navigation.
    OpenMentions,
    /// Open the saved-views modal (WP05, T024). Its own action for the reason
    /// `Triage`'s is: `v` is a rebindable board key and the help overlay names it.
    Views,
    /// Apply the view under the cursor (WP05, T025).
    ApplyView,
    /// Create a view from the live plan (WP05, T027).
    NewView,
    /// Rename the view under the cursor (WP05, T027).
    RenameView,
    /// Replace the view under the cursor's plan with the live plan (WP05, T027).
    UpdateView,
    /// Duplicate the view under the cursor under a fresh stable id (WP05, T027).
    DuplicateView,
    /// Delete the view under the cursor's **definition**, after confirmation
    /// (WP05, T027).
    DeleteView,
    Mark,
    Unmark,
    MovePrevious,
    MoveNext,
    NewIssue,
    /// Duplicate the selected issue into the create-issue form, prefilled from it
    /// (tix #1484).
    ///
    /// `C`, the capital of `c` (toggle column): a pair that reads together without
    /// changing what any existing key means, which is the same rule `B`/`A` follow.
    CloneIssue,
    /// Show the archived issues on the board, or hide them again (tix #1492).
    ///
    /// `a` was unbound on the board. The toggle is a *reload*, not a display
    /// filter: the archived files are not read until it is on.
    ToggleArchived,
    /// Show each issue's sub-issues beneath it on the board, or hide them again
    /// (tix #1399).
    ///
    /// `u` was unbound on the board. Unlike the archive toggle this is display-only:
    /// the children are already in the board state, so flipping it **reorders** the
    /// column (one level deep) rather than re-reading the store.
    ToggleChildren,
    Delete,
    Refresh,
    Settings,
    Planning,
    NewBoard,
    Help,
    Quit,
    TextFilter,
    ReorderUp,
    ReorderDown,
    Close,
    ScrollUp,
    ScrollDown,
    Comment,
    Asset,
    /// Open the create-relationship prompt from the detail view (#1359).
    NewRelationship,
    /// Re-kind or retarget the relationship under the detail pane's cursor.
    EditRelationship,
    /// Remove the relationship under the cursor, after confirmation.
    RemoveRelationship,
    /// Set, change or clear the open issue's parent from the detail pane
    /// (tix #1384).
    ///
    /// `P` was free in the detail pane. The prompt routes its write through the
    /// shared hierarchy service (`Store::set_parent`/`clear_parent`), which is
    /// the same seam `tix edit --parent` uses, so the TUI gains the
    /// set/change/clear parity for `parent` that the create-only form could not
    /// express.
    EditParent,
    /// Move the detail pane's relationship cursor.
    NextRelationship,
    PreviousRelationship,
    /// Open the picker listing the detail pane's `related_issues` entries
    /// (tix #1513).
    ///
    /// `r` was free in the detail pane — the board's `r` is `refresh`, a
    /// different context, so the two never collide.
    RelatedPicker,
    /// Follow the detail pane's selected `related_issues` entry (tix #1513).
    ///
    /// `o` was free in the detail pane and reads as "open".
    FollowRelated,
    /// Pop the detail pane's navigation stack and restore the previous issue
    /// (tix #1513).
    ///
    /// `Backspace` was free in the detail pane and reads as "back".
    NavBack,
    Submit,
    Cancel,
    Next,
    Previous,
    OpenPicker,
    Reset,
    Toggle,
    AddColumn,
    /// Move the Config mode's selected board column one position earlier
    /// (`shift+k` by default, tui-config-mode).
    MoveColumnUp,
    /// Move the Config mode's selected board column one position later
    /// (`shift+j` by default, tui-config-mode).
    MoveColumnDown,
    NewPlanningItem,
    EditPlanningItem,
    DeletePlanningItem,
    Confirm,
    Create,
    PreviousYear,
    NextYear,
    PreviousMonth,
    NextMonth,
    Reedit,
    Ignore,
    /// Declare the repair prompt's undeclared frontmatter key in `tix.toml`
    /// (tix #1506).
    ///
    /// Its own action, not `confirm`: `confirm` applies whatever fix the prompt
    /// proposes, which *happens* to be the declaration for an unknown key, while
    /// `declare_key` always means "write it into `[custom_attributes]`" and says
    /// so when there is no key to declare.
    DeclareKey,
    /// Discard the repair prompt's retained copy, after a second confirmation
    /// (tix #1506).
    ///
    /// The **only** action that removes the editor's copy. The first press arms
    /// the prompt; a second press is the decision. `Esc` deliberately
    /// acknowledges and keeps the copy instead, so a stray key cannot destroy a
    /// user's edit.
    Discard,
    /// Switch the top-level shell to the Board mode (F1 by default).
    SwitchToBoard,
    /// Switch the top-level shell to the Triage mode (F2 by default).
    SwitchToTriage,
    /// Switch the top-level shell to the Cycle mode (F4 by default).
    SwitchToCycle,
    /// Switch the top-level shell to the Milestones mode (F5 by default).
    SwitchToMilestones,
    /// Switch the top-level shell to the Repos mode (F6 by default, tix #1529).
    ///
    /// F6 was free in the shell and sits directly after the milestone switch, so
    /// the repository list reads as the last of the managed registries.
    SwitchToRepos,
    /// Switch the top-level shell to the Stats page (F7 by default).
    ///
    /// F7 was reserved in the shell until this page existed; the Stats page takes it,
    /// and its first tab is Health (mission `project-issue-health-status-01M3C8HX`).
    SwitchToStats,
    /// Open the health form for the issue in the detail pane.
    ///
    /// One action, two layers: the form's own field chooses whether the value is the
    /// issue's `current` state or an `override` layered over its derived one, so a
    /// user does not have to learn two key paths that do the same thing with one
    /// field different.
    HealthForm,
    /// Open the add-entry form on the `F7` Stats page's **Time** tab (mission
    /// `per-issue-time-tracking-01M3C9A4`, WP05 T025).
    ///
    /// One of six keys the Time tab contributes to [`InputContext::Stats`]. The key
    /// opens a form and writes nothing; the form's `Enter` is the only path that
    /// reaches the shared time service, so a stray key cannot record an entry.
    TimeAdd,
    /// Open the correction form for the Time tab's selected entry (WP05 T025).
    TimeEdit,
    /// Open the deletion form for the Time tab's selected entry (WP05 T025).
    ///
    /// A deletion removes the entry from the issue's current projection; the form asks
    /// for a reason and a confirmation, and History keeps the prior value (C-003,
    /// C-004).
    TimeDelete,
    /// Edit the Time tab's scope: issue, assignee, period (WP05 T026).
    ///
    /// It edits the **shared** `TimeFilter` the CLI's `--issue/--assignee/--from/--to`
    /// build, so a filter has one grammar and one validator.
    TimeFilter,
    /// Cycle the Time tab's breakdown dimension: all, issue, assignee, date
    /// (WP05 T026).
    TimeBreakdown,
    /// Toggle the Time tab's audit view (WP05 T027): what the current projection no
    /// longer holds but History still attributes.
    TimeHistory,
    /// Switch to the F8 Schedule page (tix #1593).
    SwitchToSchedule,
    /// Generate the selected series' due occurrence (tix #1593).
    SeriesGenerate,
    /// Pause the selected series.
    SeriesPause,
    /// Resume the selected series.
    SeriesResume,
    /// End the selected series.
    SeriesEnd,
    /// Record the selected series' due date as skipped.
    SeriesSkip,
    /// Move the selected series' candidate past its due date.
    SeriesDefer,
    /// Stop offering the selected series' due date.
    SeriesIgnore,
    /// Define a new recurring series (tix #1593).
    ///
    /// The Series tab's `n`: it opens the page's create form, whose save reaches the
    /// same `tix recurring create` service the CLI runs, with the same rule and anchor
    /// parsing and the same validation order.
    SeriesNew,
    /// Switch to the F11 Library page (tix #1593).
    SwitchToLibrary,
    /// Switch to the F10 **Portfolio** page (WP06).
    ///
    /// F10 was reserved in the shell until this page existed; the Portfolio page's
    /// Projects tab takes it.
    SwitchToPortfolio,
    /// Switch the top-level shell to the New Issue mode (F1 by default).
    SwitchToNewIssue,
    /// Switch the top-level shell to the Config mode (F12 by default).
    SwitchToConfig,
    /// Cycle the vertical navigation display state `Off`/`Small`/`Default`.
    ToggleNavigation,
}

impl TuiAction {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MoveUp => "move_up",
            Self::MoveDown => "move_down",
            Self::MoveLeft => "move_left",
            Self::MoveRight => "move_right",
            Self::NextBoard => "next_board",
            Self::PreviousBoard => "previous_board",
            Self::Open => "open",
            Self::Edit => "edit",
            Self::Agent => "agent",
            Self::View => "view",
            Self::ToggleColumn => "toggle_column",
            Self::OpenMentions => "open_mentions",
            Self::FilterModal => "filter_modal",
            Self::BulkModal => "bulk_modal",
            Self::Triage => "triage",
            Self::Views => "views",
            Self::ApplyView => "apply_view",
            Self::NewView => "new_view",
            Self::RenameView => "rename_view",
            Self::UpdateView => "update_view",
            Self::DuplicateView => "duplicate_view",
            Self::DeleteView => "delete_view",
            Self::Mark => "mark",
            Self::Unmark => "unmark",
            Self::MovePrevious => "move_previous",
            Self::MoveNext => "move_next",
            Self::NewIssue => "new_issue",
            Self::CloneIssue => "clone_issue",
            Self::ToggleArchived => "toggle_archived",
            Self::ToggleChildren => "toggle_children",
            Self::Delete => "delete",
            Self::Refresh => "refresh",
            Self::Settings => "settings",
            Self::Planning => "planning",
            Self::NewBoard => "new_board",
            Self::Help => "help",
            Self::Quit => "quit",
            Self::TextFilter => "text_filter",
            Self::ReorderUp => "reorder_up",
            Self::ReorderDown => "reorder_down",
            Self::Close => "close",
            Self::ScrollUp => "scroll_up",
            Self::ScrollDown => "scroll_down",
            Self::Comment => "comment",
            Self::Asset => "asset",
            Self::NewRelationship => "new_relationship",
            Self::EditRelationship => "edit_relationship",
            Self::RemoveRelationship => "remove_relationship",
            Self::EditParent => "edit_parent",
            Self::NextRelationship => "next_relationship",
            Self::PreviousRelationship => "previous_relationship",
            Self::RelatedPicker => "related_picker",
            Self::FollowRelated => "follow_related",
            Self::NavBack => "nav_back",
            Self::Submit => "submit",
            Self::Cancel => "cancel",
            Self::Next => "next",
            Self::Previous => "previous",
            Self::OpenPicker => "open_picker",
            Self::Reset => "reset",
            Self::Toggle => "toggle",
            Self::AddColumn => "add_column",
            Self::MoveColumnUp => "move_column_up",
            Self::MoveColumnDown => "move_column_down",
            Self::NewPlanningItem => "new_planning_item",
            Self::EditPlanningItem => "edit_planning_item",
            Self::DeletePlanningItem => "delete_planning_item",
            Self::Confirm => "confirm",
            Self::Create => "create",
            Self::PreviousYear => "previous_year",
            Self::NextYear => "next_year",
            Self::PreviousMonth => "previous_month",
            Self::NextMonth => "next_month",
            Self::Reedit => "reedit",
            Self::Ignore => "ignore",
            Self::DeclareKey => "declare_key",
            Self::Discard => "discard",
            Self::SwitchToBoard => "switch_to_board",
            Self::SwitchToTriage => "switch_to_triage",
            Self::SwitchToCycle => "switch_to_cycle",
            Self::SwitchToMilestones => "switch_to_milestones",
            Self::SwitchToRepos => "switch_to_repos",
            Self::SwitchToStats => "switch_to_stats",
            Self::HealthForm => "health_form",
            Self::TimeAdd => "time_add",
            Self::TimeEdit => "time_edit",
            Self::TimeDelete => "time_delete",
            Self::TimeFilter => "time_filter",
            Self::TimeBreakdown => "time_breakdown",
            Self::TimeHistory => "time_history",
            Self::SwitchToSchedule => "switch_to_schedule",
            Self::SeriesGenerate => "series_generate",
            Self::SeriesPause => "series_pause",
            Self::SeriesResume => "series_resume",
            Self::SeriesEnd => "series_end",
            Self::SeriesSkip => "series_skip",
            Self::SeriesDefer => "series_defer",
            Self::SeriesIgnore => "series_ignore",
            Self::SeriesNew => "series_new",
            Self::SwitchToLibrary => "switch_to_library",
            Self::SwitchToPortfolio => "switch_to_portfolio",
            Self::SwitchToNewIssue => "switch_to_new_issue",
            Self::SwitchToConfig => "switch_to_config",
            Self::ToggleNavigation => "toggle_navigation",
        }
    }

    pub const fn description(self) -> &'static str {
        match self {
            Self::MoveUp => "move up",
            Self::MoveDown => "move down",
            Self::MoveLeft => "previous column",
            Self::MoveRight => "next column",
            Self::NextBoard => "next board",
            Self::PreviousBoard => "previous board",
            Self::Open => "open detail",
            Self::Edit => "edit",
            Self::Agent => "open agent",
            Self::View => "view issue",
            Self::ToggleColumn => "toggle column",
            Self::FilterModal => "filter criteria",
            Self::BulkModal => "batch select",
            Self::Triage => "triage inbox",
            Self::OpenMentions => "mentions",
            Self::Views => "saved views",
            Self::ApplyView => "apply view",
            Self::NewView => "new view",
            Self::RenameView => "rename view",
            Self::UpdateView => "update view from live",
            Self::DuplicateView => "duplicate view",
            Self::DeleteView => "delete view",
            Self::Mark => "mark for batch",
            Self::Unmark => "unmark for batch",
            Self::MovePrevious => "move to previous column",
            Self::MoveNext => "move to next column",
            Self::NewIssue => "new issue",
            Self::CloneIssue => "clone issue",
            Self::ToggleArchived => "show archived issues",
            Self::ToggleChildren => "toggle sub-issues",
            Self::Delete => "delete",
            Self::Refresh => "refresh",
            Self::Settings => "settings",
            Self::Planning => "planning",
            Self::NewBoard => "new board",
            Self::Help => "help",
            Self::Quit => "quit",
            Self::TextFilter => "search",
            Self::ReorderUp => "reorder up",
            Self::ReorderDown => "reorder down",
            Self::Close => "close",
            Self::ScrollUp => "scroll up one page",
            Self::ScrollDown => "scroll down one page",
            Self::Comment => "comment",
            Self::Asset => "asset",
            Self::NewRelationship => "new relationship",
            Self::EditRelationship => "edit relationship",
            Self::RemoveRelationship => "remove relationship",
            Self::EditParent => "set parent",
            Self::NextRelationship => "next relationship",
            Self::PreviousRelationship => "previous relationship",
            Self::RelatedPicker => "related issues",
            Self::FollowRelated => "follow related issue",
            Self::NavBack => "back",
            Self::Submit => "submit",
            Self::Cancel => "cancel",
            Self::Next => "next",
            Self::Previous => "previous",
            Self::OpenPicker => "open picker",
            Self::Reset => "reset",
            Self::Toggle => "toggle",
            Self::AddColumn => "add column",
            Self::MoveColumnUp => "move column up",
            Self::MoveColumnDown => "move column down",
            Self::NewPlanningItem => "new",
            Self::EditPlanningItem => "edit",
            Self::DeletePlanningItem => "delete",
            Self::Confirm => "confirm",
            Self::Create => "create",
            Self::PreviousYear => "previous year",
            Self::NextYear => "next year",
            Self::PreviousMonth => "previous month",
            Self::NextMonth => "next month",
            Self::Reedit => "re-edit",
            Self::Ignore => "ignore",
            Self::DeclareKey => "declare the key in tix.toml",
            Self::Discard => "discard the edit",
            Self::SwitchToBoard => "board mode",
            Self::SwitchToTriage => "triage mode",
            Self::SwitchToCycle => "cycle mode",
            Self::SwitchToMilestones => "milestones mode",
            Self::SwitchToRepos => "repos mode",
            Self::SwitchToStats => "the Stats page",
            Self::HealthForm => "record this issue's health",
            Self::TimeAdd => "add a time entry",
            Self::TimeEdit => "correct the selected entry",
            Self::TimeDelete => "delete the selected entry",
            Self::TimeFilter => "edit the time filter",
            Self::TimeBreakdown => "cycle the breakdown",
            Self::TimeHistory => "show the audit view",
            Self::SwitchToSchedule => "schedule mode",
            Self::SeriesGenerate => "generate the due occurrence",
            Self::SeriesPause => "pause the series",
            Self::SeriesResume => "resume the series",
            Self::SeriesEnd => "end the series",
            Self::SeriesSkip => "skip the due date",
            Self::SeriesDefer => "defer the due date",
            Self::SeriesIgnore => "ignore the due date",
            Self::SeriesNew => "create a new series",
            Self::SwitchToLibrary => "library mode",
            Self::SwitchToPortfolio => "portfolio mode",
            Self::SwitchToNewIssue => "new issue mode",
            Self::SwitchToConfig => "config mode",
            Self::ToggleNavigation => "toggle navigation",
        }
    }

    /// The wording this action gets in `context`'s help.
    ///
    /// `move_left`/`move_right` walk a **column** on the board, the Config
    /// mode's two **panes** (rail ⇄ body), and a **group** in the Cycle
    /// listing; `submit` steps into the body and then activates the row there.
    /// The action — and the key — is the same event, so only the noun the help
    /// shows changes. Every other action keeps its single description.
    pub const fn description_in(self, context: InputContext) -> &'static str {
        match (context, self) {
            (InputContext::Cycle, Self::MoveLeft) => "previous group",
            (InputContext::Cycle, Self::MoveRight) => "next group",
            // tix #1593: on the Library page the two directions step between its
            // registries, not between rows.
            (InputContext::Library, Self::Previous) => "previous tab",
            (InputContext::Library, Self::Next) => "next tab",
            (InputContext::Library, Self::Submit) => "apply the selected view",
            // WP05: both of the Stats page's tabs open the selected row's issue, so the
            // one description is honest for both — the Health tab has no other meaning
            // for `Enter`, and the Time tab's row names an entry that belongs to one.
            (InputContext::Stats, Self::Submit) => "open the row's issue",
            (InputContext::Settings, Self::MoveLeft) => "previous pane",
            (InputContext::Settings, Self::MoveRight) => "next pane",
            (InputContext::Settings, Self::Submit) => "step into the body / activate row",
            // The filter modal applies ad-hoc: a pick takes effect at once and
            // closing keeps it, so both exits mean "apply and close" and the generic
            // "cancel" would read as a discard that no longer exists.
            (InputContext::FilterModal, Self::OpenPicker) => "open the focused row's picker",
            (InputContext::FilterModal, Self::Submit) => "apply and close",
            (InputContext::FilterModal, Self::Cancel) => "apply and close",
            // #1506. Every key in the repair prompt is a decision about the file
            // the editor just produced, and "confirm"/"ignore" say nothing about
            // which one — the overlay has to spell out each.
            (InputContext::EditRepair, Self::Confirm) => "apply the proposed fix",
            (InputContext::EditRepair, Self::DeclareKey) => "declare the key in tix.toml",
            (InputContext::EditRepair, Self::Reedit) => "reopen the editor on the retained copy",
            (InputContext::EditRepair, Self::Ignore) => "acknowledge (keeps the copy)",
            (InputContext::EditRepair, Self::Discard) => "discard the edit (asks again)",
            // #1510. The conflict prompt reuses the edit warning's three actions:
            // each is the same *kind* of decision, so what the key means here is
            // what the wording has to spell out.
            (InputContext::EditConflict, Self::Confirm) => "overwrite the file with this edit",
            (InputContext::EditConflict, Self::Ignore) => "keep the on-disk version",
            (InputContext::EditConflict, Self::Reedit) => "compare in the editor",
            _ => self.description(),
        }
    }
}

pub type Binding = Vec<String>;

macro_rules! partial_bindings {
    ($($field:ident),+ $(,)?) => {
        #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
        #[serde(default, deny_unknown_fields)]
        pub struct ActionBindings {
            $(
                #[serde(skip_serializing_if = "Option::is_none")]
                pub $field: Option<Binding>,
            )+
        }
    };
}

partial_bindings!(
    // The mentions view (OpenSpec change `issue-mentions`): a rebindable board
    // action, so `[keybindings.board] open_mentions = [...]` works like every other
    // board key and the bottom indicator row can read back the chord in force.
    open_mentions,
    move_up,
    move_down,
    move_left,
    move_right,
    next_board,
    previous_board,
    open,
    edit,
    agent,
    view,
    toggle_column,
    filter_modal,
    bulk_modal,
    triage,
    views,
    apply_view,
    new_view,
    rename_view,
    update_view,
    duplicate_view,
    delete_view,
    mark,
    unmark,
    move_previous,
    move_next,
    new_issue,
    clone_issue,
    toggle_archived,
    toggle_children,
    delete,
    refresh,
    settings,
    planning,
    new_board,
    help,
    quit,
    text_filter,
    reorder_up,
    reorder_down,
    close,
    scroll_up,
    scroll_down,
    comment,
    asset,
    edit_parent,
    submit,
    cancel,
    next,
    previous,
    open_picker,
    reset,
    toggle,
    add_column,
    move_column_up,
    move_column_down,
    new_planning_item,
    edit_planning_item,
    delete_planning_item,
    confirm,
    create,
    previous_year,
    next_year,
    previous_month,
    next_month,
    reedit,
    ignore,
    declare_key,
    discard,
    switch_to_board,
    switch_to_triage,
    switch_to_cycle,
    switch_to_milestones,
    switch_to_repos,
    switch_to_stats,
    health_form,
    // Mission `per-issue-time-tracking-01M3C9A4` (WP05): the Time tab's six keys, one
    // action each so every key is rebindable through `[keybindings.stats]`, appears in
    // the help overlay, and has its own canonical event the handler can read.
    time_add,
    time_edit,
    time_delete,
    time_filter,
    time_breakdown,
    time_history,
    // tix #1593.
    switch_to_schedule,
    // tix #1593: the F8 Schedule page's seven keyed actions, one action each so
    // every key is rebindable, appears in the help overlay, and has its own
    // canonical event the handler can read.
    series_generate,
    series_pause,
    series_resume,
    series_end,
    series_skip,
    series_defer,
    series_ignore,
    series_new,
    // tix #1593.
    switch_to_library,
    switch_to_portfolio,
    switch_to_new_issue,
    switch_to_config,
    toggle_navigation,
);

macro_rules! keybindings_config {
    ($($field:ident => $context:ident),+ $(,)?) => {
        #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
        #[serde(default, deny_unknown_fields)]
        pub struct KeyBindings {
            $(
                #[serde(skip_serializing_if = "ActionBindings::is_empty")]
                pub $field: ActionBindings,
            )+
        }

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

            fn overrides(&self, context: InputContext) -> &ActionBindings {
                match context {
                    $(InputContext::$context => &self.$field,)+
                }
            }
        }
    };
}

keybindings_config!(
    board => Board,
    rollover => Rollover,
    detail => Detail,
    form => Form,
    form_picker => FormPicker,
    confirm_delete => ConfirmDelete,
    confirm_blocked_move => ConfirmBlockedMove,
    help_search => HelpSearch,
    move_into_done => MoveIntoDone,
    help => Help,
    context_menu => ContextMenu,
    // #1513: the related-issues picker's own section, so its keys are rebindable
    // through `[keybindings.related_picker]` like every other context's.
    related_picker => RelatedPicker,
    filter => Filter,
    filter_modal => FilterModal,
    bulk_modal => BulkModal,
    triage => Triage,
    cycle => Cycle,
    milestones => Milestones,
    // tix #1529: the F6 Repos mode's own section, so its keys are rebindable
    // through `[keybindings.repos]` like every other context's.
    repos => Repos,
    // Mission `project-issue-health-status-01M3C8HX`: the F7 Stats page's own
    // section, so its keys are rebindable through `[keybindings.stats]`.
    stats => Stats,
    // tix #1593: the F8 Schedule page's own section, so its keys are rebindable
    // through `[keybindings.schedule]` like every other context's.
    schedule => Schedule,
    // tix #1593: the F11 Library page's own section, so its keys are rebindable
    // through `[keybindings.library]` like every other context's.
    library => Library,
    // WP06: the F10 Portfolio page's own section, so its keys are rebindable
    // through `[keybindings.portfolio]` like every other context's.
    portfolio => Portfolio,
    settings => Settings,
    settings_prompt => SettingsPrompt,
    planning_management => PlanningManagement,
    planning_confirm => PlanningConfirm,
    planning_form => PlanningForm,
    date_picker => DatePicker,
    comment => Comment,
    asset => Asset,
    edit_repair => EditRepair,
    edit_conflict => EditConflict,
    link_prompt => LinkPrompt,
    shell => Shell,
    views => Views,
    views_prompt => ViewsPrompt,
);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KeyChord {
    pub code: KeyCode,
    pub modifiers: KeyModifiers,
}

impl KeyChord {
    pub fn parse(value: &str) -> std::result::Result<Self, String> {
        let value = value.trim();
        if value.is_empty() {
            return Err("key chord must not be empty".into());
        }
        if value.chars().count() == 1 {
            let ch = value.chars().next().expect("value has one character");
            if ch.is_control() {
                return Err(format!("unsupported key name `{value}`"));
            }
            let modifiers = if ch.is_ascii_uppercase() {
                KeyModifiers::SHIFT
            } else {
                KeyModifiers::NONE
            };
            return Ok(Self {
                code: KeyCode::Char(ch),
                modifiers,
            });
        }
        let mut parts = value.split('+');
        let key = parts.next_back().ok_or("missing key name")?.trim();
        let mut modifiers = KeyModifiers::NONE;
        for part in parts {
            match part.trim().to_ascii_lowercase().as_str() {
                "ctrl" | "control" => modifiers |= KeyModifiers::CONTROL,
                "alt" | "option" => modifiers |= KeyModifiers::ALT,
                "shift" => modifiers |= KeyModifiers::SHIFT,
                "super" | "cmd" | "command" => modifiers |= KeyModifiers::SUPER,
                other => return Err(format!("unsupported modifier `{other}`")),
            }
        }
        if key.is_empty() {
            return Err("missing key name".into());
        }
        let mut code = match key.to_ascii_lowercase().as_str() {
            "backtab" => return Err("use shift+tab instead of `backtab`".into()),
            "shift+tab" => KeyCode::BackTab,
            "backspace" => KeyCode::Backspace,
            "tab" => KeyCode::Tab,
            "enter" | "return" => KeyCode::Enter,
            "esc" | "escape" => KeyCode::Esc,
            "space" => KeyCode::Char(' '),
            "left" => KeyCode::Left,
            "right" => KeyCode::Right,
            "up" => KeyCode::Up,
            "down" => KeyCode::Down,
            "home" => KeyCode::Home,
            "end" => KeyCode::End,
            "pageup" | "pgup" => KeyCode::PageUp,
            "pagedown" | "pgdn" | "pgdown" => KeyCode::PageDown,
            "delete" | "del" => KeyCode::Delete,
            "insert" | "ins" => KeyCode::Insert,
            _ => {
                if let Some(number) = key
                    .to_ascii_lowercase()
                    .strip_prefix('f')
                    .and_then(|n| n.parse::<u8>().ok())
                {
                    if (1..=12).contains(&number) {
                        KeyCode::F(number)
                    } else {
                        return Err(format!("unsupported function key `{key}`"));
                    }
                } else {
                    let mut chars = key.chars();
                    let Some(ch) = chars.next().filter(|_| chars.next().is_none()) else {
                        return Err(format!("unsupported key name `{key}`"));
                    };
                    if ch.is_control() {
                        return Err(format!("unsupported key name `{key}`"));
                    }
                    if ch.is_ascii_uppercase() {
                        modifiers |= KeyModifiers::SHIFT;
                    }
                    KeyCode::Char(ch)
                }
            }
        };
        if code == KeyCode::Tab && modifiers.contains(KeyModifiers::SHIFT) {
            code = KeyCode::BackTab;
            modifiers.remove(KeyModifiers::SHIFT);
        }
        if code == KeyCode::BackTab {
            modifiers |= KeyModifiers::SHIFT;
        }
        Ok(Self { code, modifiers })
    }

    pub fn matches(&self, event: KeyEvent) -> bool {
        if self.code != event.code {
            return false;
        }
        if self.modifiers.is_empty() {
            return event.modifiers.is_empty();
        }
        if self.code == KeyCode::BackTab {
            return event.modifiers.contains(KeyModifiers::SHIFT) || event.code == KeyCode::BackTab;
        }
        if let (KeyCode::Char(expected), KeyCode::Char(actual)) = (self.code, event.code) {
            let shift_expected = self.modifiers.contains(KeyModifiers::SHIFT);
            let normalized_expected = if shift_expected {
                expected.to_ascii_lowercase()
            } else {
                expected
            };
            let shift_actual =
                actual.is_uppercase() || event.modifiers.contains(KeyModifiers::SHIFT);
            let expected_other = self.modifiers.difference(KeyModifiers::SHIFT);
            let actual_other = event.modifiers.difference(KeyModifiers::SHIFT);
            return expected_other == actual_other
                && normalized_expected == actual.to_ascii_lowercase()
                && shift_expected == shift_actual;
        }
        event.modifiers == self.modifiers
    }

    pub fn display(&self) -> String {
        let mut out = String::new();
        if self.modifiers.contains(KeyModifiers::CONTROL) {
            out.push_str("Ctrl+");
        }
        if self.modifiers.contains(KeyModifiers::ALT) {
            out.push_str("Alt+");
        }
        if self.modifiers.contains(KeyModifiers::SUPER) {
            out.push_str("Super+");
        }
        if self.modifiers.contains(KeyModifiers::SHIFT) && self.code != KeyCode::BackTab {
            out.push_str("Shift+");
        }
        out.push_str(&match self.code {
            KeyCode::BackTab => "Shift+Tab".into(),
            KeyCode::Char(' ') => "Space".into(),
            KeyCode::Char(ch) => ch.to_string(),
            KeyCode::Enter => "Enter".into(),
            KeyCode::Esc => "Esc".into(),
            KeyCode::Left => "Left".into(),
            KeyCode::Right => "Right".into(),
            KeyCode::Up => "Up".into(),
            KeyCode::Down => "Down".into(),
            KeyCode::PageUp => "PgUp".into(),
            KeyCode::PageDown => "PgDn".into(),
            KeyCode::Delete => "Delete".into(),
            KeyCode::Insert => "Insert".into(),
            KeyCode::Home => "Home".into(),
            KeyCode::End => "End".into(),
            KeyCode::F(n) => format!("F{n}"),
            other => format!("{other:?}"),
        });
        out
    }
}

impl Serialize for KeyChord {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.display())
    }
}

impl<'de> Deserialize<'de> for KeyChord {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::parse(&value).map_err(D::Error::custom)
    }
}

impl fmt::Display for KeyChord {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.display())
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EffectiveBindings {
    modes: HashMap<InputContext, HashMap<TuiAction, Vec<KeyChord>>>,
}

fn chord(value: &str) -> KeyChord {
    KeyChord::parse(value).expect("built-in key chord must parse")
}

fn set(map: &mut HashMap<TuiAction, Vec<KeyChord>>, action: TuiAction, values: &[&str]) {
    map.insert(action, values.iter().map(|value| chord(value)).collect());
}

impl KeyBindings {
    pub fn resolve(overrides: &KeyBindings) -> Result<EffectiveBindings> {
        let mut effective = EffectiveBindings::default();
        for context in InputContext::ALL {
            let mut mode = default_mode(*context);
            overlay(&mut mode, overrides.overrides(*context), *context)?;
            effective.modes.insert(*context, mode);
        }
        Ok(effective)
    }
}

impl EffectiveBindings {
    pub fn action(&self, context: InputContext, event: KeyEvent) -> Option<TuiAction> {
        self.modes
            .get(&context)?
            .iter()
            .find_map(|(action, chords)| {
                chords
                    .iter()
                    .any(|key| key.matches(event))
                    .then_some(*action)
            })
    }

    /// Every action this context binds, sorted by name so the order is stable.
    ///
    /// For the help overlay's completeness guard: that overlay's per-context action
    /// list is written by hand, and a binding it does not name is a key that works and
    /// that nobody can discover.
    pub fn bound_actions(&self, context: InputContext) -> Vec<TuiAction> {
        let mut actions: Vec<TuiAction> = self
            .modes
            .get(&context)
            .map(|mode| mode.keys().copied().collect())
            .unwrap_or_default();
        actions.sort_by_key(|action| action.as_str());
        actions
    }

    pub fn chords(&self, context: InputContext, action: TuiAction) -> &[KeyChord] {
        self.modes
            .get(&context)
            .and_then(|mode| mode.get(&action))
            .map(Vec::as_slice)
            .unwrap_or_default()
    }

    pub fn label(&self, context: InputContext, action: TuiAction) -> String {
        let labels: Vec<String> = self
            .chords(context, action)
            .iter()
            .map(ToString::to_string)
            .collect();
        if labels.is_empty() {
            "—".into()
        } else {
            labels.join(" / ")
        }
    }

    pub fn canonical_event(&self, context: InputContext, action: TuiAction) -> KeyEvent {
        let (code, modifiers) = match (context, action) {
            (_, TuiAction::ReorderUp) => (KeyCode::Up, KeyModifiers::CONTROL),
            (_, TuiAction::ReorderDown) => (KeyCode::Down, KeyModifiers::CONTROL),
            (InputContext::Rollover, TuiAction::Previous) => (KeyCode::Tab, KeyModifiers::NONE),
            (InputContext::PlanningManagement, TuiAction::Next) => {
                (KeyCode::Tab, KeyModifiers::NONE)
            }
            (InputContext::FormPicker, TuiAction::Next) => (KeyCode::Up, KeyModifiers::NONE),
            (InputContext::FormPicker, TuiAction::Previous) => (KeyCode::Down, KeyModifiers::NONE),
            (InputContext::DatePicker, TuiAction::PreviousYear) => {
                (KeyCode::Char('['), KeyModifiers::NONE)
            }
            (InputContext::DatePicker, TuiAction::NextYear) => {
                (KeyCode::Char(']'), KeyModifiers::NONE)
            }
            (InputContext::DatePicker, TuiAction::PreviousMonth) => {
                (KeyCode::PageUp, KeyModifiers::NONE)
            }
            (InputContext::DatePicker, TuiAction::NextMonth) => {
                (KeyCode::PageDown, KeyModifiers::NONE)
            }
            (InputContext::DatePicker, TuiAction::Reset) => (KeyCode::Delete, KeyModifiers::NONE),
            // tix #1593: on the Library page `next`/`previous` step between the
            // two registries, so they must arrive as Tab/BackTab — the generic
            // arms below fold them into Down/Up, which the page's own `j`/`k`
            // already own and which would make the tab keys indistinguishable
            // from the row keys.
            (InputContext::Library, TuiAction::Next) => (KeyCode::Tab, KeyModifiers::NONE),
            (InputContext::Library, TuiAction::Previous) => (KeyCode::BackTab, KeyModifiers::NONE),
            // WP06: the Portfolio page reads two registries too, so its tab keys
            // must arrive as Tab/BackTab for the same reason — the generic arms
            // would fold them into Up/Down and make them indistinguishable from the
            // row keys.
            (InputContext::Portfolio, TuiAction::Next) => (KeyCode::Tab, KeyModifiers::NONE),
            (InputContext::Portfolio, TuiAction::Previous) => {
                (KeyCode::BackTab, KeyModifiers::NONE)
            }
            // WP05: the Stats page's two tabs switch on Tab/BackTab for the same
            // reason — the generic arms would fold them into Up/Down and make the tab
            // keys indistinguishable from the row keys, so `Tab` would stop switching.
            (InputContext::Stats, TuiAction::Next) => (KeyCode::Tab, KeyModifiers::NONE),
            (InputContext::Stats, TuiAction::Previous) => (KeyCode::BackTab, KeyModifiers::NONE),
            (InputContext::Settings, TuiAction::NewBoard) => {
                (KeyCode::Char('n'), KeyModifiers::NONE)
            }
            (InputContext::Settings, TuiAction::Delete) => (KeyCode::Char('x'), KeyModifiers::NONE),
            // #1441/#1442: `scroll_up`/`scroll_down` are **page** steps and must
            // canonicalize to themselves. The generic arms below fold them into
            // Up/Down, which is what made the detail pane's `PgUp`/`PgDn` arms dead
            // code: the key arrived canonicalized as `Down` and moved the
            // relationship cursor instead of scrolling, so a bound key did something
            // other than what it was bound to. These arms sit above the generics
            // because the match is top-down.
            (_, TuiAction::ScrollUp) => (KeyCode::PageUp, KeyModifiers::NONE),
            (_, TuiAction::ScrollDown) => (KeyCode::PageDown, KeyModifiers::NONE),
            (_, TuiAction::MoveUp | TuiAction::Previous) => (KeyCode::Up, KeyModifiers::NONE),
            (_, TuiAction::MoveDown | TuiAction::Next) => (KeyCode::Down, KeyModifiers::NONE),
            (_, TuiAction::MoveLeft) => (KeyCode::Left, KeyModifiers::NONE),
            (_, TuiAction::MoveRight) => (KeyCode::Right, KeyModifiers::NONE),
            (_, TuiAction::PreviousBoard) => (KeyCode::BackTab, KeyModifiers::NONE),
            (_, TuiAction::NextBoard) => (KeyCode::Tab, KeyModifiers::NONE),
            (_, TuiAction::Submit | TuiAction::Open | TuiAction::Ignore) => {
                (KeyCode::Enter, KeyModifiers::NONE)
            }
            (_, TuiAction::NewIssue) => (KeyCode::Char('n'), KeyModifiers::NONE),
            (_, TuiAction::CloneIssue) => (KeyCode::Char('C'), KeyModifiers::NONE),
            (_, TuiAction::ToggleArchived) => (KeyCode::Char('a'), KeyModifiers::NONE),
            (_, TuiAction::ToggleChildren) => (KeyCode::Char('u'), KeyModifiers::NONE),
            (_, TuiAction::Edit | TuiAction::EditPlanningItem) => {
                (KeyCode::Char('e'), KeyModifiers::NONE)
            }
            (_, TuiAction::Agent) => (KeyCode::Char('A'), KeyModifiers::NONE),
            // The board's `view` action is `V` (#1507): plain `v` there is the
            // saved-views modal, so the synthesized event must be the shifted
            // letter the board's own handler arm reads.
            (InputContext::Board, TuiAction::View) => (KeyCode::Char('V'), KeyModifiers::NONE),
            (_, TuiAction::View) => (KeyCode::Char('v'), KeyModifiers::NONE),
            (_, TuiAction::ToggleColumn | TuiAction::Comment) => {
                (KeyCode::Char('c'), KeyModifiers::NONE)
            }
            (_, TuiAction::FilterModal) => (KeyCode::Char('f'), KeyModifiers::NONE),
            (_, TuiAction::BulkModal) => (KeyCode::Char('B'), KeyModifiers::NONE),
            (_, TuiAction::Triage) => (KeyCode::Char('t'), KeyModifiers::NONE),
            // The mentions view's canonical event is the default chord the indicator
            // row advertises, so the board's own handler reads `i` whatever the user
            // rebound `open_mentions` to.
            (_, TuiAction::OpenMentions) => (KeyCode::Char('i'), KeyModifiers::NONE),
            // WP05. Each view action's canonical event is the key the modal's own
            // footer advertises, so a click region can synthesize exactly the key
            // the handler expects.
            (_, TuiAction::Views) => (KeyCode::Char('v'), KeyModifiers::NONE),
            (_, TuiAction::ApplyView) => (KeyCode::Enter, KeyModifiers::NONE),
            (_, TuiAction::NewView) => (KeyCode::Char('n'), KeyModifiers::NONE),
            (_, TuiAction::RenameView) => (KeyCode::Char('e'), KeyModifiers::NONE),
            (_, TuiAction::UpdateView) => (KeyCode::Char('u'), KeyModifiers::NONE),
            (_, TuiAction::DuplicateView) => (KeyCode::Char('d'), KeyModifiers::NONE),
            (_, TuiAction::DeleteView) => (KeyCode::Char('x'), KeyModifiers::NONE),
            (_, TuiAction::Mark) => (KeyCode::Char(' '), KeyModifiers::NONE),
            (_, TuiAction::Unmark) => (KeyCode::Char('x'), KeyModifiers::NONE),
            (_, TuiAction::MovePrevious) => (KeyCode::Char('<'), KeyModifiers::NONE),
            (_, TuiAction::MoveNext) => (KeyCode::Char('>'), KeyModifiers::NONE),
            (_, TuiAction::Delete) => (KeyCode::Char('d'), KeyModifiers::NONE),
            (_, TuiAction::DeletePlanningItem) => (KeyCode::Char('x'), KeyModifiers::NONE),
            (_, TuiAction::Refresh | TuiAction::Reset | TuiAction::Reedit) => {
                (KeyCode::Char('r'), KeyModifiers::NONE)
            }
            (_, TuiAction::Settings) => (KeyCode::Char('s'), KeyModifiers::NONE),
            (_, TuiAction::Planning) => (KeyCode::Char('m'), KeyModifiers::NONE),
            (_, TuiAction::NewPlanningItem) => (KeyCode::Char('n'), KeyModifiers::NONE),
            (_, TuiAction::NewBoard) => (KeyCode::Char('b'), KeyModifiers::NONE),
            (_, TuiAction::AddColumn) => (KeyCode::Char('a'), KeyModifiers::NONE),
            (_, TuiAction::MoveColumnUp) => (KeyCode::Char('K'), KeyModifiers::SHIFT),
            (_, TuiAction::MoveColumnDown) => (KeyCode::Char('J'), KeyModifiers::SHIFT),
            (_, TuiAction::Help) => (KeyCode::Char('?'), KeyModifiers::NONE),
            (_, TuiAction::Quit) => (KeyCode::Char('q'), KeyModifiers::NONE),
            (_, TuiAction::TextFilter) => (KeyCode::Char('/'), KeyModifiers::NONE),
            (_, TuiAction::Close | TuiAction::Cancel) => (KeyCode::Esc, KeyModifiers::NONE),
            (_, TuiAction::Asset) => (KeyCode::Char('a'), KeyModifiers::NONE),
            // #1359. `e` is the editor in the detail view, so re-kind is `E` — the
            // same relationship the CLI's `tix link edit <id>` changes.
            (_, TuiAction::NewRelationship) => (KeyCode::Char('n'), KeyModifiers::NONE),
            (_, TuiAction::EditRelationship) => (KeyCode::Char('E'), KeyModifiers::SHIFT),
            (_, TuiAction::RemoveRelationship) => (KeyCode::Char('d'), KeyModifiers::NONE),
            // #1384: hand the handler the key the footer advertises, not the
            // catch-all `Esc`.
            (_, TuiAction::EditParent) => (KeyCode::Char('P'), KeyModifiers::NONE),
            (_, TuiAction::NextRelationship) => (KeyCode::Char('j'), KeyModifiers::NONE),
            (_, TuiAction::PreviousRelationship) => (KeyCode::Char('k'), KeyModifiers::NONE),
            // #1513. The three related-navigation actions hand the handler the
            // key they advertise — without these arms the generic catch-all
            // would fold them into `Esc`, and `o` on a related entry would close
            // the pane instead of following the link.
            (_, TuiAction::RelatedPicker) => (KeyCode::Char('r'), KeyModifiers::NONE),
            (_, TuiAction::FollowRelated) => (KeyCode::Char('o'), KeyModifiers::NONE),
            (_, TuiAction::NavBack) => (KeyCode::Backspace, KeyModifiers::NONE),
            (_, TuiAction::OpenPicker) => (KeyCode::F(2), KeyModifiers::NONE),
            // The shell's mode switches. `F(2)` is also `open_picker`'s canonical
            // event — they are different actions in different contexts, which is
            // exactly why mode switching is scoped to the shell context and a form's
            // `F2` keeps its picker meaning.
            (_, TuiAction::SwitchToBoard) => (KeyCode::F(3), KeyModifiers::NONE),
            (_, TuiAction::SwitchToTriage) => (KeyCode::F(2), KeyModifiers::NONE),
            (_, TuiAction::SwitchToCycle) => (KeyCode::F(4), KeyModifiers::NONE),
            (_, TuiAction::SwitchToMilestones) => (KeyCode::F(5), KeyModifiers::NONE),
            (_, TuiAction::SwitchToRepos) => (KeyCode::F(6), KeyModifiers::NONE),
            // Mission `project-issue-health-status-01M3C8HX` (WP06): F7 was reserved
            // in the shell until its page existed; the Stats page takes it.
            (_, TuiAction::SwitchToStats) => (KeyCode::F(7), KeyModifiers::NONE),
            // The health form's key. `handle_detail_key` reads raw keys, so its
            // canonical event must be that key: without this the default (`Esc`) is
            // what the handler sees, and the key meant to open the form would close
            // the pane instead.
            (_, TuiAction::HealthForm) => (KeyCode::Char('H'), KeyModifiers::NONE),
            // WP05: the Time tab's commands canonicalize to their own letters, so the
            // handler reads one event per action however the user rebound it. Without
            // these the catch-all would fold all six into `Esc` — closing the page
            // instead of acting.
            (_, TuiAction::TimeAdd) => (KeyCode::Char('a'), KeyModifiers::NONE),
            (_, TuiAction::TimeEdit) => (KeyCode::Char('e'), KeyModifiers::NONE),
            (_, TuiAction::TimeDelete) => (KeyCode::Char('x'), KeyModifiers::NONE),
            (_, TuiAction::TimeFilter) => (KeyCode::Char('f'), KeyModifiers::NONE),
            (_, TuiAction::TimeBreakdown) => (KeyCode::Char('s'), KeyModifiers::NONE),
            (_, TuiAction::TimeHistory) => (KeyCode::Char('h'), KeyModifiers::NONE),
            // tix #1593: F8 was free in the shell; the Schedule page takes it.
            (_, TuiAction::SwitchToSchedule) => (KeyCode::F(8), KeyModifiers::NONE),
            // The Schedule page's actions canonicalize to their own letters: the
            // handler reads the canonical event, so each action needs one.
            (_, TuiAction::SeriesGenerate) => (KeyCode::Char('g'), KeyModifiers::NONE),
            (_, TuiAction::SeriesPause) => (KeyCode::Char('p'), KeyModifiers::NONE),
            (_, TuiAction::SeriesResume) => (KeyCode::Char('r'), KeyModifiers::NONE),
            (_, TuiAction::SeriesEnd) => (KeyCode::Char('x'), KeyModifiers::NONE),
            (_, TuiAction::SeriesSkip) => (KeyCode::Char('s'), KeyModifiers::NONE),
            (_, TuiAction::SeriesDefer) => (KeyCode::Char('d'), KeyModifiers::NONE),
            (_, TuiAction::SeriesIgnore) => (KeyCode::Char('i'), KeyModifiers::NONE),
            // The Series tab's create key: the handler opens the form when it reads
            // this canonical event, so a rebind still lands there.
            (_, TuiAction::SeriesNew) => (KeyCode::Char('n'), KeyModifiers::NONE),
            // tix #1593: F11 was free in the shell; the Library page follows the
            // repos list.
            (_, TuiAction::SwitchToLibrary) => (KeyCode::F(11), KeyModifiers::NONE),
            // WP06: F10 was reserved in the shell; the Portfolio page takes it.
            (_, TuiAction::SwitchToPortfolio) => (KeyCode::F(10), KeyModifiers::NONE),
            (_, TuiAction::SwitchToNewIssue) => (KeyCode::F(1), KeyModifiers::NONE),
            (_, TuiAction::SwitchToConfig) => (KeyCode::F(12), KeyModifiers::NONE),
            (_, TuiAction::ToggleNavigation) => (KeyCode::Char('n'), KeyModifiers::CONTROL),
            (_, TuiAction::Toggle) => (KeyCode::Char(' '), KeyModifiers::NONE),
            (_, TuiAction::Confirm) => (KeyCode::Char('y'), KeyModifiers::NONE),
            // #1506. The repair prompt's own two decisions canonicalize to the
            // keys the prompt advertises, so `handle_edit_repair_key` reads a
            // canonical `d`/`x` however the user reached the action.
            (_, TuiAction::DeclareKey) => (KeyCode::Char('d'), KeyModifiers::NONE),
            (_, TuiAction::Discard) => (KeyCode::Char('x'), KeyModifiers::NONE),
            (_, TuiAction::Create) => (KeyCode::Char('+'), KeyModifiers::NONE),
            _ => (KeyCode::Esc, KeyModifiers::NONE),
        };
        KeyEvent::new(code, modifiers)
    }
}

fn defaults(values: &[(&str, &[&str])]) -> HashMap<TuiAction, Vec<KeyChord>> {
    let mut map = HashMap::new();
    for (action, keys) in values {
        let action = match *action {
            "move_up" => TuiAction::MoveUp,
            "move_down" => TuiAction::MoveDown,
            "move_left" => TuiAction::MoveLeft,
            "move_right" => TuiAction::MoveRight,
            "next_board" => TuiAction::NextBoard,
            "previous_board" => TuiAction::PreviousBoard,
            "open" => TuiAction::Open,
            "edit" => TuiAction::Edit,
            "agent" => TuiAction::Agent,
            "view" => TuiAction::View,
            "toggle_column" => TuiAction::ToggleColumn,
            "filter_modal" => TuiAction::FilterModal,
            "bulk_modal" => TuiAction::BulkModal,
            "triage" => TuiAction::Triage,
            "open_mentions" => TuiAction::OpenMentions,
            "views" => TuiAction::Views,
            "apply_view" => TuiAction::ApplyView,
            "new_view" => TuiAction::NewView,
            "rename_view" => TuiAction::RenameView,
            "update_view" => TuiAction::UpdateView,
            "duplicate_view" => TuiAction::DuplicateView,
            "delete_view" => TuiAction::DeleteView,
            "mark" => TuiAction::Mark,
            "unmark" => TuiAction::Unmark,
            "move_previous" => TuiAction::MovePrevious,
            "move_next" => TuiAction::MoveNext,
            "new_issue" => TuiAction::NewIssue,
            "clone_issue" => TuiAction::CloneIssue,
            "toggle_archived" => TuiAction::ToggleArchived,
            "toggle_children" => TuiAction::ToggleChildren,
            "delete" => TuiAction::Delete,
            "refresh" => TuiAction::Refresh,
            "settings" => TuiAction::Settings,
            "planning" => TuiAction::Planning,
            "new_board" => TuiAction::NewBoard,
            "help" => TuiAction::Help,
            "quit" => TuiAction::Quit,
            "text_filter" => TuiAction::TextFilter,
            "reorder_up" => TuiAction::ReorderUp,
            "reorder_down" => TuiAction::ReorderDown,
            "close" => TuiAction::Close,
            "scroll_up" => TuiAction::ScrollUp,
            "scroll_down" => TuiAction::ScrollDown,
            "comment" => TuiAction::Comment,
            "asset" => TuiAction::Asset,
            "new_relationship" => TuiAction::NewRelationship,
            "edit_relationship" => TuiAction::EditRelationship,
            "remove_relationship" => TuiAction::RemoveRelationship,
            "edit_parent" => TuiAction::EditParent,
            "next_relationship" => TuiAction::NextRelationship,
            "previous_relationship" => TuiAction::PreviousRelationship,
            "related_picker" => TuiAction::RelatedPicker,
            "follow_related" => TuiAction::FollowRelated,
            "nav_back" => TuiAction::NavBack,
            "submit" => TuiAction::Submit,
            "cancel" => TuiAction::Cancel,
            "next" => TuiAction::Next,
            "previous" => TuiAction::Previous,
            "open_picker" => TuiAction::OpenPicker,
            "reset" => TuiAction::Reset,
            "toggle" => TuiAction::Toggle,
            "add_column" => TuiAction::AddColumn,
            "move_column_up" => TuiAction::MoveColumnUp,
            "move_column_down" => TuiAction::MoveColumnDown,
            "new_planning_item" => TuiAction::NewPlanningItem,
            "edit_planning_item" => TuiAction::EditPlanningItem,
            "delete_planning_item" => TuiAction::DeletePlanningItem,
            "confirm" => TuiAction::Confirm,
            "create" => TuiAction::Create,
            "previous_year" => TuiAction::PreviousYear,
            "next_year" => TuiAction::NextYear,
            "previous_month" => TuiAction::PreviousMonth,
            "next_month" => TuiAction::NextMonth,
            "reedit" => TuiAction::Reedit,
            "ignore" => TuiAction::Ignore,
            "declare_key" => TuiAction::DeclareKey,
            "discard" => TuiAction::Discard,
            "switch_to_board" => TuiAction::SwitchToBoard,
            "switch_to_triage" => TuiAction::SwitchToTriage,
            "switch_to_cycle" => TuiAction::SwitchToCycle,
            "switch_to_milestones" => TuiAction::SwitchToMilestones,
            "switch_to_repos" => TuiAction::SwitchToRepos,
            "switch_to_stats" => TuiAction::SwitchToStats,
            "health_form" => TuiAction::HealthForm,
            "time_add" => TuiAction::TimeAdd,
            "time_edit" => TuiAction::TimeEdit,
            "time_delete" => TuiAction::TimeDelete,
            "time_filter" => TuiAction::TimeFilter,
            "time_breakdown" => TuiAction::TimeBreakdown,
            "time_history" => TuiAction::TimeHistory,
            "switch_to_schedule" => TuiAction::SwitchToSchedule,
            "series_generate" => TuiAction::SeriesGenerate,
            "series_pause" => TuiAction::SeriesPause,
            "series_resume" => TuiAction::SeriesResume,
            "series_end" => TuiAction::SeriesEnd,
            "series_skip" => TuiAction::SeriesSkip,
            "series_defer" => TuiAction::SeriesDefer,
            "series_ignore" => TuiAction::SeriesIgnore,
            "series_new" => TuiAction::SeriesNew,
            "switch_to_library" => TuiAction::SwitchToLibrary,
            "switch_to_portfolio" => TuiAction::SwitchToPortfolio,
            "switch_to_new_issue" => TuiAction::SwitchToNewIssue,
            "switch_to_config" => TuiAction::SwitchToConfig,
            "toggle_navigation" => TuiAction::ToggleNavigation,
            _ => unreachable!(),
        };
        set(&mut map, action, keys);
    }
    map
}

fn default_mode(context: InputContext) -> HashMap<TuiAction, Vec<KeyChord>> {
    match context {
        InputContext::Board => defaults(&[
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            // tix #1442 (follow-up): a screen of cards. They have to be *bound* for the
            // board to see them at all: `App::handle_key` routes an unbound key in a
            // non-text context to `F(12)` rather than passing it through, which is why
            // `PgUp`/`PgDn` did nothing here while the wheel next to them worked. They
            // canonicalize to `PageUp`/`PageDown`, so the handler can tell a page from
            // a row.
            ("scroll_up", &["pgup"]),
            ("scroll_down", &["pgdn"]),
            ("move_left", &["left", "h"]),
            ("move_right", &["right", "l"]),
            ("next_board", &["tab"]),
            ("previous_board", &["shift+tab"]),
            ("open", &["enter"]),
            ("edit", &["e"]),
            // #1507: read the selected card in the resolved viewer, read-only.
            // The viewer keeps `v` in the **Detail** context; on the board `v` is
            // the saved-views modal (WP05 — 11 tests, and documented in
            // `README.md`, `docs/key-bindings.md` and `docs/saved-views.md`), so
            // the board's viewer chord is the shifted letter, matching the board's
            // `A`/`B`/`C`/`J`/`K` family.
            ("view", &["V"]),
            ("agent", &["A"]),
            ("toggle_column", &["c"]),
            ("filter_modal", &["f"]),
            ("bulk_modal", &["B"]),
            // WP06: the triage inbox. `t` was unbound, so this adds a key
            // rather than changing what any existing one means.
            ("triage", &["t"]),
            // The mentions view: `i` was unbound on the board, and the bottom
            // indicator row spells the chord it is bound to.
            ("open_mentions", &["i"]),
            // WP05: the saved-views modal. `v` was unbound, for the same reason.
            ("views", &["v"]),
            // The chord is spelled `space`, not a literal blank: `KeyChord::parse`
            // trims its input, so a bare `" "` is the empty chord and every
            // built-in binding panics at startup.
            ("mark", &["space"]),
            ("unmark", &["x"]),
            ("move_previous", &["<"]),
            ("move_next", &[">"]),
            ("new_issue", &["n"]),
            // #1484: the capital of `c` (toggle column), not a new letter — the
            // board's free letters are its navigation, and `C` keeps "clone" beside
            // the toggle it is the second half of.
            ("clone_issue", &["C"]),
            // #1492: `a` was free on the board, and "archived" is what it means.
            ("toggle_archived", &["a"]),
            // #1399: `u` was free on the board; "sub-issues" is what it shows.
            ("toggle_children", &["u"]),
            ("delete", &["d"]),
            ("refresh", &["r"]),
            ("settings", &["s"]),
            ("planning", &["m", "M"]),
            ("new_board", &["b"]),
            ("help", &["?"]),
            ("quit", &["q", "Q", "esc"]),
            ("text_filter", &["/"]),
            // #1586: `Shift+K`/`Shift+Up` and `Shift+J`/`Shift+Down` reorder the
            // selected card exactly as `Ctrl+Up`/`Ctrl+Down` do — the same
            // move the mouse drag performs. The shifted letters are free on the
            // board (plain `k`/`j` are the cursor), so this adds keys without
            // changing what any existing one means.
            ("reorder_up", &["ctrl+up", "shift+up", "K"]),
            ("reorder_down", &["ctrl+down", "shift+down", "J"]),
        ]),
        InputContext::Rollover => defaults(&[
            ("submit", &["enter"]),
            ("previous", &["left", "right", "tab"]),
            ("cancel", &["esc"]),
        ]),
        InputContext::Detail => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("edit", &["e"]),
            // #1507: view the open issue in the resolved read-only viewer.
            ("view", &["v"]),
            ("scroll_up", &["pgup"]),
            ("scroll_down", &["pgdn"]),
            ("help", &["?"]),
            ("comment", &["c"]),
            ("asset", &["a"]),
            // #1359: the three mutating relationship operations, plus the cursor
            // that names which edge `E` and `d` act on. `e` stays the editor, so
            // re-kind is `E`.
            ("new_relationship", &["n"]),
            ("edit_relationship", &["E"]),
            ("remove_relationship", &["d"]),
            // #1384: `P` was free in the detail pane. Set/change/clear the open
            // issue's parent through the shared hierarchy service, which is the
            // TUI half of `tix edit --parent` that the create-only form could
            // not express.
            ("edit_parent", &["P"]),
            ("next_relationship", &["j", "down"]),
            ("previous_relationship", &["k", "up"]),
            // #1513: the related-issues surface. `r` lists them, `o` follows the
            // selected one, `Backspace` returns to the previous pane. `j`/`k`
            // keep moving the **relationship** cursor; the picker is the
            // selection surface for related entries.
            ("related_picker", &["r"]),
            ("follow_related", &["o"]),
            ("nav_back", &["backspace"]), // Mission `project-issue-health-status-01M3C8HX` (WP06): the health form, on
            // the issue the pane is showing.
            ("health_form", &["H"]),
        ]),
        InputContext::RelatedPicker => defaults(&[
            ("cancel", &["esc"]),
            ("next", &["down"]),
            ("previous", &["up"]),
            ("submit", &["enter"]),
        ]),
        InputContext::Form | InputContext::PlanningForm => defaults(&[
            ("cancel", &["esc"]),
            ("submit", &["enter"]),
            ("next", &["tab", "down"]),
            ("previous", &["shift+tab", "up"]),
            ("open_picker", &["f2"]),
        ]),
        InputContext::FormPicker => defaults(&[
            ("cancel", &["esc", "f2"]),
            ("next", &["up"]),
            ("previous", &["down"]),
            ("submit", &["enter"]),
            ("create", &["+", "insert"]),
        ]),
        InputContext::ConfirmDelete => defaults(&[("confirm", &["y", "Y"]), ("cancel", &["esc"])]),
        // `n` cancels as well as `esc`: a yes/no prompt whose only "no" is a
        // non-printing key is a trap for anyone who does not know it.
        InputContext::ConfirmBlockedMove => defaults(&[
            ("confirm", &["y", "Y", "enter"]),
            ("cancel", &["n", "N", "esc"]),
        ]),
        // Free-text entry. `cancel` is **`esc` only**, and that is load-bearing
        // rather than a style choice.
        //
        // All four of these read arbitrary text into a buffer — a commit message, a
        // comment body, a **filesystem path**, a filter string. Binding `q` to cancel
        // means the letter `q` cannot be typed, and it is worse than that: the
        // binding resolves to the action's canonical event (`esc`), so `q` does not
        // merely fail to type, it **leaves the mode**, and every character after it
        // is then interpreted as a command in the mode underneath.
        //
        // This was found by a test flake (#1305), not by inspection. The asset
        // round-trip test types the source path through `handle_key`, and the path
        // came from a `tempfile` temp directory whose six random characters are drawn
        // from `[A-Za-z0-9]`. Roughly one run in forty produced a name containing a
        // `q`; the prompt closed mid-path and the rest of the string was applied as
        // Detail-mode keys — which is how a run came to report
        // `status = "Commented by …"` and no asset at all. A user attaching an asset
        // from a path containing `q` gets the same thing, and it silently creates a
        // comment on the issue.
        //
        // The test was at fault for depending on a random name, but the behaviour is
        // a real defect, so the binding moves rather than the fixture. `esc` remains
        // the cancel key, which is already this codebase's convention for text entry
        // — `FilterModal` and `ConfirmDelete` both bind `esc` and nothing else.
        //
        // `q`-to-close is kept where there is no text to type: `Help`,
        // `ContextMenu`, `Settings`, `PlanningManagement`, `DatePicker`, and the
        // yes/no `ConfirmBlockedMove` keep it.
        InputContext::MoveIntoDone
        | InputContext::Comment
        | InputContext::Asset
        | InputContext::Filter => defaults(&[("cancel", &["esc"]), ("submit", &["enter"])]),
        // The overlay and the context menu are *not* the same surface, and sharing a
        // context made them one: a binding added for the overlay (`pgup`/`pgdn`, tix
        // #1441) would silently become a context-menu key too. They share a key set
        // today only by coincidence, so they get their own arms.
        InputContext::Help => defaults(&[
            ("cancel", &["esc", "q", "?"]),
            ("next", &["down", "j"]),
            ("previous", &["up", "k"]),
            ("submit", &["enter"]),
            // #1496: `/` filters the list. Bound rather than handled as a raw key so it
            // is rebindable like everything else — and so the overlay's own rows name
            // it, since a search nobody knows about is a search nobody uses.
            ("text_filter", &["/"]),
            // #1441/#1442: one page at a time. These have to be *bound* for the
            // overlay to see them at all — `App::handle_key` routes an unbound key in
            // a non-text context to `F(12)` rather than passing it through — and they
            // canonicalize to themselves so the handler can tell a page from a row.
            ("scroll_up", &["pgup"]),
            ("scroll_down", &["pgdn"]),
        ]),
        // The issue action menu. It reads **free text**: letters filter the
        // list, so only the navigation keys are bound here and `allows_text_fallback`
        // keeps `j`/`k`/`q`/`?` typeable.
        InputContext::ContextMenu => defaults(&[
            ("cancel", &["esc"]),
            ("next", &["down"]),
            ("previous", &["up"]),
            ("submit", &["enter"]),
            ("scroll_up", &["pgup"]),
            ("scroll_down", &["pgdn"]),
        ]),
        // The overlay's `/` input (tix #1496): free text, so `cancel` is `Esc` and only
        // `Esc`. `q` and `?` stay ordinary characters here — binding them to cancel
        // would rewrite them to `esc` inside `App::handle_key`, before the handler saw
        // them, and a query could never contain a `q`.
        InputContext::HelpSearch => defaults(&[("cancel", &["esc"]), ("submit", &["enter"])]),
        InputContext::BulkModal => defaults(&[
            ("cancel", &["esc"]),
            ("next", &["tab", "down"]),
            ("previous", &["shift+tab", "up"]),
            ("submit", &["enter"]),
        ]),
        // WP06. Five bindings and nothing else, because every remaining inbox
        // key (`q`, `j`, `k`, `a`, `d`, `u`, `f`, `p`, `y`, `?`) has to arrive
        // **raw**: a decline reason containing `q` and a duplicate target
        // containing `a` are ordinary, and `allows_text_fallback` is what keeps
        // them letters instead of turning them into a close or an accept.
        InputContext::Triage => defaults(&[
            ("cancel", &["esc"]),
            ("submit", &["enter"]),
            ("move_up", &["up"]),
            ("move_down", &["down"]),
            ("toggle", &["space"]),
        ]),
        // The F3 Cycle mode (tui-cycle-mode). `m` opens the planning-management
        // surface for the same reason the board binds it: it is where cycles and
        // milestones are created, renamed, and deleted. Nothing here collides with
        // the surface's own keys, so opening it from this mode is unambiguous.
        InputContext::Cycle => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            // The listing's horizontal axis: `h`/`l` and the arrows land on the
            // first entry of the previous / next rendered group.
            ("move_left", &["left", "h"]),
            ("move_right", &["right", "l"]),
            ("planning", &["m"]),
            ("help", &["?"]),
        ]),
        // The F5 Milestones mode. `m`, `j`/`k`, `q`/`esc` mirror the Cycle
        // listing: it is the same kind of registry view. The planning commands
        // (`n`/`e`/`x`, `Enter` to edit) are bound here too, so the milestone
        // registry is editable from its own mode and not only from F12.
        InputContext::Milestones => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("submit", &["enter"]),
            ("new_planning_item", &["n"]),
            ("edit_planning_item", &["e"]),
            ("delete_planning_item", &["x", "X"]),
            ("planning", &["m"]),
            ("help", &["?"]),
        ]),
        // The F6 Repos mode (tix #1529). `j`/`k` walk the list, `Enter` runs tix
        // in the selected repository, and `q`/`esc` leave. No free text, so the
        // letters are safe as close keys.
        // The F7 Stats page: its two tabs and each tab's own keys.
        //
        // `Tab`/`Shift+Tab` switch between the Health and Time tabs; `Enter` opens the
        // selected Health row's issue's detail (where the health form lives);
        // `j`/`k` walk the active tab's rows; and `q`/`esc` leave. No free text, so the
        // letters are safe as close and command keys.
        //
        // The Time tab's six commands are all **inert without `Enter`**: `a`/`e`/`x`
        // open a form, `f` opens the filter editor, and `s`/`h` change only what the
        // tab is showing — so no key on the page writes anything by itself (WP05).
        InputContext::Stats => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("next", &["tab"]),
            ("previous", &["shift+tab"]),
            ("submit", &["enter"]),
            ("time_add", &["a"]),
            ("time_edit", &["e"]),
            ("time_delete", &["x"]),
            ("time_filter", &["f"]),
            ("time_breakdown", &["s"]),
            ("time_history", &["h"]),
            ("help", &["?"]),
        ]),
        InputContext::Repos => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("submit", &["enter"]),
            ("help", &["?"]),
        ]),
        // The F8 Schedule page (tix #1593): `j`/`k` walk the series rows and the
        // action keys are free letters on a page that carries no free text.
        InputContext::Schedule => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("series_new", &["n"]),
            ("series_generate", &["g"]),
            ("series_pause", &["p"]),
            ("series_resume", &["r"]),
            ("series_end", &["x"]),
            ("series_skip", &["s"]),
            ("series_defer", &["d"]),
            ("series_ignore", &["i"]),
            ("help", &["?"]),
        ]),
        // The F11 Library page (tix #1593). It reads two registries, so the tab
        // keys are its own: `tab`/`h` and `shift+tab`/`l` switch between Views and
        // Templates, `j`/`k` (and the arrows) walk rows, and `enter` applies the
        // selected view. No free text, so `q`/`esc` may close it.
        InputContext::Library => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("next", &["tab", "l", "right"]),
            ("previous", &["shift+tab", "h", "left"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("submit", &["enter"]),
            ("help", &["?"]),
        ]),
        // The F10 Portfolio page's Projects tab (WP06). It reads one registry, so it
        // has no tab keys: `j`/`k` (and the arrows) walk the project rows, the pane
        // beside them is read-only, and `q`/`esc` may close it because it carries no
        // free text.
        InputContext::Portfolio => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("next", &["tab"]),
            ("previous", &["shift+tab"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("move_left", &["left", "h"]),
            ("move_right", &["right", "l"]),
            ("submit", &["enter"]),
            ("help", &["?"]),
        ]),
        // The filter modal is picker-backed: `enter` (and `l`/`right`) open the
        // focused criterion's value list, or the calendar on a date row, so the
        // open-picker action owns them. `submit` moves to plain `a`, which is what
        // commits. **Not `ctrl+enter`**: without the kitty keyboard protocol a
        // terminal sends the same byte as plain `enter`, so the chord would be
        // unreachable. Both rewrite to their canonical event before the handler
        // runs — `open_picker` to `F(2)`, `submit` to `Enter` — so the handler can
        // tell "open the list" from "apply the filter" without seeing the chord.
        // WP05. The list is a menu: `n`/`e`/`u`/`d`/`x` are commands, so this
        // context deliberately has **no** text fallback — an unbound key is inert
        // rather than typed. The prompt beside it is the opposite, which is why
        // they are two contexts rather than one.
        InputContext::Views => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("apply_view", &["enter"]),
            ("new_view", &["n"]),
            ("rename_view", &["e"]),
            ("update_view", &["u"]),
            ("duplicate_view", &["d"]),
            ("delete_view", &["x", "X"]),
        ]),
        // Free text, so `submit`/`cancel` only and `cancel` is `esc` **alone**: a
        // view name containing `q` is ordinary, and binding it here would close
        // the prompt and apply the rest of the name as commands underneath.
        InputContext::ViewsPrompt => defaults(&[("cancel", &["esc"]), ("submit", &["enter"])]),
        InputContext::FilterModal => defaults(&[
            ("cancel", &["esc"]),
            ("next", &["tab", "down"]),
            ("previous", &["shift+tab", "up"]),
            ("reset", &["r", "R"]),
            ("submit", &["a"]),
            ("open_picker", &["f2", "enter", "l", "right"]),
        ]),
        // The F12 Config mode's sections (tui-config-mode). The dashboards
        // section edits the active board, so `tab`/`shift+tab` switch boards
        // (`next_board`/`previous_board`, whose canonical events are Tab and
        // BackTab). `left`/`right` move the pane focus between the section rail
        // and the body, and `up`/`down` move inside the focused pane — the
        // section when the rail is focused, the row when the body is. `n`/`e`/`x`
        // are the new/rename/delete keys in both the dashboards section and the
        // cycles/milestones sections — the section decides what they act on.
        //
        // `enter` is `submit`, not a second `toggle` chord: it steps from the
        // rail into the body and then activates the row, while `space` keeps
        // toggling wherever the cursor is. Both bound to `toggle` would
        // canonicalize to the same event and there would be no Enter behaviour
        // to implement.
        InputContext::Settings => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("next_board", &["tab", "]"]),
            ("previous_board", &["shift+tab", "["]),
            ("move_left", &["left", "h"]),
            ("move_right", &["right", "l"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("toggle", &["space"]),
            ("submit", &["enter"]),
            ("add_column", &["a"]),
            ("move_column_up", &["K"]),
            ("move_column_down", &["J"]),
            ("new_board", &["n"]),
            ("edit_planning_item", &["e"]),
            ("delete", &["x", "X"]),
        ]),
        InputContext::SettingsPrompt => defaults(&[
            ("cancel", &["esc", "q", "Q"]),
            ("submit", &["enter", "y", "Y"]),
        ]),
        InputContext::PlanningManagement => defaults(&[
            ("close", &["q", "Q", "esc"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            // The segments (Cycles / Milestones) are a horizontal axis, so the
            // horizontal movement keys switch them — the same rule the Config
            // rail's vertical section list deliberately does not follow: there
            // `h`/`l` are the pane axis and `j`/`k` walk the sections.
            ("move_left", &["left", "h"]),
            ("move_right", &["right", "l"]),
            ("next", &["tab", "shift+tab"]),
            ("new_planning_item", &["n"]),
            ("edit_planning_item", &["e"]),
            ("delete_planning_item", &["x", "X"]),
        ]),
        InputContext::PlanningConfirm => {
            defaults(&[("confirm", &["y", "Y", "enter"]), ("cancel", &["esc"])])
        }
        InputContext::DatePicker => defaults(&[
            ("cancel", &["esc", "q"]),
            ("submit", &["enter"]),
            ("move_up", &["up", "k"]),
            ("move_down", &["down", "j"]),
            ("move_left", &["left", "h"]),
            ("move_right", &["right", "l"]),
            ("previous_month", &["pgup"]),
            ("next_month", &["pgdn"]),
            ("previous_year", &["["]),
            ("next_year", &["]"]),
            ("reset", &["delete", "c", "C"]),
        ]),
        // #1506/#1510. The repair prompt the editor round trip raises when the
        // saved file has a problem: apply the proposed fix, declare the key,
        // reopen the editor on the retained copy, acknowledge, or discard.
        // `confirm` keeps `a`/`y` — the chord #1506's warning advertised — and
        // every other key is a decision, never a stray exit. `discard` is `x`
        // and requires a second press; `Esc` acknowledges and **keeps** the copy.
        InputContext::EditRepair => defaults(&[
            ("confirm", &["a", "y"]),
            ("declare_key", &["d", "D"]),
            ("reedit", &["r", "R"]),
            ("ignore", &["i", "I", "enter", "esc"]),
            ("discard", &["x", "X"]),
        ]),
        // #1510. The conflict prompt: overwrite, abandon, compare. The chords are
        // the ones the handler's arms key on — `handle_key` rewrites a bound key to
        // its action's canonical event, which is `y` for `confirm`, `Enter` for
        // `ignore`, and `r` for `reedit` — so every chord listed here arrives as
        // that canonical code. `Esc` is bound to `ignore`, which is what makes it
        // the safe default the prompt promises. `q` is deliberately *not* bound:
        // the prompt closes only through a decision it names.
        InputContext::EditConflict => defaults(&[
            ("confirm", &["o", "O", "y", "Y"]),
            ("ignore", &["a", "A", "esc"]),
            ("reedit", &["c", "C", "r", "R"]),
        ]),
        // The mode shell (tui-mode-navigation). Five switches and a display-state
        // toggle, nothing else: every other key belongs to the active mode, and this
        // context is consulted only when that mode declines the key.
        InputContext::Shell => defaults(&[
            ("switch_to_new_issue", &["f1"]),
            ("switch_to_triage", &["f2"]),
            ("switch_to_board", &["f3"]),
            ("switch_to_cycle", &["f4"]),
            ("switch_to_milestones", &["f5"]),
            // #1529: F6 was free in the shell; the repo list follows the
            // milestone registry.
            ("switch_to_repos", &["f6"]),
            // Mission `project-issue-health-status-01M3C8HX` (WP06): F7 now has its
            // page — the Stats page's Health tab.
            ("switch_to_stats", &["f7"]),
            // #1593: F7 stays reserved; F8 is the Schedule page, whose Series tab
            // ships with the recurring-issues mission.
            ("switch_to_schedule", &["f8"]),
            // WP06: F10 was the last reserved page key; the Portfolio page's
            // Projects tab takes it.
            ("switch_to_portfolio", &["f10"]),
            // #1593: F11 is the Library page.
            ("switch_to_library", &["f11"]),
            ("switch_to_config", &["f12"]),
            ("toggle_navigation", &["ctrl+n"]),
        ]),
        // #1359. Free text, so `q` must be typeable: a title fragment or a path
        // containing `q` is unremarkable, and binding it to cancel closes the prompt
        // and applies the rest of the input as commands underneath. See the note on
        // the `Asset`/`Comment`/`Filter` group for the full reasoning.
        InputContext::LinkPrompt => defaults(&[("cancel", &["esc"]), ("submit", &["enter"])]),
    }
}

macro_rules! overlay_fields {
    ($map:ident, $overrides:ident, $context:expr, $($field:ident => $action:ident),+ $(,)?) => {
        $(
            if let Some(values) = &$overrides.$field {
                let mut chords = Vec::with_capacity(values.len());
                for value in values {
                    chords.push(KeyChord::parse(value).map_err(|message| TixError::Config(format!(
                        "`keybindings.{}.{}`: {message}", $context.as_str(), stringify!($field)
                    )))?);
                }
                if chords.is_empty() {
                    return Err(TixError::Config(format!(
                        "`keybindings.{}.{}` must not be empty", $context.as_str(), stringify!($field)
                    )));
                }
                $map.insert(TuiAction::$action, chords);
            }
        )+
    };
}

fn overlay(
    map: &mut HashMap<TuiAction, Vec<KeyChord>>,
    overrides: &ActionBindings,
    context: InputContext,
) -> Result<()> {
    overlay_fields!(map, overrides, context,
        move_up => MoveUp, move_down => MoveDown, move_left => MoveLeft, move_right => MoveRight,
        next_board => NextBoard, previous_board => PreviousBoard, open => Open, edit => Edit,
        agent => Agent, view => View, toggle_column => ToggleColumn, filter_modal => FilterModal,
        bulk_modal => BulkModal, mark => Mark, unmark => Unmark, triage => Triage,
        open_mentions => OpenMentions,
        views => Views, apply_view => ApplyView, new_view => NewView,
        rename_view => RenameView, update_view => UpdateView,
        duplicate_view => DuplicateView, delete_view => DeleteView,
        move_previous => MovePrevious, move_next => MoveNext, new_issue => NewIssue,
        clone_issue => CloneIssue,
        toggle_archived => ToggleArchived,
        toggle_children => ToggleChildren,
        delete => Delete, refresh => Refresh, settings => Settings, planning => Planning,
        new_board => NewBoard, help => Help, quit => Quit, text_filter => TextFilter, reorder_up => ReorderUp,
        reorder_down => ReorderDown, close => Close, scroll_up => ScrollUp, scroll_down => ScrollDown,
        comment => Comment, asset => Asset, edit_parent => EditParent,
        submit => Submit, cancel => Cancel, next => Next,
        previous => Previous, open_picker => OpenPicker, reset => Reset, toggle => Toggle,
        add_column => AddColumn, move_column_up => MoveColumnUp, move_column_down => MoveColumnDown,
        new_planning_item => NewPlanningItem,
        edit_planning_item => EditPlanningItem, delete_planning_item => DeletePlanningItem,
        confirm => Confirm, create => Create, previous_year => PreviousYear, next_year => NextYear,
        previous_month => PreviousMonth, next_month => NextMonth, reedit => Reedit, ignore => Ignore,
        declare_key => DeclareKey, discard => Discard,
        switch_to_board => SwitchToBoard, switch_to_triage => SwitchToTriage,
        switch_to_cycle => SwitchToCycle, switch_to_milestones => SwitchToMilestones,
        switch_to_repos => SwitchToRepos,
        switch_to_stats => SwitchToStats, health_form => HealthForm,
        time_add => TimeAdd, time_edit => TimeEdit, time_delete => TimeDelete,
        time_filter => TimeFilter, time_breakdown => TimeBreakdown, time_history => TimeHistory,
        switch_to_schedule => SwitchToSchedule,
        series_generate => SeriesGenerate, series_pause => SeriesPause,
        series_resume => SeriesResume, series_end => SeriesEnd,
        series_skip => SeriesSkip, series_defer => SeriesDefer,
        series_ignore => SeriesIgnore,
        series_new => SeriesNew,
        switch_to_new_issue => SwitchToNewIssue,
        switch_to_library => SwitchToLibrary,
        switch_to_portfolio => SwitchToPortfolio,
        switch_to_new_issue => SwitchToNewIssue,
        switch_to_config => SwitchToConfig, toggle_navigation => ToggleNavigation,
    );
    let mut seen: HashMap<KeyChord, TuiAction> = HashMap::new();
    for (action, chords) in map {
        for key in chords {
            if let Some(previous) = seen.insert(*key, *action) {
                return Err(TixError::Config(format!(
                    "`keybindings.{}`: `{}` is assigned to both `{}` and `{}`",
                    context.as_str(),
                    key,
                    previous.as_str(),
                    action.as_str()
                )));
            }
        }
    }
    Ok(())
}

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

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

    #[test]
    fn parses_and_normalizes_documented_chords() {
        assert_eq!(KeyChord::parse("ESC").unwrap(), chord("esc"));
        assert_eq!(KeyChord::parse("Enter").unwrap(), chord("enter"));
        assert_eq!(KeyChord::parse("LEFT").unwrap(), chord("left"));
        assert_eq!(KeyChord::parse("PgUp").unwrap(), chord("pgup"));
        assert_eq!(KeyChord::parse("F2").unwrap(), chord("f2"));
        assert_eq!(KeyChord::parse("Ctrl+UP").unwrap(), chord("ctrl+up"));
        assert_eq!(KeyChord::parse("A").unwrap().display(), "Shift+A");
        assert!(KeyChord::parse("ctrl+wat").is_err());
        assert!(KeyChord::parse("f99").is_err());
    }

    #[test]
    fn defaults_validate_and_cross_mode_reuse_is_allowed() {
        let defaults = KeyBindings::resolve(&KeyBindings::default()).unwrap();
        assert!(
            defaults
                .action(
                    InputContext::Board,
                    KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE)
                )
                .is_some()
        );
        let mut overrides = KeyBindings::default();
        overrides.board.open = Some(vec!["f4".into()]);
        overrides.detail.close = Some(vec!["f4".into()]);
        assert!(KeyBindings::resolve(&overrides).is_ok());
    }

    #[test]
    fn filter_modal_opens_the_picker_and_commits_on_the_apply_key() {
        let bindings = KeyBindings::resolve(&KeyBindings::default()).unwrap();
        let ctx = InputContext::FilterModal;
        // `enter`, `l` and `right` all open the focused row's picker and rewrite to
        // the action's canonical event, so the handler sees one key rather than
        // three. A regression here would make `enter` commit again (the pre-overhaul
        // behavior) with no handler change to notice it.
        for code in [KeyCode::Enter, KeyCode::Char('l'), KeyCode::Right] {
            let event = KeyEvent::new(code, KeyModifiers::NONE);
            let action = bindings.action(ctx, event);
            assert_eq!(
                action,
                Some(TuiAction::OpenPicker),
                "{code:?} must open the focused row's picker"
            );
            assert_eq!(
                bindings.canonical_event(ctx, TuiAction::OpenPicker),
                KeyEvent::new(KeyCode::F(2), KeyModifiers::NONE),
                "{code:?} must canonicalize to the picker's F2"
            );
        }
        // A plain, always-deliverable key commits. It canonicalizes to `enter` so
        // the handler can tell it apart from the opener — and it is deliberately not
        // `ctrl+enter`, which a terminal without the kitty keyboard protocol sends
        // as the same byte as plain `enter`.
        let commit = KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE);
        assert_eq!(bindings.action(ctx, commit), Some(TuiAction::Submit));
        assert_eq!(
            bindings.canonical_event(ctx, TuiAction::Submit),
            KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)
        );
        // The plain `enter` that opens the picker is not the one that commits.
        assert_eq!(
            bindings.action(ctx, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)),
            Some(TuiAction::OpenPicker)
        );
        assert!(
            bindings
                .action(ctx, KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL))
                .is_none(),
            "the unreachable `ctrl+enter` chord must not be bound at all"
        );
    }

    #[test]
    fn board_binds_v_to_views_and_shift_v_to_view_and_detail_keeps_v() {
        let bindings = KeyBindings::resolve(&KeyBindings::default()).unwrap();
        // The board's `v` is the saved-views modal (WP05), so the read-only viewer
        // (#1507) takes the shifted letter there; Detail has no views modal and
        // keeps the plain `v`.
        let board_view = KeyEvent::new(KeyCode::Char('V'), KeyModifiers::NONE);
        assert_eq!(
            bindings.action(InputContext::Board, board_view),
            Some(TuiAction::View),
            "the board must bind `V` to view"
        );
        assert_eq!(
            bindings.canonical_event(InputContext::Board, TuiAction::View),
            board_view,
            "`view` must canonicalize to the board's own chord so the handler sees it as typed"
        );
        assert_eq!(
            bindings.action(
                InputContext::Board,
                KeyEvent::new(KeyCode::Char('v'), KeyModifiers::NONE)
            ),
            Some(TuiAction::Views),
            "the board must bind `v` to the saved-views modal"
        );
        let detail_view = KeyEvent::new(KeyCode::Char('v'), KeyModifiers::NONE);
        assert_eq!(
            bindings.action(InputContext::Detail, detail_view),
            Some(TuiAction::View),
            "Detail must bind `v` to view"
        );
        assert_eq!(
            bindings.canonical_event(InputContext::Detail, TuiAction::View),
            detail_view,
            "`view` must canonicalize to `v` in Detail"
        );
    }

    /// The conflict prompt's three decisions (#1510): every choice is reachable by
    /// two chords, and each pair resolves to an action whose canonical event is the
    /// code the handler's arms read (`y`, `Enter`, `r`) — the indirection that makes
    /// `Esc` abandon and `c` compare without a chord name in the logic.
    #[test]
    fn the_conflict_prompt_binds_overwrite_abandon_and_compare() {
        let bindings = KeyBindings::resolve(&KeyBindings::default()).unwrap();
        let cases = [
            (KeyCode::Char('o'), TuiAction::Confirm),
            (KeyCode::Char('y'), TuiAction::Confirm),
            (KeyCode::Char('a'), TuiAction::Ignore),
            (KeyCode::Esc, TuiAction::Ignore),
            (KeyCode::Char('c'), TuiAction::Reedit),
            (KeyCode::Char('r'), TuiAction::Reedit),
        ];
        for (code, action) in cases {
            assert_eq!(
                bindings.action(
                    InputContext::EditConflict,
                    KeyEvent::new(code, KeyModifiers::NONE)
                ),
                Some(action),
                "{code:?} must be {action:?} in the conflict prompt"
            );
        }
        // …and the canonical events are what `handle_edit_conflict_key` matches on,
        // so the mapping is asserted rather than assumed.
        for (action, expected) in [
            (TuiAction::Confirm, KeyCode::Char('y')),
            (TuiAction::Ignore, KeyCode::Enter),
            (TuiAction::Reedit, KeyCode::Char('r')),
        ] {
            assert_eq!(
                bindings.canonical_event(InputContext::EditConflict, action),
                KeyEvent::new(expected, KeyModifiers::NONE),
                "{action:?} must hand the handler `{expected:?}`"
            );
        }
        // A key nobody bound does nothing: `q` must not close the prompt.
        assert_eq!(
            bindings.action(
                InputContext::EditConflict,
                KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE)
            ),
            None
        );
    }

    /// The Config mode's column reordering (tui-config-mode). `Shift+K`/
    /// `Shift+J` move the selected column; they are distinct from the plain
    /// `k`/`j` cursor moves, they accept the documented TOML override, and a
    /// conflict inside the same context is still rejected.
    #[test]
    fn settings_binds_column_moves_distinct_from_the_cursor() {
        let bindings = KeyBindings::resolve(&KeyBindings::default()).unwrap();
        let shifted = |ch: char| KeyEvent::new(KeyCode::Char(ch), KeyModifiers::SHIFT);
        assert_eq!(
            bindings.action(InputContext::Settings, shifted('K')),
            Some(TuiAction::MoveColumnUp)
        );
        assert_eq!(
            bindings.action(InputContext::Settings, shifted('J')),
            Some(TuiAction::MoveColumnDown)
        );
        // Plain `k`/`j` stay the cursor; only the shifted pair reorders.
        assert_eq!(
            bindings.action(
                InputContext::Settings,
                KeyEvent::new(KeyCode::Char('k'), KeyModifiers::NONE)
            ),
            Some(TuiAction::MoveUp)
        );
        assert_eq!(
            bindings.action(
                InputContext::Settings,
                KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE)
            ),
            Some(TuiAction::MoveDown)
        );
        // The canonical events are the uppercase codes the handler matches on.
        assert_eq!(
            bindings.canonical_event(InputContext::Settings, TuiAction::MoveColumnUp),
            shifted('K')
        );
        assert_eq!(
            bindings.canonical_event(InputContext::Settings, TuiAction::MoveColumnDown),
            shifted('J')
        );

        // The documented TOML fields load and take effect.
        let mut overrides = KeyBindings::default();
        overrides.settings.move_column_up = Some(vec!["ctrl+u".into()]);
        overrides.settings.move_column_down = Some(vec!["ctrl+d".into()]);
        let overridden = KeyBindings::resolve(&overrides).unwrap();
        assert_eq!(
            overridden.action(
                InputContext::Settings,
                KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL)
            ),
            Some(TuiAction::MoveColumnUp)
        );
        assert_eq!(
            overridden.action(
                InputContext::Settings,
                KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL)
            ),
            Some(TuiAction::MoveColumnDown)
        );

        // A same-context conflict is still rejected, naming the mode and action.
        let mut conflict = KeyBindings::default();
        conflict.settings.move_column_up = Some(vec!["a".into()]);
        let error = KeyBindings::resolve(&conflict).unwrap_err().to_string();
        assert!(
            error.contains("settings") && error.contains("move_column_up"),
            "the conflict must name the mode and the action: {error}"
        );
    }

    /// Task 5.4: `i` is bound to the mentions view on the board, resolves without a
    /// conflict against every other board default, and canonicalizes back to `i` — so
    /// the board's own handler can read the key it advertises.
    #[test]
    fn the_mentions_view_binds_i_on_the_board_without_a_conflict() {
        let bindings = KeyBindings::resolve(&KeyBindings::default())
            .expect("adding open_mentions must not conflict with an existing board chord");
        let key = KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE);
        assert_eq!(
            bindings.action(InputContext::Board, key),
            Some(TuiAction::OpenMentions)
        );
        assert_eq!(
            bindings.canonical_event(InputContext::Board, TuiAction::OpenMentions),
            key
        );
        assert_eq!(
            bindings
                .chords(InputContext::Board, TuiAction::OpenMentions)
                .len(),
            1
        );
        // The action is reachable by name from `tix.toml`, like every other one.
        let mut overrides = KeyBindings::default();
        overrides.board.open_mentions = Some(vec!["ctrl+m".into()]);
        let rebound = KeyBindings::resolve(&overrides).expect("a rebind resolves");
        assert_eq!(
            rebound.action(
                InputContext::Board,
                KeyEvent::new(KeyCode::Char('m'), KeyModifiers::CONTROL)
            ),
            Some(TuiAction::OpenMentions)
        );
    }

    #[test]
    fn conflicts_report_mode_and_actions() {
        let mut overrides = KeyBindings::default();
        overrides.board.open = Some(vec!["ctrl+n".into()]);
        overrides.board.new_issue = Some(vec!["ctrl+n".into()]);
        let error = KeyBindings::resolve(&overrides).unwrap_err().to_string();
        assert!(error.contains("board") && error.contains("open") && error.contains("new_issue"));
    }

    #[test]
    fn shell_defaults_resolve_mode_switches_and_toggle() {
        let bindings = KeyBindings::resolve(&KeyBindings::default()).unwrap();
        // F1 New Issue, F2 Triage, F3 Board, F4 Cycles, F5 Milestones,
        // F6 Repos (tix #1529), F12 Config.
        let cases = [
            (KeyCode::F(1), TuiAction::SwitchToNewIssue),
            (KeyCode::F(2), TuiAction::SwitchToTriage),
            (KeyCode::F(3), TuiAction::SwitchToBoard),
            (KeyCode::F(4), TuiAction::SwitchToCycle),
            (KeyCode::F(5), TuiAction::SwitchToMilestones),
            (KeyCode::F(6), TuiAction::SwitchToRepos),
            (KeyCode::F(12), TuiAction::SwitchToConfig),
        ];
        for (code, action) in cases {
            assert_eq!(
                bindings.action(InputContext::Shell, KeyEvent::new(code, KeyModifiers::NONE)),
                Some(action),
                "{code:?} must switch modes in the shell"
            );
            assert_eq!(
                bindings.canonical_event(InputContext::Shell, action),
                KeyEvent::new(code, KeyModifiers::NONE),
                "{action:?} must canonicalize to its default chord"
            );
        }
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::Char('n'), KeyModifiers::CONTROL)
            ),
            Some(TuiAction::ToggleNavigation)
        );
        // F6 switches to the Repos mode (tix #1529); F8 and F11 are the Schedule
        // and Library pages (tix #1593) — the first of the reserved keys to be
        // spent.
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::F(8), KeyModifiers::NONE)
            ),
            Some(TuiAction::SwitchToSchedule)
        );
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::F(11), KeyModifiers::NONE)
            ),
            Some(TuiAction::SwitchToLibrary)
        );
        // WP06: F10 was reserved too, and the Portfolio page's Projects tab took
        // it.
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::F(10), KeyModifiers::NONE)
            ),
            Some(TuiAction::SwitchToPortfolio)
        );
        // F9 stays reserved: the shell binds nothing there until its page exists.
        // `#1593` reserves F9 for the Data page (Import/Export, Archive, Duplicates),
        // and this mission's epic surface is the F10 Portfolio page's Epics tab — so
        // F9 is deliberately **not** spent here. F7 left this list when mission
        // `project-issue-health-status-01M3C8HX` gave it the Stats page's Health tab,
        // and F10 left it with the Portfolio page (WP06).
        assert_eq!(
            bindings.action(
                InputContext::Shell,
                KeyEvent::new(KeyCode::F(9), KeyModifiers::NONE)
            ),
            None,
            "F9 must stay unbound in the shell until the Data page exists"
        );
    }

    #[test]
    fn shell_conflict_reports_both_actions_and_mode() {
        let mut overrides = KeyBindings::default();
        overrides.shell.switch_to_board = Some(vec!["f2".into()]);
        overrides.shell.switch_to_triage = Some(vec!["f2".into()]);
        let error = KeyBindings::resolve(&overrides).unwrap_err().to_string();
        assert!(
            error.contains("shell")
                && error.contains("switch_to_board")
                && error.contains("switch_to_triage"),
            "got {error:?}"
        );
    }
}