tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
use std::collections::HashMap;
use std::fmt;
use std::path::Path;

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

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

mod defaults;
#[allow(clippy::wildcard_imports)]
use defaults::*;

#[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,
    /// Empty the batch selection from the board (`X`).
    ///
    /// Its own action rather than an overload of `Unmark`: the modal's `X` empties
    /// the whole set while `x` removes one card, and the board now reads the same
    /// two keys. Canonicalizing both to one action would collapse the distinction.
    ClearMarks,
    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,
    /// Scroll the detail pane's body one row. `j`/`Down` and `k`/`Up` were freed
    /// for this when the relationship cursor moved to `Tab`/`BackTab`.
    ScrollLineDown,
    ScrollLineUp,
    /// Scroll the detail pane's body to the top (`g`) or bottom (`G`).
    ScrollTop,
    ScrollBottom,
    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 (`Tab`/`BackTab`).
    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::ClearMarks => "clear_marks",
            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::ScrollLineDown => "scroll_line_down",
            Self::ScrollLineUp => "scroll_line_up",
            Self::ScrollTop => "scroll_top",
            Self::ScrollBottom => "scroll_bottom",
            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::ClearMarks => "clear marks",
            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::ScrollLineDown => "scroll down one line",
            Self::ScrollLineUp => "scroll up one line",
            Self::ScrollTop => "scroll to top",
            Self::ScrollBottom => "scroll to bottom",
            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 `[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,
    clear_marks,
    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 `[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(default, skip_serializing_if = "Option::is_none")]
                pub $field: Option<Box<ActionBindings>>,
            )+
        }

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

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

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 `[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 `[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 `[stats]`.
    stats => Stats,
    // tix #1593: the F8 Schedule page's own section, so its keys are rebindable
    // through `[schedule]` like every other context's.
    schedule => Schedule,
    // tix #1593: the F11 Library page's own section, so its keys are rebindable
    // through `[library]` like every other context's.
    library => Library,
    // WP06: the F10 Portfolio page's own section, so its keys are rebindable
    // through `[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>>>,
}

impl KeyBindings {
    /// Load sparse TUI overrides from `tix_keybindings.toml` in `project_root`.
    ///
    /// A missing file is the default configuration, not an error. A present file
    /// deserializes directly into [`KeyBindings`], whose mode tables are sparse:
    /// omitted modes and actions overlay nothing and therefore keep their
    /// built-in chords.
    pub fn load(project_root: &Path) -> Result<Self> {
        let path = project_root.join(crate::keybindings::KEYBINDINGS_FILE);
        if !path.exists() {
            return Ok(Self::default());
        }
        let contents = std::fs::read_to_string(&path)
            .map_err(|error| TixError::Config(format!("{}: {error}", path.display())))?;
        let overrides: Self = toml::from_str(&contents)
            .map_err(|error| TixError::Config(format!("{}: {error}", path.display())))?;
        Ok(overrides)
    }

    /// Load the dedicated file and resolve it over the built-in defaults.
    pub fn load_effective(project_root: &Path) -> Result<EffectiveBindings> {
        Self::resolve(&Self::load(project_root)?)
    }

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

/// The dedicated, optional keybinding override file.
pub const KEYBINDINGS_FILE: &str = "tix_keybindings.toml";

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

    #[allow(clippy::too_many_lines)]
    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),
            // The line and end-of-body scrolls canonicalize to the keys their
            // handlers read, so `j`/`Down` both arrive as `Down` and `g`/`G` as
            // themselves (the detail pane's handler reads the canonical event).
            (_, TuiAction::ScrollLineDown) => (KeyCode::Down, KeyModifiers::NONE),
            (_, TuiAction::ScrollLineUp) => (KeyCode::Up, KeyModifiers::NONE),
            (_, TuiAction::ScrollTop) => (KeyCode::Char('g'), KeyModifiers::NONE),
            (_, TuiAction::ScrollBottom) => (KeyCode::Char('G'), 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::ClearMarks) => (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::Tab, KeyModifiers::NONE),
            (_, TuiAction::PreviousRelationship) => (KeyCode::BackTab, 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)
    }
}

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

#[cfg(test)]
mod tests;