gwm-cli 1.6.1

git worktree manager — TUI + CLI, native libgit2, per-repo bootstrap
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
//! Configurable TUI keymap (issue #87).
//!
//! Three layers, in order of authority:
//!
//! 1. **Built-in defaults** ([`Keymap::defaults`]) — the bindings the
//!    binary ships with. Captures the historical hard-coded set
//!    (`j/k`, `g g`, `Tab`, `o`, `l`, `R`, `y`, `p`, `f/F`, `/`, `?`,
//!    `q`, …).
//! 2. **User overrides** ([`Keymap::apply_override`]) — fed from
//!    `[tui.keys]` in `.gwm.toml`. An override **replaces** the
//!    default for the targeted action; it does not merge. Passing an
//!    empty `Vec` unbinds the action entirely.
//! 3. **Hard-coded escape hatches** — `Ctrl+C` (emergency quit) and
//!    `Esc` / `Enter` keep their contextual handling in
//!    `src/tui/mod.rs`. They are deliberately outside the keymap
//!    because their semantics depend on the active view (filter bar,
//!    picker mode, sticky filter, etc.) — folding them into the
//!    keymap would require modal state the configuration language
//!    has no way to express.
//!
//! ## Chord / prefix policy
//!
//! Per the design decision recorded on PR #87, binding a chord that
//! is a strict prefix of another chord (e.g. `g` alone while `g g` is
//! also bound) is a **hard error at load time**. Resolving the
//! ambiguity at runtime would require a Vim-style 500 ms timeout in
//! the event loop, which conflicts with the project's preference for
//! a pure state-machine TUI. Easier to refuse the config and force
//! the user to pick.
//!
//! ## Quit policy
//!
//! `quit` is the only action with a guaranteed escape hatch: the
//! hard-coded `Ctrl+C` branch in `run_app` runs *before* any keymap
//! lookup, so even an empty / hostile user keymap can be exited. The
//! doctor check defined in `crate::doctor` emits a warning when no
//! non-`Ctrl+C` binding for `quit` survives the override layer.

use crate::error::{GwmError, Result};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::fmt;

// ---------------------------------------------------------------------------
// Action enum + ACTIONS table
// ---------------------------------------------------------------------------

/// Declarative macro that defines `Action`, its slug roundtrip, the
/// `ACTIONS` table, and `Action::all()` from a **single** ordered list
/// of `(Variant => "slug")` pairs. Adding a new action means editing
/// one place; the rest stays in sync mechanically.
macro_rules! define_actions {
  ($( $variant:ident => $slug:literal ),* $(,)?) => {
    /// Every user-rebindable verb the TUI exposes.
    ///
    /// Variants whose semantics depend on the active view (`Enter`,
    /// `Esc`, `Ctrl+C`) are deliberately **not** listed — see the
    /// module-level "Hard-coded escape hatches" note for why.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum Action {
      $( $variant, )*
    }

    impl Action {
      /// Stable string slug used in `[tui.keys]`, `gwm tui keys`, and
      /// any future docs generator. Lowercase + underscores; never
      /// renamed in a backwards-incompatible way without a deprecation
      /// alias.
      pub fn slug(self) -> &'static str {
        match self {
          $( Action::$variant => $slug, )*
        }
      }

      /// Inverse of [`Action::slug`]. Used by the config loader to
      /// translate `.gwm.toml` keys into typed actions.
      pub fn from_slug(s: &str) -> Option<Self> {
        match s {
          $( $slug => Some(Action::$variant), )*
          _ => None,
        }
      }

      /// Iterator over every variant. Order matches the declarative
      /// macro invocation below, which is also the order surfaced by
      /// `gwm tui keys`.
      pub fn all() -> impl Iterator<Item = Self> {
        [ $( Action::$variant, )* ].into_iter()
      }
    }

    /// Static (Action, slug) table — convenience for callers that
    /// want both at once (the help-overlay renderer, `gwm tui keys`
    /// printer, `gwm doctor` reporter).
    pub const ACTIONS: &[(Action, &str)] = &[
      $( (Action::$variant, $slug), )*
    ];
  };
}

define_actions! {
  // Navigation
  Down              => "down",
  Up                => "up",
  Top               => "top",
  Bottom            => "bottom",
  // #437: Working Tree pane scroll, status context only.
  WtScrollDown      => "wt_scroll_down",
  WtScrollUp        => "wt_scroll_up",
  ToggleSidebar     => "toggle_sidebar",
  ToggleSidebarMode => "toggle_sidebar_mode",
  CycleSidebarLayout => "cycle_sidebar_layout",
  ToggleSidebarPosition => "toggle_sidebar_position",
  FocusSwap         => "focus_swap",
  FocusWorktrees    => "focus_worktrees",
  FocusStatus       => "focus_status",
  // Filter
  Filter            => "filter",
  // Lifecycle / mutating
  Refresh           => "refresh",
  Sync              => "sync",
  Create            => "create",
  DeleteConfirm     => "delete",
  Bootstrap         => "bootstrap",
  ToggleDeleteBranch => "delete_branch",
  Pull              => "pull",
  Push              => "push",
  EditWorktree      => "edit_worktree",
  ExitToWorktree    => "exit_to_worktree",
  LazyGitPty        => "lazygit_pty",
  LazyGitFullscreen => "lazygit_fullscreen",
  ReviewFullscreen  => "review_fullscreen",
  ReviewPty         => "review_pty",
  YankPath          => "yank_path",
  YankBranchName    => "yank_branch_name",
  YankWorktreeName  => "yank_worktree_name",
  TerminalPty       => "terminal_pty",
  TerminalFullscreen => "terminal_fullscreen",
  BrowseLinks       => "browse_links",
  OpenDocs          => "open_docs",
  LinkPrompt        => "link",
  FetchGithub       => "fetch_github",
  MuxPane           => "mux_pane",
  Macro1            => "macro_one",
  Macro2            => "macro_two",
  // Overlays
  CommandLogs       => "command_logs",
  ConfigPanel       => "config_panel",
  // #436: CI checks overlay — also reachable via `c` in the status context.
  CiChecks          => "ci_checks",
  ExecOverlay       => "exec_overlay",
  CleanOverlay      => "clean_overlay",
  AgentSessions     => "agent_sessions",
  Help              => "help",
  Quit              => "quit",
  // Future surface — bound to ':' by default, picked up by #32.
  CommandPalette    => "command_palette",
}

impl Action {
  /// Like [`Action::from_slug`] but also accepts the pre-#290 slugs that were
  /// renamed. Use this in config deserialization so existing `.gwm.toml` files
  /// with the old key names keep working after the upgrade.
  ///
  /// The canonical slug is tried first; only on a miss do the compat aliases
  /// fire. The aliases are intentionally one-way: `Action::slug()` still
  /// returns the new canonical slug, so `gwm tui keys` and the help overlay
  /// stay up-to-date.
  pub fn from_slug_compat(s: &str) -> Option<Self> {
    if let Some(a) = Self::from_slug(s) {
      return Some(a);
    }
    COMPAT_ALIASES.iter().find(|(slug, _)| *slug == s).map(|(_, a)| *a)
  }

  /// Whether this action mutates a repo through the *active* repo context
  /// (`App.repo`/`workdir`/`config`) rather than only the selected worktree's
  /// path. In workspace mode (#304) these are blocked while the selected row's
  /// repo can't be activated, since they would otherwise target the previously
  /// active repo. Navigation, yanks and read-only launchers are absent on
  /// purpose — they don't write through the active repo handle.
  pub fn is_repo_mutating(self) -> bool {
    matches!(
      self,
      Action::Create
        | Action::DeleteConfirm
        | Action::Bootstrap
        | Action::Sync
        | Action::Pull
        | Action::Push
        | Action::EditWorktree
        | Action::LinkPrompt
        // FetchGithub persists detected PR/issue titles + states into the
        // active repo's git config, so it writes through `App.repo` too (#304).
        | Action::FetchGithub
        // #325: the exec / clean overlays resolve their command / dir-set from
        // the *active* repo's `[exec]` / `[clean]` config and act on the
        // selected worktree's path. With a stale workspace selection both the
        // config and the path belong to the previously active repo — and exec
        // runs an arbitrary command while clean deletes directories — so they
        // must be blocked before the overlay opens (Codex #333 review).
        | Action::ExecOverlay
        | Action::CleanOverlay
    )
  }

  /// The pre-#290 alias slug(s) that resolve to this action, if any. Used by
  /// the in-TUI keymap editor (issue #294) to strip a stale alias from a
  /// legacy config when the canonical slug is (re)written — otherwise the
  /// alias, applied later in the sorted override walk, would silently shadow
  /// the new binding (Codex #297 review).
  pub fn compat_alias_slugs(self) -> impl Iterator<Item = &'static str> {
    COMPAT_ALIASES
      .iter()
      .filter(move |(_, a)| *a == self)
      .map(|(slug, _)| *slug)
  }
}

/// Pre-#290 slug aliases, accepted by [`Action::from_slug_compat`] so existing
/// `.gwm.toml` files keep working after the #290 rename. The canonical slug is
/// always preferred; these only fire on a miss. Single source of truth for both
/// directions (resolve + [`Action::compat_alias_slugs`]).
const COMPAT_ALIASES: &[(&str, Action)] = &[
  ("git_tui", Action::LazyGitFullscreen),
  ("git_tui_overlay", Action::LazyGitPty),
  ("review", Action::ReviewFullscreen),
  ("review_overlay", Action::ReviewPty),
  ("yank", Action::YankPath),
  ("open", Action::TerminalFullscreen),
  ("open_terminal_overlay", Action::TerminalPty),
  ("open_menu", Action::BrowseLinks),
];

// ---------------------------------------------------------------------------
// Key-string parser
// ---------------------------------------------------------------------------

/// One keystroke in a chord. Wraps a crossterm [`KeyCode`] +
/// [`KeyModifiers`] pair, but only retains the three modifier bits
/// that are meaningful at the keymap layer (Ctrl / Alt / Shift) —
/// other crossterm bits (keypad, repeat, …) are filtered in
/// [`KeyStroke::from_event`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeyStroke {
  pub code: KeyCode,
  pub modifiers: KeyModifiers,
}

impl KeyStroke {
  pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
    let (code, modifiers) = Self::normalize(code, Self::sanitize(modifiers));
    Self { code, modifiers }
  }

  /// Build a stroke from a raw crossterm event, dropping modifier
  /// bits we never bind against (KEYPAD, REPEAT, SUPER, HYPER, META).
  pub fn from_event(ev: &KeyEvent) -> Self {
    Self::new(ev.code, ev.modifiers)
  }

  fn sanitize(m: KeyModifiers) -> KeyModifiers {
    m & (KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT)
  }

  /// Fold a shifted character keystroke to a terminal-independent
  /// canonical form. A shifted letter already encodes its shift state
  /// in the glyph itself, but terminals disagree on how they report it:
  ///
  /// - legacy terminals: `Char('V')` with **no** modifier;
  /// - many modern terminals: `Char('V')` **with** `SHIFT`;
  /// - the kitty keyboard protocol: the base key `Char('v')` with `SHIFT`.
  ///
  /// All three mean the same keystroke. We canonicalise any `Char` that
  /// still carries `SHIFT` to its uppercase form with the `SHIFT` bit
  /// dropped, so a binding written `"V"` (parsed to `Char('V')`, no
  /// modifier) matches every variant. Without this, the bound chord and
  /// the runtime event compared unequal on SHIFT-reporting terminals and
  /// every uppercase binding (`G`, `R`, `V`, `H`, …) silently did nothing
  /// (PR #192).
  ///
  /// `BackTab` gets the same treatment for the same reason: it *is* the
  /// shifted Tab, but terminals disagree on whether they additionally set
  /// the `SHIFT` bit (some send bare `BackTab`, others `BackTab` + `SHIFT`,
  /// kitty `BackTab` + `SHIFT`). We canonicalise to bare `BackTab` so a
  /// binding written `"BackTab"` matches every variant. Without this the
  /// modal `prev_field` / `prev_tab` defaults silently stopped firing on
  /// SHIFT-reporting terminals once they routed through the keymap instead
  /// of a modifier-blind `match KeyCode::BackTab` (issue #219 review).
  fn normalize(code: KeyCode, modifiers: KeyModifiers) -> (KeyCode, KeyModifiers) {
    match code {
      KeyCode::Char(c) if modifiers.contains(KeyModifiers::SHIFT) => {
        (KeyCode::Char(c.to_ascii_uppercase()), modifiers - KeyModifiers::SHIFT)
      }
      KeyCode::BackTab if modifiers.contains(KeyModifiers::SHIFT) => {
        (KeyCode::BackTab, modifiers - KeyModifiers::SHIFT)
      }
      _ => (code, modifiers),
    }
  }

  /// Parse a chord string (`"j"`, `"g g"`, `"Ctrl+x Ctrl+s"`) into
  /// its sequence of keystrokes. Whitespace separates keystrokes;
  /// `+` separates modifiers from the key. Use `"Space"` for the
  /// literal space character.
  pub fn parse_chord(s: &str) -> Result<Vec<KeyStroke>> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
      return Err(GwmError::Config(format!("keymap: empty key string {:?}", s)));
    }
    trimmed.split_whitespace().map(Self::parse_single).collect()
  }

  fn parse_single(token: &str) -> Result<KeyStroke> {
    if token.is_empty() {
      return Err(GwmError::Config("keymap: empty keystroke token".into()));
    }
    let parts: Vec<&str> = token.split('+').collect();
    if parts.iter().any(|p| p.is_empty()) {
      return Err(GwmError::Config(format!("keymap: dangling '+' in {:?}", token)));
    }
    let (key_str, mod_strs) = parts.split_last().expect("token is non-empty, split_last cannot fail");

    let mut modifiers = KeyModifiers::empty();
    for m in mod_strs {
      let bit = match *m {
        "Ctrl" => KeyModifiers::CONTROL,
        "Alt" => KeyModifiers::ALT,
        "Shift" => KeyModifiers::SHIFT,
        other => {
          return Err(GwmError::Config(format!(
            "keymap: unknown modifier {:?} in {:?}",
            other, token
          )))
        }
      };
      if modifiers.contains(bit) {
        return Err(GwmError::Config(format!(
          "keymap: duplicate modifier {:?} in {:?}",
          m, token
        )));
      }
      modifiers |= bit;
    }

    let code = parse_keycode(key_str, token)?;
    // Route through `new` so a chord written `"Shift+v"` canonicalises
    // to the same `Char('V')` (no SHIFT) as `"V"` — and matches whatever
    // shift encoding the terminal delivers at runtime. See `normalize`.
    Ok(KeyStroke::new(code, modifiers))
  }
}

fn parse_keycode(s: &str, full_token: &str) -> Result<KeyCode> {
  let code = match s {
    "Tab" => KeyCode::Tab,
    "Enter" => KeyCode::Enter,
    "Esc" => KeyCode::Esc,
    "Up" => KeyCode::Up,
    "Down" => KeyCode::Down,
    "Left" => KeyCode::Left,
    "Right" => KeyCode::Right,
    "Backspace" => KeyCode::Backspace,
    "BackTab" => KeyCode::BackTab,
    "Home" => KeyCode::Home,
    "End" => KeyCode::End,
    "PageUp" => KeyCode::PageUp,
    "PageDown" => KeyCode::PageDown,
    "Insert" => KeyCode::Insert,
    "Delete" => KeyCode::Delete,
    "Space" => KeyCode::Char(' '),
    other if other.starts_with('F') && other.len() > 1 => {
      let n: u8 = other[1..]
        .parse()
        .map_err(|_| GwmError::Config(format!("keymap: invalid function key {:?}", other)))?;
      if !(1..=12).contains(&n) {
        return Err(GwmError::Config(format!(
          "keymap: function key out of range {:?} (expected F1..=F12)",
          other
        )));
      }
      KeyCode::F(n)
    }
    other => {
      let mut chars = other.chars();
      let (first, second) = (chars.next(), chars.next());
      match (first, second) {
        (Some(c), None) => KeyCode::Char(c),
        _ => {
          return Err(GwmError::Config(format!(
            "keymap: unknown key {:?} in {:?}",
            other, full_token
          )))
        }
      }
    }
  };
  Ok(code)
}

impl fmt::Display for KeyStroke {
  /// Canonical rendering used by `gwm tui keys` and the help overlay.
  /// Modifier order is always `Ctrl+Alt+Shift+<key>` so two bindings
  /// that compare equal also render identically.
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if self.modifiers.contains(KeyModifiers::CONTROL) {
      write!(f, "Ctrl+")?;
    }
    if self.modifiers.contains(KeyModifiers::ALT) {
      write!(f, "Alt+")?;
    }
    if self.modifiers.contains(KeyModifiers::SHIFT) {
      write!(f, "Shift+")?;
    }
    match self.code {
      KeyCode::Char(' ') => write!(f, "Space"),
      KeyCode::Char(c) => write!(f, "{c}"),
      KeyCode::Tab => write!(f, "Tab"),
      KeyCode::Enter => write!(f, "Enter"),
      KeyCode::Esc => write!(f, "Esc"),
      KeyCode::Up => write!(f, "Up"),
      KeyCode::Down => write!(f, "Down"),
      KeyCode::Left => write!(f, "Left"),
      KeyCode::Right => write!(f, "Right"),
      KeyCode::Backspace => write!(f, "Backspace"),
      KeyCode::BackTab => write!(f, "BackTab"),
      KeyCode::Home => write!(f, "Home"),
      KeyCode::End => write!(f, "End"),
      KeyCode::PageUp => write!(f, "PageUp"),
      KeyCode::PageDown => write!(f, "PageDown"),
      KeyCode::Insert => write!(f, "Insert"),
      KeyCode::Delete => write!(f, "Delete"),
      KeyCode::F(n) => write!(f, "F{n}"),
      other => write!(f, "{other:?}"),
    }
  }
}

fn format_chord(strokes: &[KeyStroke]) -> String {
  strokes.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(" ")
}

// ---------------------------------------------------------------------------
// Keymap
// ---------------------------------------------------------------------------

/// Where a given binding came from. Surfaces in `gwm tui keys` as the
/// third column so the user can audit what's hers vs. what shipped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
  Default,
  UserConfig,
}

/// One entry in the resolved keymap: an action, the list of chords
/// that fire it (any one match suffices), and the source layer the
/// binding came from.
#[derive(Debug, Clone)]
pub struct Binding {
  pub action: Action,
  pub chords: Vec<Vec<KeyStroke>>,
  pub source: Source,
}

/// Outcome of [`Keymap::lookup`] for a given pending-keys buffer.
#[derive(Debug, PartialEq, Eq)]
pub enum ChordResolution {
  /// Buffer exactly matches a bound chord. Caller fires the action
  /// and clears the buffer.
  Matched(Action),
  /// Buffer is the strict prefix of at least one bound chord.
  /// Caller keeps the buffer armed and waits for the next stroke.
  PendingPrefix,
  /// Buffer matches no binding and is not the prefix of any.
  /// Caller clears the buffer (and may retry the last stroke alone
  /// — that policy lives in the event loop, not here).
  NoMatch,
}

#[derive(Debug, Clone)]
pub struct Keymap {
  entries: Vec<Binding>,
}

impl Keymap {
  /// Built-in defaults. Mirrors the historical hard-coded set in
  /// `src/tui/mod.rs` before issue #87. Adding a default binding
  /// here automatically surfaces it in `gwm tui keys` and the help
  /// overlay.
  pub fn defaults() -> Self {
    let entries = vec![
      def(Action::Down, &["j", "Down"]),
      def(Action::Up, &["k", "Up"]),
      def(Action::Top, &["g g"]),
      def(Action::Bottom, &["G", "End"]),
      // #437: `J` / `K` scroll the Working Tree pane from the status context.
      def(Action::WtScrollDown, &["J"]),
      def(Action::WtScrollUp, &["K"]),
      // #290: V=toggle show/hide, S=cycle content (Commits↔Stashes),
      // Space=cycle orientation (auto/side-by-side/stacked), v=toggle position.
      def(Action::ToggleSidebar, &["V"]),
      def(Action::ToggleSidebarMode, &["S"]),
      def(Action::CycleSidebarLayout, &["Space"]),
      def(Action::ToggleSidebarPosition, &["v"]),
      def(Action::FocusSwap, &["Tab"]),
      def(Action::FocusWorktrees, &["1"]),
      def(Action::FocusStatus, &["2"]),
      def(Action::CommandLogs, &["3"]),
      def(Action::ConfigPanel, &["4"]),
      // #436: `C` opens the CI checks overlay from anywhere in the list
      // view; `c` does the same while the status pane holds the focus
      // (contextual routing, same mechanism as j/k sidebar scroll).
      def(Action::CiChecks, &["C"]),
      // #325: `x` opens the exec profile picker overlay.
      def(Action::ExecOverlay, &["x"]),
      def(Action::AgentSessions, &["a"]),
      // #325: `X` opens the clean reclaim overlay.
      def(Action::CleanOverlay, &["X"]),
      def(Action::Filter, &["/"]),
      def(Action::Refresh, &["f"]),
      // #290: `s` (lowercase) is now Sync — replaces ToggleSidebarMode.
      def(Action::Sync, &["s"]),
      def(Action::Create, &["n"]),
      def(Action::DeleteConfirm, &["d"]),
      def(Action::Bootstrap, &["b"]),
      // #290: `D` (uppercase) is now ToggleDeleteBranch — `p` repurposed as Pull.
      def(Action::ToggleDeleteBranch, &["D"]),
      // #290: `p` is now Pull (was ToggleDeleteBranch before).
      def(Action::Pull, &["p"]),
      // #290: `P` is Push.
      def(Action::Push, &["P"]),
      // #290: `c` opens the edit-worktree modal (rename branch).
      def(Action::EditWorktree, &["c"]),
      // #290: `e` exits the TUI and prints the selected worktree path to stdout.
      def(Action::ExitToWorktree, &["e"]),
      // #35/#290: `l` opens lazygit in an embedded PTY overlay.
      def(Action::LazyGitPty, &["l"]),
      // #290: `L` opens lazygit fullscreen (was unbound before #290).
      def(Action::LazyGitFullscreen, &["L"]),
      // #290: `R` opens the review launcher fullscreen (renamed from review).
      def(Action::ReviewFullscreen, &["R"]),
      // #35/#290: `r` opens the review launcher in an embedded PTY overlay.
      def(Action::ReviewPty, &["r"]),
      // #290: `Y` yanks the worktree path (was `y` before #290).
      def(Action::YankPath, &["Y"]),
      // #290: `y` yanks the branch name (was yank-path `y` before #290).
      def(Action::YankBranchName, &["y"]),
      // #290: `w` yanks the worktree slug/name.
      def(Action::YankWorktreeName, &["w"]),
      // #35/#290: `o` opens a native terminal PTY overlay (renamed from open_terminal_overlay).
      def(Action::TerminalPty, &["o"]),
      // #290: `O` opens a native terminal fullscreen (was unbound before #290).
      def(Action::TerminalFullscreen, &["O"]),
      // #290: `B` opens the browse-links menu (was `O` for open_menu before #290).
      def(Action::BrowseLinks, &["B"]),
      def(Action::OpenDocs, &["."]),
      // #290: `i` links the selected worktree to an issue/PR (was `L` before #290).
      def(Action::LinkPrompt, &["i"]),
      def(Action::FetchGithub, &["F"]),
      // #290: `t` opens the selected worktree in a new multiplexer pane/tab.
      def(Action::MuxPane, &["t"]),
      // #290: `h`/`H` fire user-configured macro1/macro2.
      def(Action::Macro1, &["h"]),
      def(Action::Macro2, &["H"]),
      def(Action::Help, &["?"]),
      def(Action::Quit, &["q"]),
      def(Action::CommandPalette, &[":"]),
    ];
    Self { entries }
  }

  /// Replace the chords bound to `action` with `chords` and re-validate
  /// the full keymap. An empty `Vec` unbinds the action. The validation
  /// pass rejects:
  ///
  /// - the same chord wired to two different actions (conflict);
  /// - a chord that is a strict prefix of another (`g` while `g g`
  ///   is bound) — see the module-level chord/prefix policy note.
  ///
  /// Returns `Err(GwmError::Config(_))` on failure; the keymap is
  /// left untouched on error so callers can surface the message and
  /// move on.
  pub fn apply_override(&mut self, action: Action, chords: Vec<Vec<KeyStroke>>) -> Result<()> {
    // Build the candidate list. For default bindings on other actions, silently
    // vacate any chord that the new user override is claiming — user intent is
    // explicit and wins over shipped defaults. User-vs-user conflicts still
    // fail validation below.
    let new_chord_set: std::collections::HashSet<&[KeyStroke]> = chords.iter().map(|c| c.as_slice()).collect();
    let mut candidate: Vec<(Action, Vec<Vec<KeyStroke>>)> = self
      .entries
      .iter()
      .map(|b| {
        if b.action == action {
          (b.action, chords.clone())
        } else if b.source == Source::Default {
          let pruned: Vec<Vec<KeyStroke>> = b
            .chords
            .iter()
            .filter(|c| !new_chord_set.contains(c.as_slice()))
            .cloned()
            .collect();
          (b.action, pruned)
        } else {
          (b.action, b.chords.clone())
        }
      })
      .collect();
    if !candidate.iter().any(|(a, _)| *a == action) {
      candidate.push((action, chords.clone()));
    }
    Self::validate(&candidate)?;

    // Commit: vacate the claimed chords from default bindings on other actions,
    // then update (or insert) the overridden action's binding.
    for entry in self.entries.iter_mut() {
      if entry.action != action && entry.source == Source::Default {
        entry.chords.retain(|c| !new_chord_set.contains(c.as_slice()));
      }
    }

    let mut replaced = false;
    for entry in self.entries.iter_mut() {
      if entry.action == action {
        entry.chords = chords.clone();
        entry.source = Source::UserConfig;
        replaced = true;
        break;
      }
    }
    if !replaced {
      self.entries.push(Binding {
        action,
        chords,
        source: Source::UserConfig,
      });
    }
    Ok(())
  }

  fn validate(entries: &[(Action, Vec<Vec<KeyStroke>>)]) -> Result<()> {
    let mut all: Vec<(&[KeyStroke], Action)> = Vec::new();
    for (action, chords) in entries {
      for chord in chords {
        if chord.is_empty() {
          return Err(GwmError::Config(format!(
            "keymap: empty chord bound to {:?}",
            action.slug()
          )));
        }
        all.push((chord.as_slice(), *action));
      }
    }
    for i in 0..all.len() {
      for j in (i + 1)..all.len() {
        if all[i].0 == all[j].0 {
          if all[i].1 != all[j].1 {
            return Err(GwmError::Config(format!(
              "keymap: chord {:?} bound to both {:?} and {:?} — conflict",
              format_chord(all[i].0),
              all[i].1.slug(),
              all[j].1.slug()
            )));
          }
          continue;
        }
        let (short, long) = if all[i].0.len() < all[j].0.len() {
          (i, j)
        } else {
          (j, i)
        };
        if all[short].0.len() < all[long].0.len() && all[long].0.starts_with(all[short].0) {
          return Err(GwmError::Config(format!(
            "keymap: chord {:?} (action {:?}) is a prefix of {:?} (action {:?}) — refused at load time so the event loop never has to time out",
            format_chord(all[short].0),
            all[short].1.slug(),
            format_chord(all[long].0),
            all[long].1.slug()
          )));
        }
      }
    }
    Ok(())
  }

  /// Resolve a pending-keys buffer against the keymap.
  pub fn lookup(&self, keys: &[KeyStroke]) -> ChordResolution {
    let mut pending = false;
    for entry in &self.entries {
      for chord in &entry.chords {
        if chord.as_slice() == keys {
          return ChordResolution::Matched(entry.action);
        }
        if chord.len() > keys.len() && chord.starts_with(keys) {
          pending = true;
        }
      }
    }
    if pending {
      ChordResolution::PendingPrefix
    } else {
      ChordResolution::NoMatch
    }
  }

  /// Snapshot the resolved keymap for `gwm tui keys` / help overlay.
  /// Order matches the declarative `define_actions!` invocation so the
  /// rendered table stays stable across runs.
  pub fn list(&self) -> Vec<Binding> {
    self.entries.clone()
  }

  /// The canonical rendering of the **first** chord bound to `action`,
  /// or `None` when the action is unbound. Used by UI copy that names a
  /// key inline (e.g. pane titles such as `Issue / PR [F]`,
  /// issue #224) so the hint tracks user overrides under `[tui.keys]`
  /// instead of hard-coding a default that may have been rebound. A
  /// multi-chord action returns its first chord in declaration order,
  /// matching what `gwm tui keys` lists first.
  pub fn primary_chord(&self, action: Action) -> Option<String> {
    self
      .entries
      .iter()
      .find(|b| b.action == action)
      .and_then(|b| b.chords.first())
      .map(|chord| format_chord(chord))
  }

  /// Every chord bound to `action`, comma-joined (`"j, Down"`) or empty when
  /// unbound — the help-overlay / Keys-tab row form. Mirrors
  /// [`crate::tui::modal_keymap::ModalKeymap::keys_display`].
  pub fn keys_display(&self, action: Action) -> String {
    self
      .entries
      .iter()
      .find(|b| b.action == action)
      .map(|b| b.chords.iter().map(|c| format_chord(c)).collect::<Vec<_>>().join(", "))
      .unwrap_or_default()
  }
}

/// Build a default `Binding` from a list of chord literals. Panics
/// if a literal does not parse — that is a programmer error in the
/// defaults table, never user input.
fn def(action: Action, chord_literals: &[&str]) -> Binding {
  let chords = chord_literals
    .iter()
    .map(|s| {
      KeyStroke::parse_chord(s).unwrap_or_else(|e| panic!("default keymap chord {:?} failed to parse: {}", s, e))
    })
    .collect();
  Binding {
    action,
    chords,
    source: Source::Default,
  }
}