chainview 0.1.2

Terminal UI for option chains, Greeks and volatility - real-time market data and backtest replay in your terminal.
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
//! The single-source keybinding map โ€” pure data + resolution, no rendering
//! (`docs/05-views-and-ux.md` ยง3).
//!
//! # One map, read by both dispatch and the overlay
//!
//! [`KEYMAP`] is the **single source of truth** for every key ChainView acts on.
//! It lives in the **application** layer (this module) so both the key dispatch
//! ([`resolve_global`], read by
//! [`App::dispatch_key_global`](crate::App::dispatch_key_global), and
//! [`resolve_replay`], read by the replay screen) and the help overlay
//! (`src/ui/theme.rs`, which imports [`help_sections`]) read one table โ€” a bound
//! key and its documentation **cannot drift** (proved by the cross-check test
//! below). The overlay renderer depends on this module (`ui โ†’ application`), never
//! the reverse: this module holds no `ratatui` type. Global keys work in every
//! screen; screen-local keys are additive.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::app::{LiveScreen, Mode, ReplayScreen};

// ---------------------------------------------------------------------------
// Key chords + contexts.
// ---------------------------------------------------------------------------

/// A normalized, comparable, displayable key chord (`docs/05-views-and-ux.md`
/// ยง3). The keymap matches on these rather than raw crossterm events, so a binding
/// is provider- and platform-independent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyChord {
    /// A plain character key (space is `Char(' ')`, labelled `Space`).
    Char(char),
    /// A `Ctrl`-modified character key, lower-cased (`Ctrl-c`).
    Ctrl(char),
    /// The up arrow.
    Up,
    /// The down arrow.
    Down,
    /// The left arrow.
    Left,
    /// The right arrow.
    Right,
    /// The Enter/Return key.
    Enter,
    /// The Escape key.
    Esc,
    /// The Tab key.
    Tab,
    /// Shift-Tab (crossterm's `BackTab`), labelled `S-Tab`.
    BackTab,
    /// The Home key.
    Home,
    /// The End key.
    End,
}

impl KeyChord {
    /// Normalize a crossterm [`KeyEvent`] into a [`KeyChord`], or `None` for a key
    /// outside the keymap vocabulary.
    ///
    /// [`KeyCode`] is crossterm's **open, `#[non_exhaustive]`** vocabulary, so the
    /// catch-all is required and correct here โ€” an unmapped key normalizes to
    /// `None` and the dispatch forwards it (or ignores it).
    #[must_use]
    pub fn from_event(key: KeyEvent) -> Option<Self> {
        if key.modifiers.contains(KeyModifiers::CONTROL)
            && let KeyCode::Char(c) = key.code
        {
            return Some(Self::Ctrl(c.to_ascii_lowercase()));
        }
        match key.code {
            KeyCode::Char(c) => Some(Self::Char(c)),
            KeyCode::Up => Some(Self::Up),
            KeyCode::Down => Some(Self::Down),
            KeyCode::Left => Some(Self::Left),
            KeyCode::Right => Some(Self::Right),
            KeyCode::Enter => Some(Self::Enter),
            KeyCode::Esc => Some(Self::Esc),
            KeyCode::Tab => Some(Self::Tab),
            KeyCode::BackTab => Some(Self::BackTab),
            KeyCode::Home => Some(Self::Home),
            KeyCode::End => Some(Self::End),
            _ => None,
        }
    }
}

/// The context a binding is active in (`docs/05-views-and-ux.md` ยง3). `Global`
/// keys work everywhere; `Any` documents keys (like `Esc`) that mean the same in
/// every screen; the mode-scoped variants are screen-local and additive.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Context {
    /// Works in every screen, resolved at the global dispatch level.
    Global,
    /// Documented as active in any screen (e.g. `Esc` โ€” ascend / close overlay).
    Any,
    /// Active only on the given live screen.
    Live(LiveScreen),
    /// Active only on the given replay screen.
    Replay(ReplayScreen),
}

// ---------------------------------------------------------------------------
// Actions.
// ---------------------------------------------------------------------------

/// The semantic action a binding performs, grouped by scope so each scope's
/// resolution stays exhaustive and wildcard-free (`docs/05-views-and-ux.md` ยง3).
///
/// Actions whose bodies land in a later issue (chain nav #18, surface/payoff v0.2,
/// depth v0.5, most replay controls v0.3) are declared here so the map documents
/// them; the map is the source of truth and a later issue wires the body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    /// A global action (quit / help / screen switch / cycle / reconnect / reload).
    Global(GlobalAction),
    /// A chain-screen action.
    Chain(ChainAction),
    /// A depth-screen action.
    Depth(DepthAction),
    /// A surface-screen action.
    Surface(SurfaceAction),
    /// A payoff-screen action.
    Payoff(PayoffAction),
    /// A replay-screen action.
    Replay(ReplayAction),
    /// Ascend focus / close overlay (`Esc`, context [`Context::Any`]).
    Ascend,
}

/// A global-level action declared in the map (`docs/05-views-and-ux.md` ยง3). The
/// concrete screen-switch slot is derived from the pressed digit at resolution
/// time (see [`resolve_global`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum GlobalAction {
    /// Quit (terminal restored on the way out).
    Quit,
    /// Toggle the modal help overlay.
    ToggleHelp,
    /// Switch to the screen the pressed number key selects (reachable only).
    SwitchScreen,
    /// Cycle to the next reachable screen.
    NextScreen,
    /// Cycle to the previous reachable screen.
    PrevScreen,
    /// Refresh / reconnect the active provider (Live).
    Reconnect,
    /// Mode reload โ€” re-open the bundle (Replay) / re-discover the provider (Live).
    Rediscover,
}

/// The resolved global command, with the screen-switch slot bound
/// (`docs/05-views-and-ux.md` ยง3). `App::dispatch_key_global` matches this
/// exhaustively.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlobalCommand {
    /// Quit.
    Quit,
    /// Toggle the help overlay.
    ToggleHelp,
    /// Switch to the screen bound to slot `1..=4` (reachable only).
    SwitchScreen(u8),
    /// Cycle to the next reachable screen.
    NextScreen,
    /// Cycle to the previous reachable screen.
    PrevScreen,
    /// Reconnect the active provider.
    Reconnect,
    /// Reload the mode (re-discover / re-open the bundle).
    Rediscover,
}

/// A chain-screen action (`docs/05-views-and-ux.md` ยง3); bodies land in #18.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ChainAction {
    /// Move the strike selection (`โ†‘โ†“` / `kj`).
    MoveStrike,
    /// Switch expiration (`โ†โ†’` / `hl`).
    SwitchExpiry,
    /// Previous / next underlying (`[` / `]`).
    SwitchUnderlying,
    /// Focus the call / put leg of the cursor strike (`c` / `p`).
    FocusLeg,
    /// Drill into the selected strike (`Enter`).
    Drill,
    /// Add the focused leg to the payoff builder (`a`).
    AddLeg,
}

/// A depth-screen action (`docs/05-views-and-ux.md` ยง3); body lands in v0.5.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DepthAction {
    /// Scroll the depth ladder (`โ†‘โ†“`).
    Scroll,
}

/// A surface-screen action (`docs/05-views-and-ux.md` ยง3); bodies wired in #47.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum SurfaceAction {
    /// Cycle the Greek/IV/Price axis (`g` forward / `G` back).
    CycleGreek,
    /// Cycle the view `smile โ†’ curve โ†’ surface` (`x`).
    ToggleView,
}

/// A payoff-screen action (`docs/05-views-and-ux.md` ยง3); bodies land in v0.2.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PayoffAction {
    /// Add a leg at the cursor strike/side (`a`).
    AddLeg,
    /// Remove the leg under the cursor (`x`).
    RemoveLeg,
    /// Increase / decrease the cursor leg's quantity (`+` / `-`).
    Quantity,
    /// Toggle the cursor leg buy / sell (`s`).
    ToggleSide,
    /// Commit the built strategy (`Enter`).
    Commit,
    /// Cancel the builder (`Esc`).
    Cancel,
    /// Toggle expiration / t+0 curve (`t`).
    ToggleCurve,
}

/// A replay-screen action (`docs/05-views-and-ux.md` ยง3). The scrub, end-jump,
/// play/pause, and speed actions have bodies now (via `AppEvent::ReplaySeek` /
/// `AppEvent::ReplayControl`, #34); the fill drill-down (`,` / `.`) lands with the
/// drill-down render (#35+).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ReplayAction {
    /// Play / pause the timeline (`Space`).
    PlayPause,
    /// Playback speed slower (`-`).
    SpeedSlower,
    /// Playback speed faster (`+`).
    SpeedFaster,
    /// Step the scrub head back one step (`โ†` / `h`).
    StepBack,
    /// Step the scrub head forward one step (`โ†’` / `l`).
    StepForward,
    /// Previous fill (drill-down, `,`).
    PrevFill,
    /// Next fill (drill-down, `.`).
    NextFill,
    /// Jump to the start of the run (`Home`).
    JumpStart,
    /// Jump to the end of the run (`End`).
    JumpEnd,
}

// ---------------------------------------------------------------------------
// The map.
// ---------------------------------------------------------------------------

/// One row of the keybinding map: its context, its semantic action, the chords
/// that trigger it, the label the overlay/keybar show, and its help text
/// (`docs/05-views-and-ux.md` ยง3).
#[derive(Debug, Clone, Copy)]
pub struct Binding {
    /// The context the binding is active in.
    pub context: Context,
    /// The semantic action.
    pub action: Action,
    /// The chords that trigger the action (for dispatch + cross-check).
    pub chords: &'static [KeyChord],
    /// The human label shown in the overlay/keybar (e.g. `โ†‘โ†“ / kj`).
    pub keys_label: &'static str,
    /// The one-line description shown in the overlay.
    pub help: &'static str,
    /// `Some(version)` when the key **resolves and is documented** but its body is
    /// **not yet wired** (its `handle_key` is a no-op pending later I/O plumbing) โ€”
    /// the help overlay renders a dim `(<version>)` suffix so `?` honestly advertises
    /// which advertised keys are not live yet, instead of presenting a dead key as a
    /// working feature (`docs/05-views-and-ux.md` ยง3, the honesty ethos). `None` for
    /// a live, wired key. This marks + documents only; it never changes resolution.
    pub deferred: Option<&'static str>,
}

/// The single source of truth for every key ChainView acts on
/// (`docs/05-views-and-ux.md` ยง3). Both the dispatch ([`resolve_global`],
/// [`resolve_replay`]) and the help overlay (`src/ui/theme.rs`, via
/// `help_sections`) read this one table, so a bound key and its documentation
/// cannot drift.
pub static KEYMAP: &[Binding] = &[
    // -- Global (all wired) ----------------------------------------------------
    Binding {
        context: Context::Global,
        action: Action::Global(GlobalAction::Quit),
        chords: &[KeyChord::Char('q'), KeyChord::Ctrl('c')],
        keys_label: "q / Ctrl-C",
        help: "Quit",
        deferred: None,
    },
    Binding {
        context: Context::Global,
        action: Action::Global(GlobalAction::ToggleHelp),
        chords: &[KeyChord::Char('?')],
        keys_label: "?",
        help: "Toggle help",
        deferred: None,
    },
    Binding {
        context: Context::Global,
        action: Action::Global(GlobalAction::SwitchScreen),
        chords: &[
            KeyChord::Char('1'),
            KeyChord::Char('2'),
            KeyChord::Char('3'),
            KeyChord::Char('4'),
        ],
        keys_label: "1-4",
        help: "Switch screen",
        deferred: None,
    },
    Binding {
        context: Context::Global,
        action: Action::Global(GlobalAction::NextScreen),
        chords: &[KeyChord::Tab],
        keys_label: "Tab",
        help: "Next screen",
        deferred: None,
    },
    Binding {
        context: Context::Global,
        action: Action::Global(GlobalAction::PrevScreen),
        chords: &[KeyChord::BackTab],
        keys_label: "S-Tab",
        help: "Previous screen",
        deferred: None,
    },
    Binding {
        context: Context::Global,
        action: Action::Global(GlobalAction::Reconnect),
        chords: &[KeyChord::Char('r')],
        keys_label: "r",
        help: "Reconnect provider",
        deferred: None,
    },
    Binding {
        context: Context::Global,
        action: Action::Global(GlobalAction::Rediscover),
        chords: &[KeyChord::Char('R')],
        keys_label: "R",
        help: "Reload / re-open",
        deferred: None,
    },
    // -- Any -------------------------------------------------------------------
    Binding {
        context: Context::Any,
        action: Action::Ascend,
        chords: &[KeyChord::Esc],
        keys_label: "Esc",
        help: "Ascend / close",
        deferred: None,
    },
    // -- Chain (MoveStrike/FocusLeg #18 + AddLeg #26 wired; the rest defer I/O) --
    Binding {
        context: Context::Live(LiveScreen::Chain),
        action: Action::Chain(ChainAction::MoveStrike),
        chords: &[
            KeyChord::Up,
            KeyChord::Down,
            KeyChord::Char('k'),
            KeyChord::Char('j'),
        ],
        keys_label: "โ†‘โ†“ / kj",
        help: "Move strike",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Chain),
        action: Action::Chain(ChainAction::SwitchExpiry),
        chords: &[
            KeyChord::Left,
            KeyChord::Right,
            KeyChord::Char('h'),
            KeyChord::Char('l'),
        ],
        keys_label: "โ†โ†’ / hl",
        help: "Switch expiration",
        deferred: Some("soon"),
    },
    Binding {
        context: Context::Live(LiveScreen::Chain),
        action: Action::Chain(ChainAction::SwitchUnderlying),
        chords: &[KeyChord::Char('['), KeyChord::Char(']')],
        keys_label: "[ ]",
        help: "Prev / next underlying",
        deferred: Some("soon"),
    },
    Binding {
        context: Context::Live(LiveScreen::Chain),
        action: Action::Chain(ChainAction::FocusLeg),
        chords: &[KeyChord::Char('c'), KeyChord::Char('p')],
        keys_label: "c / p",
        help: "Focus call / put leg",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Chain),
        action: Action::Chain(ChainAction::Drill),
        chords: &[KeyChord::Enter],
        keys_label: "Enter",
        help: "Drill into strike",
        deferred: Some("soon"),
    },
    Binding {
        context: Context::Live(LiveScreen::Chain),
        action: Action::Chain(ChainAction::AddLeg),
        chords: &[KeyChord::Char('a')],
        keys_label: "a",
        help: "Add leg to builder",
        deferred: None,
    },
    // -- Depth (body wired #48) ------------------------------------------------
    Binding {
        context: Context::Live(LiveScreen::Depth),
        action: Action::Depth(DepthAction::Scroll),
        chords: &[
            KeyChord::Up,
            KeyChord::Down,
            KeyChord::Char('k'),
            KeyChord::Char('j'),
        ],
        keys_label: "โ†‘โ†“ / kj",
        help: "Scroll ladder",
        deferred: None,
    },
    // -- Surface (body wired #47) ----------------------------------------------
    Binding {
        context: Context::Live(LiveScreen::Surface),
        action: Action::Surface(SurfaceAction::CycleGreek),
        chords: &[KeyChord::Char('g'), KeyChord::Char('G')],
        keys_label: "g / G",
        // SF-04: not just "Greek" โ€” the cycle includes IV and price, which are not
        // Greeks โ€” and the axis applies to the curve/surface views (view-scoped per
        // SF-01). Kept terse so it fits the overlay column without truncation; the full
        // glyph list (ฮ”/ฮ“/ฮ˜/ฮฝ/IV/price) lives in docs/05 ยง3.
        help: "Cycle axis (curve/surf)",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Surface),
        action: Action::Surface(SurfaceAction::ToggleView),
        chords: &[KeyChord::Char('x')],
        keys_label: "x",
        help: "Smile / curve / surface",
        deferred: None,
    },
    // -- Payoff (live, builder wired #26; the t+0 curve renders in #27) ---------
    Binding {
        context: Context::Live(LiveScreen::Payoff),
        action: Action::Payoff(PayoffAction::AddLeg),
        chords: &[KeyChord::Char('a')],
        keys_label: "a",
        help: "Add leg at cursor",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Payoff),
        action: Action::Payoff(PayoffAction::RemoveLeg),
        chords: &[KeyChord::Char('x')],
        keys_label: "x",
        help: "Remove cursor leg",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Payoff),
        action: Action::Payoff(PayoffAction::Quantity),
        chords: &[KeyChord::Char('+'), KeyChord::Char('-')],
        keys_label: "+ / -",
        help: "Quantity + / -",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Payoff),
        action: Action::Payoff(PayoffAction::ToggleSide),
        chords: &[KeyChord::Char('s')],
        keys_label: "s",
        help: "Toggle buy / sell",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Payoff),
        action: Action::Payoff(PayoffAction::Commit),
        chords: &[KeyChord::Enter],
        keys_label: "Enter",
        help: "Commit strategy",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Payoff),
        action: Action::Payoff(PayoffAction::Cancel),
        chords: &[KeyChord::Esc],
        keys_label: "Esc",
        help: "Cancel builder",
        deferred: None,
    },
    Binding {
        context: Context::Live(LiveScreen::Payoff),
        action: Action::Payoff(PayoffAction::ToggleCurve),
        chords: &[KeyChord::Char('t')],
        keys_label: "t",
        help: "Expiration / t+0",
        deferred: None,
    },
    // -- Replay (scrub/end-jump/playback/speed wired #34; fill drill-down v0.3+) --
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::PlayPause),
        chords: &[KeyChord::Char(' ')],
        keys_label: "Space",
        help: "Play / pause",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::SpeedSlower),
        chords: &[KeyChord::Char('-')],
        keys_label: "-",
        help: "Slower (while playing)",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::SpeedFaster),
        chords: &[KeyChord::Char('+')],
        keys_label: "+",
        help: "Faster (while playing)",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::StepBack),
        chords: &[KeyChord::Left, KeyChord::Char('h')],
        keys_label: "โ† / h",
        help: "Step back",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::StepForward),
        chords: &[KeyChord::Right, KeyChord::Char('l')],
        keys_label: "โ†’ / l",
        help: "Step forward",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::PrevFill),
        chords: &[KeyChord::Char(',')],
        keys_label: ",",
        help: "Previous fill",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::NextFill),
        chords: &[KeyChord::Char('.')],
        keys_label: ".",
        help: "Next fill",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::JumpStart),
        chords: &[KeyChord::Home],
        keys_label: "Home",
        help: "Jump to start",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Replay),
        action: Action::Replay(ReplayAction::JumpEnd),
        chords: &[KeyChord::End],
        keys_label: "End",
        help: "Jump to end",
        deferred: None,
    },
    // -- Replay Payoff-at-head (#49): the same scrub/jump/playback keys as the equity
    //    screen (the recovery for "flat at this step" is scrubbing to an open step), so
    //    they are bound in the Payoff context too. The fill drill-down (`,` / `.`) is
    //    NOT bound here โ€” the payoff panel has no fill list. --
    Binding {
        context: Context::Replay(ReplayScreen::Payoff),
        action: Action::Replay(ReplayAction::PlayPause),
        chords: &[KeyChord::Char(' ')],
        keys_label: "Space",
        help: "Play / pause",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Payoff),
        action: Action::Replay(ReplayAction::SpeedSlower),
        chords: &[KeyChord::Char('-')],
        keys_label: "-",
        help: "Slower (while playing)",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Payoff),
        action: Action::Replay(ReplayAction::SpeedFaster),
        chords: &[KeyChord::Char('+')],
        keys_label: "+",
        help: "Faster (while playing)",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Payoff),
        action: Action::Replay(ReplayAction::StepBack),
        chords: &[KeyChord::Left, KeyChord::Char('h')],
        keys_label: "โ† / h",
        help: "Step back",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Payoff),
        action: Action::Replay(ReplayAction::StepForward),
        chords: &[KeyChord::Right, KeyChord::Char('l')],
        keys_label: "โ†’ / l",
        help: "Step forward",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Payoff),
        action: Action::Replay(ReplayAction::JumpStart),
        chords: &[KeyChord::Home],
        keys_label: "Home",
        help: "Jump to start",
        deferred: None,
    },
    Binding {
        context: Context::Replay(ReplayScreen::Payoff),
        action: Action::Replay(ReplayAction::JumpEnd),
        chords: &[KeyChord::End],
        keys_label: "End",
        help: "Jump to end",
        deferred: None,
    },
];

// ---------------------------------------------------------------------------
// Dispatch resolution โ€” both read the one map.
// ---------------------------------------------------------------------------

/// Resolve a chord against the **global** bindings into the [`GlobalCommand`] the
/// dispatch executes (`docs/05-views-and-ux.md` ยง3), or `None` when no global
/// binding matches (the dispatch then forwards the key to the active screen).
///
/// This is the read side `App::dispatch_key_global` uses, so the running dispatch
/// and the help overlay share the one map.
#[must_use]
pub fn resolve_global(chord: KeyChord) -> Option<GlobalCommand> {
    let binding = KEYMAP
        .iter()
        .find(|b| b.context == Context::Global && b.chords.contains(&chord))?;
    match binding.action {
        Action::Global(action) => resolve_global_command(action, chord),
        Action::Chain(_)
        | Action::Depth(_)
        | Action::Surface(_)
        | Action::Payoff(_)
        | Action::Replay(_)
        | Action::Ascend => None,
    }
}

/// Bind the concrete screen-switch slot (from the pressed digit) to a resolved
/// [`GlobalCommand`].
#[must_use]
fn resolve_global_command(action: GlobalAction, chord: KeyChord) -> Option<GlobalCommand> {
    match action {
        GlobalAction::Quit => Some(GlobalCommand::Quit),
        GlobalAction::ToggleHelp => Some(GlobalCommand::ToggleHelp),
        GlobalAction::NextScreen => Some(GlobalCommand::NextScreen),
        GlobalAction::PrevScreen => Some(GlobalCommand::PrevScreen),
        GlobalAction::Reconnect => Some(GlobalCommand::Reconnect),
        GlobalAction::Rediscover => Some(GlobalCommand::Rediscover),
        GlobalAction::SwitchScreen => slot_from_chord(chord).map(GlobalCommand::SwitchScreen),
    }
}

/// The screen-switch slot `1..=9` a digit chord selects, or `None` for a non-digit.
#[must_use]
fn slot_from_chord(chord: KeyChord) -> Option<u8> {
    let KeyChord::Char(c) = chord else {
        return None;
    };
    c.to_digit(10).and_then(|d| u8::try_from(d).ok())
}

/// Resolve a chord against the **chain** screen's bindings
/// (`docs/05-views-and-ux.md` ยง3), or `None` when no binding matches (the
/// dispatch then ignores the key, e.g. `Esc`, which is a [`Context::Any`] binding,
/// not a chain one).
///
/// This is the read side the chain screen's `handle_key` (`src/ui/chain.rs`) uses,
/// so the chain dispatch and the help overlay share the one map โ€” a bound key and
/// its documentation cannot drift (the cross-check test below proves it). The concrete
/// direction (`โ†‘` vs `โ†“`, `โ†` vs `โ†’`, `[` vs `]`, `c` vs `p`) is read from the
/// resolved chord at dispatch time, the same way [`resolve_global`] derives the
/// screen-switch slot from the pressed digit.
#[must_use]
pub fn resolve_chain(chord: KeyChord) -> Option<ChainAction> {
    let binding = KEYMAP
        .iter()
        .find(|b| b.context == Context::Live(LiveScreen::Chain) && b.chords.contains(&chord))?;
    match binding.action {
        Action::Chain(action) => Some(action),
        Action::Global(_)
        | Action::Depth(_)
        | Action::Surface(_)
        | Action::Payoff(_)
        | Action::Replay(_)
        | Action::Ascend => None,
    }
}

/// Resolve a chord against the **payoff** screen's bindings
/// (`docs/05-views-and-ux.md` ยง3), or `None` when no binding matches (the dispatch
/// then ignores the key).
///
/// This is the read side the payoff screen's `handle_key` (`src/ui/payoff.rs`) uses,
/// so the builder dispatch and the help overlay share the one map โ€” a bound key and
/// its documentation cannot drift. The concrete direction of the shared
/// [`PayoffAction::Quantity`] chord (`+` increment vs `-` decrement) is read from the
/// resolved chord at dispatch time, the same way [`resolve_global`] derives the
/// screen-switch slot from the pressed digit.
#[must_use]
pub fn resolve_payoff(chord: KeyChord) -> Option<PayoffAction> {
    let binding = KEYMAP
        .iter()
        .find(|b| b.context == Context::Live(LiveScreen::Payoff) && b.chords.contains(&chord))?;
    match binding.action {
        Action::Payoff(action) => Some(action),
        Action::Global(_)
        | Action::Chain(_)
        | Action::Depth(_)
        | Action::Surface(_)
        | Action::Replay(_)
        | Action::Ascend => None,
    }
}

/// Resolve a chord against the **depth** screen's bindings
/// (`docs/05-views-and-ux.md` ยง3), or `None` when no binding matches (the dispatch
/// then ignores the key).
///
/// This is the read side the depth screen's `handle_key` (`src/ui/depth.rs`) uses,
/// so the depth dispatch and the help overlay share the one map โ€” a bound key and
/// its documentation cannot drift (#48). The concrete scroll direction (`โ†‘`/`k` up vs
/// `โ†“`/`j` down โ€” the chain's `kj` idiom, #48 P3-01) is read from the resolved chord
/// at dispatch time, the same way [`resolve_global`] derives the screen-switch slot
/// from the pressed digit.
#[must_use]
pub fn resolve_depth(chord: KeyChord) -> Option<DepthAction> {
    let binding = KEYMAP
        .iter()
        .find(|b| b.context == Context::Live(LiveScreen::Depth) && b.chords.contains(&chord))?;
    match binding.action {
        Action::Depth(action) => Some(action),
        Action::Global(_)
        | Action::Chain(_)
        | Action::Surface(_)
        | Action::Payoff(_)
        | Action::Replay(_)
        | Action::Ascend => None,
    }
}

/// Resolve a chord against the **surface** screen's bindings
/// (`docs/05-views-and-ux.md` ยง3), or `None` when no binding matches (the dispatch
/// then ignores the key).
///
/// This is the read side the surface screen's `handle_key` (`src/ui/surface.rs`) uses,
/// so the surface dispatch and the help overlay share the one map โ€” a bound key and
/// its documentation cannot drift (#47). The concrete direction of the shared
/// [`SurfaceAction::CycleGreek`] chord (`g` forward vs `G` back) is read from the
/// resolved chord at dispatch time, the same way [`resolve_global`] derives the
/// screen-switch slot from the pressed digit.
#[must_use]
pub fn resolve_surface(chord: KeyChord) -> Option<SurfaceAction> {
    let binding = KEYMAP
        .iter()
        .find(|b| b.context == Context::Live(LiveScreen::Surface) && b.chords.contains(&chord))?;
    match binding.action {
        Action::Surface(action) => Some(action),
        Action::Global(_)
        | Action::Chain(_)
        | Action::Depth(_)
        | Action::Payoff(_)
        | Action::Replay(_)
        | Action::Ascend => None,
    }
}

/// Resolve a chord against a **replay** screen's bindings
/// (`docs/05-views-and-ux.md` ยง3), or `None` when no binding matches.
#[must_use]
pub fn resolve_replay(chord: KeyChord, screen: ReplayScreen) -> Option<ReplayAction> {
    let binding = KEYMAP
        .iter()
        .find(|b| b.context == Context::Replay(screen) && b.chords.contains(&chord))?;
    match binding.action {
        Action::Replay(action) => Some(action),
        Action::Global(_)
        | Action::Chain(_)
        | Action::Depth(_)
        | Action::Surface(_)
        | Action::Payoff(_)
        | Action::Ascend => None,
    }
}

// ---------------------------------------------------------------------------
// Overlay grouping โ€” pure, read by the ui help-overlay renderer.
// ---------------------------------------------------------------------------

/// The bindings in a context, in map order.
#[must_use]
fn bindings_in(context: Context) -> Vec<&'static Binding> {
    KEYMAP.iter().filter(|b| b.context == context).collect()
}

/// The overlay sections for the active mode: the global keys first, then the
/// mode's screens โ€” every screen and its keys, generated from the map so the
/// overlay cannot drift from the dispatch (`docs/05-views-and-ux.md` ยง3). Read by
/// the ui help-overlay renderer (`src/ui/theme.rs`).
#[must_use]
pub(crate) fn help_sections(mode: &Mode) -> Vec<(&'static str, Vec<&'static Binding>)> {
    let mut global = bindings_in(Context::Global);
    global.extend(bindings_in(Context::Any));
    match mode {
        Mode::Live(_) => {
            let mut sections = vec![("Global", global)];
            sections.push(("Chain", bindings_in(Context::Live(LiveScreen::Chain))));
            sections.push(("Depth", bindings_in(Context::Live(LiveScreen::Depth))));
            sections.push(("Surface", bindings_in(Context::Live(LiveScreen::Surface))));
            sections.push(("Payoff", bindings_in(Context::Live(LiveScreen::Payoff))));
            sections
        }
        Mode::Replay(_) => {
            // `r` (Reconnect) is a Live-only affordance โ€” in replay it is a deliberate
            // no-op (there is no live provider; `R` reloads the bundle instead), so it
            // must NOT appear in the replay overlay or `?` would advertise a dead key
            // (fix SF-04). The binding stays in `KEYMAP` (dispatch reads one table);
            // this scopes only the DOCUMENTATION, keeping the overlay truthful in both
            // modes without a second source of truth.
            global.retain(|b| b.action != Action::Global(GlobalAction::Reconnect));
            let mut sections = vec![("Global", global)];
            sections.push(("Replay", bindings_in(Context::Replay(ReplayScreen::Replay))));
            sections.push(("Payoff", bindings_in(Context::Replay(ReplayScreen::Payoff))));
            sections
        }
    }
}

/// Every binding the help overlay shows for `mode`, flattened โ€” the cross-check
/// surface a test uses to prove every dispatched key is documented.
#[must_use]
pub fn help_bindings(mode: &Mode) -> Vec<&'static Binding> {
    help_sections(mode)
        .into_iter()
        .flat_map(|(_, bindings)| bindings)
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::tests_support::{live_app_on, replay_app_on};
    use crate::app::{LiveScreen, ReplayScreen, ScreenLoad};
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn press(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    // --- The map drives dispatch AND the overlay (anti-drift) ----------------

    #[test]
    fn test_resolve_global_every_global_chord_resolves_and_is_documented() {
        // Every chord in a Global-context binding resolves to a command (dispatch
        // acts on it) AND appears in the help overlay (documented). A key the
        // dispatch acts on but the overlay omits would be a defect.
        let live = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, false);
        let documented = help_bindings(&live.mode);
        for binding in KEYMAP.iter().filter(|b| b.context == Context::Global) {
            for &chord in binding.chords {
                assert!(
                    resolve_global(chord).is_some(),
                    "global chord {chord:?} does not resolve",
                );
                assert!(
                    documented.iter().any(|b| b.chords.contains(&chord)),
                    "global chord {chord:?} is dispatched but not in the overlay",
                );
            }
        }
    }

    #[test]
    fn test_resolve_chain_every_chain_chord_resolves_and_is_documented() {
        // Every chord in a chain-context binding resolves to a `ChainAction`
        // (`ui::chain::handle_key` acts on it) AND appears in the help overlay
        // (documented), so the chain dispatch and its documentation cannot drift.
        let live = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, false);
        let documented = help_bindings(&live.mode);
        for binding in KEYMAP
            .iter()
            .filter(|b| b.context == Context::Live(LiveScreen::Chain))
        {
            for &chord in binding.chords {
                assert!(
                    resolve_chain(chord).is_some(),
                    "chain chord {chord:?} does not resolve",
                );
                assert!(
                    documented.iter().any(|b| b.chords.contains(&chord)),
                    "chain chord {chord:?} is dispatched but not in the overlay",
                );
            }
        }
    }

    #[test]
    fn test_resolve_chain_ignores_non_chain_chords() {
        // A global chord (`q`) and the `Context::Any` `Esc` are not chain bindings,
        // so the chain screen forwards nothing for them.
        assert_eq!(resolve_chain(KeyChord::Char('q')), None);
        assert_eq!(resolve_chain(KeyChord::Esc), None);
        assert_eq!(resolve_chain(KeyChord::Char('z')), None);
        // A chain chord resolves to its action.
        assert_eq!(
            resolve_chain(KeyChord::Char('j')),
            Some(ChainAction::MoveStrike),
        );
        assert_eq!(
            resolve_chain(KeyChord::Char('c')),
            Some(ChainAction::FocusLeg)
        );
    }

    #[test]
    fn test_keymap_marks_deferred_chain_keys_not_the_wired_ones() {
        // The wired chain keys (MoveStrike/FocusLeg #18, AddLeg #26) carry no deferred
        // marker; the three not-yet-wired ones do, so the overlay advertises honestly
        // which keys are not live.
        let deferral = |action: ChainAction| -> Option<&'static str> {
            KEYMAP
                .iter()
                .find(|b| b.action == Action::Chain(action))
                .and_then(|b| b.deferred)
        };
        assert_eq!(
            deferral(ChainAction::MoveStrike),
            None,
            "MoveStrike is wired"
        );
        assert_eq!(deferral(ChainAction::FocusLeg), None, "FocusLeg is wired");
        assert_eq!(
            deferral(ChainAction::AddLeg),
            None,
            "AddLeg is wired in #26 (chainโ†’aโ†’builder)"
        );
        assert!(deferral(ChainAction::SwitchExpiry).is_some());
        assert!(deferral(ChainAction::SwitchUnderlying).is_some());
        assert!(deferral(ChainAction::Drill).is_some());
    }

    #[test]
    fn test_keymap_marks_replay_keys_all_wired() {
        // #34 wired the scrub, end-jump, play/pause, and speed keys; #35 wired the
        // fill drill-down (`,` / `.`), so no replay key carries a deferred marker any
        // more โ€” the overlay advertises every replay key as live.
        let deferral = |action: ReplayAction| -> Option<&'static str> {
            KEYMAP
                .iter()
                .find(|b| b.action == Action::Replay(action))
                .and_then(|b| b.deferred)
        };
        assert_eq!(deferral(ReplayAction::StepBack), None);
        assert_eq!(deferral(ReplayAction::StepForward), None);
        assert_eq!(deferral(ReplayAction::JumpStart), None);
        assert_eq!(deferral(ReplayAction::JumpEnd), None);
        assert_eq!(deferral(ReplayAction::PlayPause), None);
        assert_eq!(deferral(ReplayAction::SpeedFaster), None);
        assert_eq!(deferral(ReplayAction::SpeedSlower), None);
        // #35 wired the fill drill-down render, so `,` / `.` are live now.
        assert_eq!(deferral(ReplayAction::PrevFill), None);
        assert_eq!(deferral(ReplayAction::NextFill), None);
    }

    #[test]
    fn test_help_reconnect_scoped_to_live_overlay_only() {
        // SF-04: `r` (Reconnect) is Live-only; the replay overlay must NOT advertise
        // it (it is a no-op there), while the live overlay still does. The binding
        // stays in KEYMAP for dispatch โ€” this only scopes the documentation, so the
        // overlay is truthful in BOTH modes from the one source of truth.
        let live = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, false);
        let replay = replay_app_on(ReplayScreen::Replay, false);
        let is_reconnect = |b: &&Binding| b.action == Action::Global(GlobalAction::Reconnect);
        assert!(
            help_bindings(&live.mode).iter().any(is_reconnect),
            "the live overlay lists Reconnect",
        );
        assert!(
            !help_bindings(&replay.mode).iter().any(is_reconnect),
            "the replay overlay omits Reconnect (no-op in replay)",
        );
        // Single source of truth intact: `r` still resolves globally in the map.
        assert_eq!(
            resolve_global(KeyChord::Char('r')),
            Some(GlobalCommand::Reconnect),
        );
    }

    #[test]
    fn test_help_speed_keys_note_while_playing() {
        // SF-03: the `+`/`-` speed help labels state the while-playing condition, so
        // the overlay does not advertise a silent no-op while paused.
        let help_of = |action: ReplayAction| -> &'static str {
            KEYMAP
                .iter()
                .find(|b| b.action == Action::Replay(action))
                .map_or("", |b| b.help)
        };
        assert!(
            help_of(ReplayAction::SpeedFaster).contains("playing"),
            "faster notes while-playing",
        );
        assert!(
            help_of(ReplayAction::SpeedSlower).contains("playing"),
            "slower notes while-playing",
        );
    }

    #[test]
    fn test_keymap_deferred_keys_still_resolve_and_are_documented() {
        // Deferral marks + documents only โ€” it never changes resolution: a deferred
        // chain key still resolves to its action AND stays in the overlay.
        let live = live_app_on(LiveScreen::Chain, ScreenLoad::Ready, false);
        let documented = help_bindings(&live.mode);
        assert_eq!(
            resolve_chain(KeyChord::Enter),
            Some(ChainAction::Drill),
            "a deferred key still resolves",
        );
        assert!(
            documented
                .iter()
                .any(|b| b.chords.contains(&KeyChord::Enter)
                    && b.context == Context::Live(LiveScreen::Chain)),
            "a deferred key stays documented",
        );
    }

    #[test]
    fn test_resolve_replay_every_replay_chord_resolves_and_is_documented() {
        let replay = replay_app_on(ReplayScreen::Replay, false);
        let documented = help_bindings(&replay.mode);
        for binding in KEYMAP
            .iter()
            .filter(|b| b.context == Context::Replay(ReplayScreen::Replay))
        {
            for &chord in binding.chords {
                assert!(
                    resolve_replay(chord, ReplayScreen::Replay).is_some(),
                    "replay chord {chord:?} does not resolve",
                );
                assert!(
                    documented.iter().any(|b| b.chords.contains(&chord)),
                    "replay chord {chord:?} is dispatched but not in the overlay",
                );
            }
        }
    }

    #[test]
    fn test_resolve_replay_payoff_every_chord_resolves_and_is_documented() {
        // #49: the replay payoff-at-head panel binds the scrub/jump/playback keys in
        // its own context (the recovery for "flat at this step" is scrubbing), so every
        // Payoff-context chord resolves for that screen AND appears in the overlay โ€” no
        // dead key, no drift. The panel binds no fill drill-down (`,` / `.`).
        let replay = replay_app_on(ReplayScreen::Payoff, false);
        let documented = help_bindings(&replay.mode);
        let mut chords_seen = 0usize;
        for binding in KEYMAP
            .iter()
            .filter(|b| b.context == Context::Replay(ReplayScreen::Payoff))
        {
            for &chord in binding.chords {
                chords_seen += 1;
                assert!(
                    resolve_replay(chord, ReplayScreen::Payoff).is_some(),
                    "replay payoff chord {chord:?} does not resolve",
                );
                assert!(
                    documented.iter().any(|b| b.chords.contains(&chord)),
                    "replay payoff chord {chord:?} is dispatched but not in the overlay",
                );
            }
        }
        assert!(
            chords_seen > 0,
            "the payoff panel binds its scrub/playback keys"
        );
        // The fill drill-down is NOT bound on the payoff panel (there is no fill list).
        assert!(
            resolve_replay(KeyChord::Char(','), ReplayScreen::Payoff).is_none(),
            "`,` (prev fill) is inert on the payoff panel",
        );
    }

    #[test]
    fn test_resolve_payoff_every_payoff_chord_resolves_and_is_documented() {
        // Every chord in a payoff-context binding resolves to a `PayoffAction`
        // (`ui::payoff::handle_key` acts on it) AND appears in the help overlay, so
        // the builder dispatch and its documentation cannot drift.
        let live = live_app_on(LiveScreen::Payoff, ScreenLoad::Ready, false);
        let documented = help_bindings(&live.mode);
        for binding in KEYMAP
            .iter()
            .filter(|b| b.context == Context::Live(LiveScreen::Payoff))
        {
            for &chord in binding.chords {
                assert!(
                    resolve_payoff(chord).is_some(),
                    "payoff chord {chord:?} does not resolve",
                );
                assert!(
                    documented.iter().any(|b| b.chords.contains(&chord)),
                    "payoff chord {chord:?} is dispatched but not in the overlay",
                );
            }
        }
    }

    #[test]
    fn test_resolve_payoff_quantity_shares_plus_and_minus_chords() {
        // Both `+` and `-` resolve to the one `Quantity` action; the screen reads the
        // concrete chord to decide increment vs decrement.
        assert_eq!(
            resolve_payoff(KeyChord::Char('+')),
            Some(PayoffAction::Quantity),
        );
        assert_eq!(
            resolve_payoff(KeyChord::Char('-')),
            Some(PayoffAction::Quantity),
        );
        assert_eq!(resolve_payoff(KeyChord::Enter), Some(PayoffAction::Commit));
        assert_eq!(resolve_payoff(KeyChord::Esc), Some(PayoffAction::Cancel));
        // A non-payoff chord does not resolve here.
        assert_eq!(resolve_payoff(KeyChord::Char('q')), None);
    }

    #[test]
    fn test_resolve_surface_every_surface_chord_resolves_and_is_documented() {
        // Every chord in a surface-context binding resolves to a `SurfaceAction`
        // (`ui::surface::handle_key` acts on it) AND appears in the help overlay, so
        // the surface dispatch and its documentation cannot drift (#47).
        let live = live_app_on(LiveScreen::Surface, ScreenLoad::Ready, false);
        let documented = help_bindings(&live.mode);
        for binding in KEYMAP
            .iter()
            .filter(|b| b.context == Context::Live(LiveScreen::Surface))
        {
            for &chord in binding.chords {
                assert!(
                    resolve_surface(chord).is_some(),
                    "surface chord {chord:?} does not resolve",
                );
                assert!(
                    documented.iter().any(|b| b.chords.contains(&chord)),
                    "surface chord {chord:?} is dispatched but not in the overlay",
                );
            }
        }
    }

    #[test]
    fn test_resolve_depth_every_depth_chord_resolves_and_is_documented() {
        // Every chord in a depth-context binding resolves to a `DepthAction`
        // (`ui::depth::handle_key` acts on it) AND appears in the help overlay, so the
        // depth dispatch and its documentation cannot drift (#48).
        let live = live_app_on(LiveScreen::Depth, ScreenLoad::Ready, false);
        let documented = help_bindings(&live.mode);
        for binding in KEYMAP
            .iter()
            .filter(|b| b.context == Context::Live(LiveScreen::Depth))
        {
            for &chord in binding.chords {
                assert!(
                    resolve_depth(chord).is_some(),
                    "depth chord {chord:?} does not resolve",
                );
                assert!(
                    documented.iter().any(|b| b.chords.contains(&chord)),
                    "depth chord {chord:?} is dispatched but not in the overlay",
                );
            }
        }
    }

    #[test]
    fn test_resolve_depth_ignores_non_depth_chords_and_binds_scroll() {
        // `โ†‘โ†“ / kj` all resolve to the one Scroll action; the screen reads the concrete
        // chord to decide up vs down (the chain's `kj` idiom, #48 P3-01). A non-depth
        // chord does not resolve here.
        assert_eq!(resolve_depth(KeyChord::Up), Some(DepthAction::Scroll));
        assert_eq!(resolve_depth(KeyChord::Down), Some(DepthAction::Scroll));
        assert_eq!(
            resolve_depth(KeyChord::Char('k')),
            Some(DepthAction::Scroll),
            "k scrolls up (the chain idiom)",
        );
        assert_eq!(
            resolve_depth(KeyChord::Char('j')),
            Some(DepthAction::Scroll),
            "j scrolls down (the chain idiom)",
        );
        assert_eq!(resolve_depth(KeyChord::Char('q')), None);
    }

    #[test]
    fn test_keymap_depth_scroll_is_wired_not_deferred() {
        // The depth body lands in #48, so the depth Scroll key carries no deferred
        // marker; the overlay advertises it as live.
        let deferred = KEYMAP
            .iter()
            .find(|b| b.action == Action::Depth(DepthAction::Scroll))
            .and_then(|b| b.deferred);
        assert_eq!(deferred, None, "depth Scroll is wired in #48");
    }

    #[test]
    fn test_keymap_surface_keys_are_wired_not_deferred() {
        // The surface bodies land in #47, so the surface keys carry no deferred
        // marker; the overlay advertises them as live.
        for action in [SurfaceAction::CycleGreek, SurfaceAction::ToggleView] {
            let deferred = KEYMAP
                .iter()
                .find(|b| b.action == Action::Surface(action))
                .and_then(|b| b.deferred);
            assert_eq!(deferred, None, "surface {action:?} is wired in #47");
        }
        // g/G share the CycleGreek action; x is ToggleView. The screen reads the
        // concrete chord to decide the cycle direction.
        assert_eq!(
            resolve_surface(KeyChord::Char('g')),
            Some(SurfaceAction::CycleGreek),
        );
        assert_eq!(
            resolve_surface(KeyChord::Char('G')),
            Some(SurfaceAction::CycleGreek),
        );
        assert_eq!(
            resolve_surface(KeyChord::Char('x')),
            Some(SurfaceAction::ToggleView),
        );
        assert_eq!(resolve_surface(KeyChord::Char('q')), None);
    }

    #[test]
    fn test_keymap_payoff_builder_keys_are_wired_not_deferred() {
        // The builder bodies land in #26, so the payoff keys carry no deferred
        // marker; the help overlay advertises them as live.
        for action in [
            PayoffAction::AddLeg,
            PayoffAction::RemoveLeg,
            PayoffAction::Quantity,
            PayoffAction::ToggleSide,
            PayoffAction::Commit,
            PayoffAction::Cancel,
            PayoffAction::ToggleCurve,
        ] {
            let deferred = KEYMAP
                .iter()
                .find(|b| b.action == Action::Payoff(action))
                .and_then(|b| b.deferred);
            assert_eq!(deferred, None, "payoff {action:?} is wired in #26");
        }
    }

    #[test]
    fn test_resolve_global_switch_screen_binds_the_pressed_slot() {
        assert_eq!(
            resolve_global(KeyChord::Char('2')),
            Some(GlobalCommand::SwitchScreen(2)),
        );
        assert_eq!(
            resolve_global(KeyChord::Tab),
            Some(GlobalCommand::NextScreen)
        );
        assert_eq!(
            resolve_global(KeyChord::BackTab),
            Some(GlobalCommand::PrevScreen),
        );
        assert_eq!(
            resolve_global(KeyChord::Char('q')),
            Some(GlobalCommand::Quit)
        );
        assert_eq!(
            resolve_global(KeyChord::Ctrl('c')),
            Some(GlobalCommand::Quit)
        );
    }

    #[test]
    fn test_resolve_global_unmapped_key_returns_none() {
        // A chain-nav key (`j`) is not a global binding, so it forwards to the
        // screen; `Esc` (context Any) is not a global command either.
        assert_eq!(resolve_global(KeyChord::Char('j')), None);
        assert_eq!(resolve_global(KeyChord::Esc), None);
        assert_eq!(resolve_global(KeyChord::Char('z')), None);
    }

    #[test]
    fn test_key_chord_from_event_normalizes_ctrl_and_named_keys() {
        assert_eq!(
            KeyChord::from_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)),
            Some(KeyChord::Ctrl('c')),
        );
        assert_eq!(
            KeyChord::from_event(press(KeyCode::Char('?'))),
            Some(KeyChord::Char('?')),
        );
        assert_eq!(
            KeyChord::from_event(press(KeyCode::BackTab)),
            Some(KeyChord::BackTab),
        );
        assert_eq!(KeyChord::from_event(press(KeyCode::Up)), Some(KeyChord::Up));
        assert!(KeyChord::from_event(press(KeyCode::F(5))).is_none());
    }
}