repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
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
//! The footer line [0016](../../../../docs/adr/0016-one-binding-table-feeds-every-surface.md)
//! mandates: derived from the binding table every frame, never a literal binding string.
//! [keybindings.md](../../../../docs/spec/keybindings.md#the-footer) fixes the four rules
//! [`budget`] encodes and the per-context content [`list_items`], [`detail_items`] and
//! [`confirm_items`] read off [`BindingTable::primary_chord`].

use std::fmt;

use ratatui::{Frame, buffer::Buffer, layout::Rect, style::Style};

use crate::{
    degrade::{self, Priority},
    keys::{Action, BindingTable, Context},
    sort::SortColumn,
    theme::{Role, Theme},
};

// `Priority`'s own doc lives on `degrade::Priority`: lower drops first, `Pinned` never
// drops, and items sharing a rank drop together as one atomic group (`! launcher` and
// `; action` here), never one without the other. [header.rs](../header/index.html) shares
// this same enum for the header's own five items, per
// [0026](../../../../docs/adr/0026-the-status-row-is-one-list-not-a-stack-of-surfaces.md)'s
// citation of the footer's own mechanics rather than a second one.

/// One hint's chord text and its label, kept as two fields rather than joined into one
/// opaque string: [theming.md](../../../../docs/spec/theming.md) fixes the key's role as
/// `accent` and the label's as `dim`, and that split only survives to where [`draw`] paints
/// the line because nothing here joins the two first.
#[derive(Clone, Debug)]
struct Hint {
    key: String,
    label: String,
}

impl fmt::Display for Hint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.label.is_empty() {
            write!(f, "{}", self.key)
        } else {
            write!(f, "{} {}", self.key, self.label)
        }
    }
}

struct Item {
    hint: Hint,
    priority: Priority,
    /// Whether the action(s) `hint` names are Built
    /// ([ADR 0023](../../../../docs/adr/0023-an-unbuilt-binding-is-not-advertised-and-an-unavailable-one-answers-on-press.md)).
    /// [`footer_line`] drops every item with `built: false` before the width budget ever
    /// runs: an unbuilt action was never offered, at any width. `list_items` and
    /// `detail_items` still carry it as an `Item` regardless, since the documented
    /// degradation table describes the finished keyboard and the algorithm proof reads
    /// against that full ladder; only the actual render path filters on this field.
    built: bool,
}

/// One item's chord, read from `table` rather than typed here, paired with its short label.
/// Panics naming the gap if `action` is not bound at all in `context`, since that is a wiring
/// bug in this module; an action bound but unbuilt is not a panic; `built` on the returned
/// [`Item`] carries that instead, and [`footer_line`] is what acts on it.
fn hint_item(table: &BindingTable, context: Context, action: Action, label: &str) -> (Hint, bool) {
    let (code, modifiers) = table.primary_chord(context, action).unwrap_or_else(|| {
        panic!("{action:?} is not bound in {context:?}, but the footer names it")
    });
    (
        Hint {
            key: crate::keys::chord_label(code, modifiers),
            label: label.to_string(),
        },
        table.is_built(context, action),
    )
}

/// Two actions' chords joined with `/` as one key, e.g. `j/k`, paired with a combined label
/// like `move`. Built only when both halves are: a combined hint hiding either action's own
/// built state would let one leak past [`footer_line`]'s filter riding on the other's back.
fn combined_hint_item(
    table: &BindingTable,
    context: Context,
    first: Action,
    second: Action,
    label: &str,
) -> (Hint, bool) {
    let chord = |action| {
        let (code, modifiers) = table
            .primary_chord(context, action)
            .unwrap_or_else(|| panic!("{action:?} is not bound in {context:?}"));
        crate::keys::chord_label(code, modifiers)
    };
    let hint = Hint {
        key: format!("{}/{}", chord(first), chord(second)),
        label: label.to_string(),
    };
    let built = table.is_built(context, first) && table.is_built(context, second);
    (hint, built)
}

/// [keybindings.md](../../../../docs/spec/keybindings.md#the-footer)'s list-context content,
/// in display order. Drop order: refresh first, movement second, then `enter detail`,
/// `/ filter`, `space select`, the launcher/action pair, and `? help` pinned last.
fn list_items(table: &BindingTable) -> Vec<Item> {
    let item = |(hint, built), priority| Item {
        hint,
        priority,
        built,
    };
    vec![
        item(
            combined_hint_item(
                table,
                Context::List,
                Action::MoveDown,
                Action::MoveUp,
                "move",
            ),
            Priority::Drop(2),
        ),
        item(
            hint_item(table, Context::List, Action::ToggleSelection, "select"),
            Priority::Drop(5),
        ),
        item(
            hint_item(table, Context::List, Action::OpenDetail, "detail"),
            Priority::Drop(3),
        ),
        item(
            hint_item(table, Context::Global, Action::EnterFilter, "filter"),
            Priority::Drop(4),
        ),
        item(
            hint_item(table, Context::Global, Action::OpenLauncher, "launcher"),
            Priority::Drop(6),
        ),
        item(
            hint_item(table, Context::Global, Action::OpenActionPalette, "action"),
            Priority::Drop(6),
        ),
        item(
            hint_item(table, Context::Global, Action::RefreshAll, "refresh"),
            Priority::Drop(1),
        ),
        item(
            hint_item(table, Context::Global, Action::OpenHelp, "help"),
            Priority::Pinned,
        ),
    ]
}

/// [keybindings.md](../../../../docs/spec/keybindings.md#the-footer)'s detail-context
/// content: the same shape as [`list_items`] with `scroll` standing in for `move` and no
/// `select`/`detail` hints, since neither action exists while the detail pane is focused.
fn detail_items(table: &BindingTable) -> Vec<Item> {
    let item = |(hint, built), priority| Item {
        hint,
        priority,
        built,
    };
    vec![
        item(
            combined_hint_item(
                table,
                Context::Detail,
                Action::ScrollDown,
                Action::ScrollUp,
                "scroll",
            ),
            Priority::Drop(2),
        ),
        item(
            hint_item(table, Context::Global, Action::EnterFilter, "filter"),
            Priority::Drop(3),
        ),
        item(
            hint_item(table, Context::Global, Action::OpenLauncher, "launcher"),
            Priority::Drop(4),
        ),
        item(
            hint_item(table, Context::Global, Action::OpenActionPalette, "action"),
            Priority::Drop(4),
        ),
        item(
            hint_item(table, Context::Global, Action::RefreshAll, "refresh"),
            Priority::Drop(1),
        ),
        item(
            hint_item(table, Context::Global, Action::OpenHelp, "help"),
            Priority::Pinned,
        ),
    ]
}

/// [keybindings.md](../../../../docs/spec/keybindings.md#the-footer)'s confirm-context
/// content: both hints pinned, since its whole footer is documented at 15 columns, short
/// enough to survive almost any frame.
fn confirm_items(table: &BindingTable) -> Vec<Item> {
    let item = |(hint, built), priority| Item {
        hint,
        priority,
        built,
    };
    vec![
        item(
            hint_item(table, Context::Confirm, Action::Run, "run"),
            Priority::Pinned,
        ),
        item(
            hint_item(table, Context::Confirm, Action::Decline, "cancel"),
            Priority::Pinned,
        ),
    ]
}

/// The Filter line's own footer
/// ([keybindings.md](../../../../docs/spec/keybindings.md#the-footer)): `enter apply` and
/// `esc cancel` are pinned, the way in and the way out of the line. `alt-/ clear filter` is
/// the newest of the three and the first to drop, since the other two are what makes the line
/// usable at all.
fn filter_items(table: &BindingTable) -> Vec<Item> {
    let item = |(hint, built), priority| Item {
        hint,
        priority,
        built,
    };
    vec![
        item(
            hint_item(table, Context::Input, Action::Apply, "apply"),
            Priority::Pinned,
        ),
        item(
            hint_item(table, Context::Input, Action::Cancel, "cancel"),
            Priority::Pinned,
        ),
        item(
            hint_item(table, Context::Input, Action::ClearFilter, "clear filter"),
            Priority::Drop(1),
        ),
    ]
}

/// The Action palette's own footer
/// ([keybindings.md](../../../../docs/spec/keybindings.md#the-footer)): the four keys the
/// palette answers while it is choosing, `esc cancel` pinned as the way out. The newline
/// hint is given up first, by rule 2's own reasoning: `ctrl-o editor` reaches the same
/// multi-line command by a route that works on a terminal that sends no meta at all, so the
/// hint with a fallback drops before the one without.
///
/// Drawn by [`draw_action_palette`] into the palette's own last interior row rather than the
/// frame's last row, since the palette takes the whole frame in place of the list, the status
/// row and the footer alike.
fn action_palette_items(table: &BindingTable) -> Vec<Item> {
    let item = |(hint, built), priority| Item {
        hint,
        priority,
        built,
    };
    vec![
        item(
            hint_item(table, Context::Input, Action::Apply, "run"),
            Priority::Drop(3),
        ),
        item(
            hint_item(table, Context::Input, Action::InsertNewline, "newline"),
            Priority::Drop(1),
        ),
        item(
            hint_item(table, Context::Input, Action::OpenInEditor, "editor"),
            Priority::Drop(2),
        ),
        item(
            hint_item(table, Context::Input, Action::Cancel, "cancel"),
            Priority::Pinned,
        ),
    ]
}

/// The sort menu's own footer
/// ([keybindings.md](../../../../docs/spec/keybindings.md#the-footer)): the six column keys
/// in the order the table draws the columns, then the way back to the natural order and the
/// way out. The column hints are given up right to left, which is the order the table's own
/// columns are clipped off a narrowing frame, so the footer stops teaching a sort for a
/// column that is no longer on screen before it stops teaching one that is. `0 natural`
/// outlasts every column key, since it is the way back out of a sort, and `esc cancel` is
/// pinned.
fn sort_items(table: &BindingTable) -> Vec<Item> {
    let item = |(hint, built), priority| Item {
        hint,
        priority,
        built,
    };
    let columns = SortColumn::ALL;
    let mut items: Vec<Item> = columns
        .iter()
        .enumerate()
        .map(|(index, column)| {
            item(
                hint_item(table, Context::Sort, column.action(), column.label()),
                // Right to left: the rightmost column key is given up first, and `name`, the
                // one column the table never clips, is the last one to go.
                Priority::Drop((columns.len() - index) as u8),
            )
        })
        .collect();
    items.push(item(
        hint_item(table, Context::Sort, Action::SortNatural, "natural"),
        Priority::Drop((columns.len() + 1) as u8),
    ));
    items.push(item(
        hint_item(table, Context::Sort, Action::CloseSortMenu, "cancel"),
        Priority::Pinned,
    ));
    items
}

/// The ASCII ellipsis [keybindings.md](../../../../docs/spec/keybindings.md#the-footer) rule
/// 1 fixes: a space then three dots, never unicode's `…`, because `unicode-width` scores
/// that as 2 under `width_cjk` while every other footer glyph scores 1.
const ELLIPSIS: &str = " ...";
/// The two-space gap rule 1 puts between every item.
const SEPARATOR: &str = "  ";

/// The footer's content at some width: the surviving hints in display order, plus whether
/// the ellipsis was reserved for a dropped one, kept unflattened so a later ticket can style
/// each [`Hint`]'s key and label separately at the point [`draw`] paints them.
#[derive(Debug)]
struct FooterLine {
    hints: Vec<Hint>,
    truncated: bool,
}

impl fmt::Display for FooterLine {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let joined = self
            .hints
            .iter()
            .map(Hint::to_string)
            .collect::<Vec<_>>()
            .join(SEPARATOR);
        write!(f, "{joined}")?;
        if self.truncated {
            write!(f, "{ELLIPSIS}")?;
        }
        Ok(())
    }
}

/// Selects `items` into at most `width` ASCII columns, following
/// [keybindings.md](../../../../docs/spec/keybindings.md#the-footer)'s four rules, encoded
/// once in [`degrade::budget`] and shared with the header's own ladder: every item is
/// width-checked including the first (rule 4), the ellipsis is reserved inside the budget
/// rather than appended once something already fits (rule 4), items sharing a [`Priority`]
/// drop together (rule 3), and a [`Priority::Pinned`] item never drops; only the ellipsis
/// drops from it (rule 4). Widths are ASCII byte counts here, which is exactly
/// `unicode-width`'s score for the vocabulary this module builds, per rule 1.
fn budget(items: &[Item], width: usize) -> FooterLine {
    debug_assert!(
        items
            .iter()
            .all(|item| item.hint.key.is_ascii() && item.hint.label.is_ascii()),
        "a footer item must be ASCII, or its byte length is not its display width"
    );
    let generic_items: Vec<degrade::Item<Hint>> = items
        .iter()
        .map(|item| degrade::Item {
            content: item.hint.clone(),
            priority: item.priority,
        })
        .collect();
    let line = degrade::budget(&generic_items, width, SEPARATOR, ELLIPSIS);
    FooterLine {
        hints: line.items,
        truncated: line.truncated,
    }
}

/// [`budget`]'s selection for `context` at `width` columns, read off `table`. `Input`'s
/// content is the Filter line's own footer: the Action and Launcher palettes never reach
/// this function, since each draws its own self-contained overlay rather than sharing the
/// list's status row, list and footer layout. `Global` and `Overlay` never reach it either,
/// since neither owns a footer of its own.
fn footer_line(table: &BindingTable, context: Context, width: u16) -> FooterLine {
    let items = match context {
        Context::List => list_items(table),
        Context::Detail => detail_items(table),
        Context::Confirm => confirm_items(table),
        Context::Input => filter_items(table),
        Context::Sort => sort_items(table),
        Context::Global | Context::Overlay => {
            panic!("no footer content is defined yet for {context:?}")
        }
    };
    drop_unbuilt_then_budget(items, width)
}

/// Carries only Built bindings ([ADR
/// 0023](../../../../docs/adr/0023-an-unbuilt-binding-is-not-advertised-and-an-unavailable-one-answers-on-press.md)):
/// an unbuilt item never enters the width budget at all, dropped unconditionally rather than
/// at some particular width, since it was never offered regardless of how much room there is.
/// A named function rather than inlined in [`footer_line`] so a test can drive this exact
/// filtering step directly, since every context [`footer_line`] dispatches to happens to
/// carry no unbuilt item today.
fn drop_unbuilt_then_budget(items: Vec<Item>, width: u16) -> FooterLine {
    let items: Vec<Item> = items.into_iter().filter(|item| item.built).collect();
    budget(&items, width as usize)
}

/// The footer text for `context` at `width` columns, ASCII throughout, read off `table`
/// rather than a literal binding string: never stale after a rebind, because `App` hands this
/// its live table on every frame, including one right after a config reload. `draw` no
/// longer calls this now that it paints each hint's key and label in their own role: kept as
/// the plain-text oracle the width-budget tests in this module, `app.rs` and `reload.rs`
/// check the render against, independent of colour.
#[allow(dead_code)] // read only from `#[cfg(test)]` call sites now that `draw` paints directly
pub(crate) fn render(table: &BindingTable, context: Context, width: u16) -> String {
    footer_line(table, context, width).to_string()
}

/// [`render`]'s counterpart for the Action palette, which owns a footer of its own rather
/// than the one `Context::Input` renders for the Filter line.
#[allow(dead_code)] // read only from `#[cfg(test)]` call sites, exactly as `render` is
pub(crate) fn render_action_palette(table: &BindingTable, width: u16) -> String {
    drop_unbuilt_then_budget(action_palette_items(table), width).to_string()
}

/// Writes `text` at `(*x, y)` in `style` and advances `*x` by its own byte length: sound
/// only because every footer item is ASCII (the same invariant [`budget`]'s own
/// `debug_assert!` already leans on), so a byte count is always a display-column count.
/// Calls the unbounded `set_string`, never `set_stringn`
/// ([0016](../../../../docs/adr/0016-one-binding-table-feeds-every-surface.md)'s ban on the
/// latter's silent truncation): [`footer_line`] has already selected a line that fits
/// `area`'s own width, so nothing here needs, or should trust, a second clipping pass.
fn paint_run(buf: &mut Buffer, x: &mut u16, y: u16, text: &str, style: Style) {
    debug_assert!(text.is_ascii(), "a footer span must be ASCII: {text:?}");
    buf.set_string(*x, y, text, style);
    *x += text.len() as u16;
}

/// Draws `context`'s footer into `area`, one row, each hint's key in `accent` and its label
/// in `dim` ([theming.md](../../../../docs/spec/theming.md)'s per-surface assignment), the
/// separator and ellipsis carrying no meaning of their own so they paint `dim` alongside the
/// labels: this is [`footer_line`]'s same selection, painted span by span instead of joined
/// into one string first.
pub(crate) fn draw(
    frame: &mut Frame,
    area: Rect,
    context: Context,
    table: &BindingTable,
    theme: &Theme,
) {
    paint_line(frame, area, &footer_line(table, context, area.width), theme);
}

/// [`draw`]'s counterpart for the Action palette, painted into whichever row the palette
/// hands over ([`action_palette_items`]): its own last interior row, not the frame's last.
pub(crate) fn draw_action_palette(
    frame: &mut Frame,
    area: Rect,
    table: &BindingTable,
    theme: &Theme,
) {
    let line = drop_unbuilt_then_budget(action_palette_items(table), area.width);
    paint_line(frame, area, &line, theme);
}

/// One already-selected [`FooterLine`] painted span by span into `area`'s single row, each
/// hint's key in `accent` and its label in `dim`: the one painting path both callers above
/// share, so neither can grow a second set of roles.
fn paint_line(frame: &mut Frame, area: Rect, line: &FooterLine, theme: &Theme) {
    let buf = frame.buffer_mut();
    let mut x = area.x;
    let mut first = true;
    for hint in &line.hints {
        if !first {
            paint_run(buf, &mut x, area.y, SEPARATOR, theme.style_for(Role::Dim));
        }
        first = false;
        paint_run(
            buf,
            &mut x,
            area.y,
            &hint.key,
            theme.style_for(Role::Accent),
        );
        if !hint.label.is_empty() {
            paint_run(buf, &mut x, area.y, " ", theme.style_for(Role::Dim));
            paint_run(buf, &mut x, area.y, &hint.label, theme.style_for(Role::Dim));
        }
    }
    if line.truncated {
        paint_run(buf, &mut x, area.y, ELLIPSIS, theme.style_for(Role::Dim));
    }
}

#[cfg(test)]
mod tests {
    use ratatui::{Terminal, backend::TestBackend};

    use super::*;

    /// The compiled default table, which is all these tests need: none of them exercises a
    /// config rebind, only the derivation and the width budget.
    fn default_table() -> BindingTable {
        BindingTable::compiled_default()
    }

    /// A synthetic single-word hint for the generic budget tests below, which exercise the
    /// drop algorithm independent of the real footer's key/label content.
    fn bare(text: &str) -> Hint {
        Hint {
            key: text.to_string(),
            label: String::new(),
        }
    }

    // --- the generic budget algorithm, proven against synthetic items so each clause has
    // its own test independent of the real footer content ---

    #[test]
    fn budget_width_checks_the_first_item_not_only_later_ones() {
        // Full set is "XXXXXXXXXX  Y", 13 columns. A lazygit-style `i > 0` guard that
        // exempts the first surviving item's width from the fit check would judge the full
        // set to fit at width 5 (13 minus X's own 10 columns is 3, which is <= 5) and return
        // it unchanged, overrunning the real width by 8 columns. Correct behaviour checks
        // the first item too, drops it, and returns "Y ..." instead.
        let items = [
            Item {
                hint: bare("XXXXXXXXXX"),
                priority: Priority::Drop(1),
                built: true,
            },
            Item {
                hint: bare("Y"),
                priority: Priority::Pinned,
                built: true,
            },
        ];
        let rendered = budget(&items, 5).to_string();
        assert_eq!(rendered, "Y ...");
        assert!(rendered.len() <= 5, "must never overrun the given width");
    }

    #[test]
    fn budget_reserves_the_ellipsis_inside_the_budget_rather_than_appending_it_after_a_fit_check() {
        // After dropping the first item, "BB  C" alone fits in 8, but "BB  C ..." (9) does
        // not. A budget that checks fit before adding the ellipsis, then appends it anyway,
        // would stop here and overrun; the correct pass drops further, to "C ...".
        let items = [
            Item {
                hint: bare("AAAA"),
                priority: Priority::Drop(1),
                built: true,
            },
            Item {
                hint: bare("BB"),
                priority: Priority::Drop(2),
                built: true,
            },
            Item {
                hint: bare("C"),
                priority: Priority::Pinned,
                built: true,
            },
        ];
        let rendered = budget(&items, 8).to_string();
        assert_eq!(rendered, "C ...");
        assert!(rendered.len() <= 8, "must never overrun the given width");
    }

    #[test]
    fn budget_drops_the_ellipsis_from_the_last_surviving_item_rather_than_dropping_that_item() {
        let items = [
            Item {
                hint: bare("AAAA"),
                priority: Priority::Drop(1),
                built: true,
            },
            Item {
                hint: bare("BB"),
                priority: Priority::Pinned,
                built: true,
            },
        ];
        assert_eq!(budget(&items, 5).to_string(), "BB");
    }

    #[test]
    fn budget_renders_nothing_once_even_the_pinned_item_alone_cannot_fit() {
        let items = [Item {
            hint: bare("BB"),
            priority: Priority::Pinned,
            built: true,
        }];
        assert_eq!(budget(&items, 1).to_string(), "");
    }

    #[test]
    fn budget_drops_a_shared_priority_group_together_never_one_item_alone() {
        // LAUNCHER and ACTION share a priority. At width 16, dropping LAUNCHER alone would
        // leave "ACTION  HELP ..." (16, fits), which is exactly the bug the atomic-pair rule
        // forbids: the two-repo key vanishing while the one-repo key stays. The correct pass
        // drops both together, giving "HELP ...".
        let items = [
            Item {
                hint: bare("LAUNCHER"),
                priority: Priority::Drop(1),
                built: true,
            },
            Item {
                hint: bare("ACTION"),
                priority: Priority::Drop(1),
                built: true,
            },
            Item {
                hint: bare("HELP"),
                priority: Priority::Pinned,
                built: true,
            },
        ];
        assert_eq!(budget(&items, 16).to_string(), "HELP ...");
    }

    // --- the launcher/action pair, proven across every width rather than at a named one ---

    /// Rule 3 pairs `! launcher` and `; action` so one never renders without the other.
    /// `list_items` and `detail_items` each build the pair inline with its own two
    /// [`Priority`] literals, so nothing stops the two numbers drifting apart under a future
    /// edit; the documented widths for detail happen to land where both are present or both
    /// are gone, so a table lookup at those widths alone cannot catch it. Scanning every
    /// width from zero to the full unrounded line, in both contexts, can.
    #[test]
    fn launcher_and_action_hints_are_never_present_without_each_other_at_any_width() {
        let table = default_table();
        let launcher = hint_item(&table, Context::Global, Action::OpenLauncher, "launcher")
            .0
            .to_string();
        let action = hint_item(&table, Context::Global, Action::OpenActionPalette, "action")
            .0
            .to_string();
        for (context, items) in [
            (Context::List, list_items(&table)),
            (Context::Detail, detail_items(&table)),
        ] {
            let full_width = items
                .iter()
                .map(|item| item.hint.to_string())
                .collect::<Vec<_>>()
                .join(SEPARATOR)
                .len();
            for width in 0..=full_width {
                let rendered = budget(&items, width).to_string();
                let has_launcher = rendered.contains(&launcher);
                let has_action = rendered.contains(&action);
                assert_eq!(
                    has_launcher, has_action,
                    "{context:?} at width {width}: launcher present = {has_launcher}, action \
                     present = {has_action}, rendered {rendered:?}"
                );
            }
        }
    }

    // --- a survivor's key and label stay separate values, not pre-joined ---

    #[test]
    fn a_survivors_key_and_label_stay_separate_fields_after_budget_selects_it() {
        let line = budget(&list_items(&default_table()), 88);
        let move_hint = line
            .hints
            .iter()
            .find(|hint| hint.label == "move")
            .expect("the move hint must survive at full width");
        assert_eq!(move_hint.key, "j/k");
    }

    // --- the real list and detail content, against the documented degradation table ---

    /// One `width  expected text` row of a degradation code block.
    struct Row {
        width: u16,
        expected: String,
    }

    /// Finds the fenced code block that follows `after`, and parses each line as
    /// `<width>  <expected text>`. Panics naming the offending line on anything else,
    /// rather than skipping it, because a row this cannot read is a width case this test
    /// could never have caught wrong.
    fn parse_degradation_table(spec: &str, after: &str) -> Vec<Row> {
        let start = spec
            .find(after)
            .unwrap_or_else(|| panic!("keybindings.md no longer contains {after:?}"));
        let rest = &spec[start..];
        let fence_start = rest
            .find("```\n")
            .expect("a fenced code block must follow the marker");
        let after_fence = &rest[fence_start + 4..];
        let fence_end = after_fence
            .find("```")
            .expect("the fenced code block must close");
        let block = &after_fence[..fence_end];

        block
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| {
                let trimmed = line.trim_start();
                let (width_text, expected) = trimmed.split_once("  ").unwrap_or_else(|| {
                    panic!("degradation table row is not `<width>  <text>`: {line:?}")
                });
                let width: u16 = width_text.trim().parse().unwrap_or_else(|_| {
                    panic!("degradation table row has no numeric width: {line:?}")
                });
                Row {
                    width,
                    expected: expected.trim_end().to_string(),
                }
            })
            .collect()
    }

    fn read_spec() -> String {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        std::fs::read_to_string(manifest_dir.join("../../docs/spec/keybindings.md"))
            .expect("read the keybinding spec")
    }

    /// The documented tables describe the finished keyboard
    /// ([keybindings.md](../../../../docs/spec/keybindings.md)'s "The footer": "The drop
    /// tables below describe the finished keyboard; today's footer is the same ladder over
    /// whichever subset is Built"), so these two tests prove [`budget`]'s drop algorithm
    /// against the full item list `list_items`/`detail_items` build, deliberately bypassing
    /// [`footer_line`]'s Built filter rather than [`render`]: today's `EnterFilter` is
    /// unbuilt, and comparing the real, filtered footer against a table that assumes it is
    /// built would fail the moment this test ran, for a reason that has nothing to do with
    /// the drop algorithm this test exists to check.
    /// [`list_footer_never_advertises_an_unbuilt_binding_at_any_width`] below is what proves
    /// the Built filter itself, against the real `render`.
    #[test]
    fn list_footer_matches_the_documented_degradation_table_at_every_named_width() {
        let spec = read_spec();
        let rows = parse_degradation_table(
            &spec,
            "The list context's footer is 87 columns at full width",
        );
        assert!(!rows.is_empty(), "expected at least one documented width");
        let table = default_table();
        for row in rows {
            assert_eq!(
                budget(&list_items(&table), row.width as usize).to_string(),
                row.expected,
                "list footer mismatch at width {}",
                row.width
            );
        }
    }

    #[test]
    fn detail_footer_matches_the_documented_degradation_table_at_every_named_width() {
        let spec = read_spec();
        let rows = parse_degradation_table(
            &spec,
            "The detail context's footer is 61 columns at full width",
        );
        assert!(!rows.is_empty(), "expected at least one documented width");
        let table = default_table();
        for row in rows {
            assert_eq!(
                budget(&detail_items(&table), row.width as usize).to_string(),
                row.expected,
                "detail footer mismatch at width {}",
                row.width
            );
        }
    }

    #[test]
    fn sort_footer_matches_the_documented_degradation_table_at_every_named_width() {
        let spec = read_spec();
        let rows = parse_degradation_table(
            &spec,
            "The sort context's footer is 73 columns at full width",
        );
        assert!(!rows.is_empty(), "expected at least one documented width");
        let table = default_table();
        for row in rows {
            assert_eq!(
                budget(&sort_items(&table), row.width as usize).to_string(),
                row.expected,
                "sort footer mismatch at width {}",
                row.width
            );
        }
    }

    #[test]
    fn action_palette_footer_matches_the_documented_degradation_table_at_every_named_width() {
        let spec = read_spec();
        let rows = parse_degradation_table(
            &spec,
            "The Action palette's own footer is 55 columns at full width",
        );
        assert!(!rows.is_empty(), "expected at least one documented width");
        let table = default_table();
        for row in rows {
            assert_eq!(
                budget(&action_palette_items(&table), row.width as usize).to_string(),
                row.expected,
                "Action palette footer mismatch at width {}",
                row.width
            );
        }
    }

    /// The newline hint is the first of the four to go, because `ctrl-o editor` is a second
    /// route to the same multi-line command: a user who has lost the one still has the
    /// other, which is the fallback rule 2 orders the whole ladder by. Proven across every
    /// width rather than at the one the documented table names, so the two hints cannot
    /// swap ranks at some width no row happens to cover.
    #[test]
    fn the_action_palette_footer_gives_up_the_newline_hint_before_the_editor_hint() {
        let table = default_table();
        for width in 0..=60u16 {
            let rendered = render_action_palette(&table, width);
            assert!(
                !rendered.contains("newline") || rendered.contains("editor"),
                "width {width} kept the newline hint after dropping the editor hint: \
                 {rendered:?}"
            );
        }
    }

    /// The palette is unusable without a way out, so `esc cancel` is the one hint that
    /// survives every width its footer renders anything at all in.
    #[test]
    fn the_action_palette_footers_way_out_is_the_last_hint_to_go() {
        let table = default_table();
        for width in 10..=60u16 {
            let rendered = render_action_palette(&table, width);
            assert!(
                rendered.contains("esc cancel"),
                "width {width} drew {rendered:?} with no way out of the palette"
            );
        }
    }

    /// The menu is useless without a way out, so `esc cancel` is the one hint that survives
    /// every width the footer renders anything at all in.
    #[test]
    fn the_sort_footers_way_out_is_the_last_hint_to_go() {
        let table = default_table();
        for width in 10..=80u16 {
            let rendered = render(&table, Context::Sort, width);
            assert!(
                rendered.contains("esc cancel"),
                "width {width} drew {rendered:?} with no way out of the menu"
            );
        }
    }

    // --- the real footer, unlike the ladder above, carries only Built bindings ---

    /// The mutation this catches: deleting `drop_unbuilt_then_budget`'s
    /// `.filter(|item| item.built)` line. `footer_line` dispatches every real context to
    /// this same function, so this exercises the production code path rather than a copy of
    /// it; no real footer content today references an unbuilt action (keybindings.md's "Not
    /// built yet" list no longer touches any footer at all now that `/` is built), which is
    /// why this drives the shared function directly with a manufactured unbuilt item rather
    /// than reading one off `list_items` or `detail_items`.
    #[test]
    fn drop_unbuilt_then_budget_never_advertises_an_unbuilt_binding_at_any_width() {
        fn items() -> Vec<Item> {
            vec![
                Item {
                    hint: Hint {
                        key: "x".to_string(),
                        label: "built".to_string(),
                    },
                    priority: Priority::Pinned,
                    built: true,
                },
                Item {
                    hint: Hint {
                        key: "y".to_string(),
                        label: "unbuilt".to_string(),
                    },
                    priority: Priority::Pinned,
                    built: false,
                },
            ]
        }
        let full_width: usize = items()
            .iter()
            .map(|item| item.hint.to_string())
            .collect::<Vec<_>>()
            .join(SEPARATOR)
            .len();
        for width in 0..=full_width {
            let rendered = drop_unbuilt_then_budget(items(), width as u16).to_string();
            assert!(
                !rendered.contains("unbuilt"),
                "width {width} advertises the unbuilt hint: {rendered:?}"
            );
        }
    }

    // --- confirm ---

    #[test]
    fn confirm_footer_matches_the_documented_text_at_its_full_width() {
        assert_eq!(
            render(&default_table(), Context::Confirm, 15),
            "y run  n cancel"
        );
    }

    #[test]
    fn confirm_footer_renders_nothing_once_even_the_pinned_pair_cannot_fit() {
        assert_eq!(render(&default_table(), Context::Confirm, 14), "");
    }

    // --- input: the Filter line's own footer ---

    #[test]
    fn filter_footer_matches_the_documented_degradation_table_at_every_named_width() {
        let spec = read_spec();
        let rows = parse_degradation_table(
            &spec,
            "The Filter line's own footer, which sits one row above the line itself",
        );
        assert!(!rows.is_empty(), "expected at least one documented width");
        let table = default_table();
        for row in rows {
            assert_eq!(
                budget(&filter_items(&table), row.width as usize).to_string(),
                row.expected,
                "filter footer mismatch at width {}",
                row.width
            );
        }
    }

    #[test]
    fn filter_line_footer_renders_nothing_once_even_the_pinned_pair_cannot_fit() {
        assert_eq!(render(&default_table(), Context::Input, 22), "");
    }

    #[test]
    #[should_panic(expected = "no footer content is defined yet for Global")]
    fn footer_still_panics_for_global_and_overlay_which_own_no_footer_of_their_own() {
        render(&default_table(), Context::Global, 80);
    }

    // --- absences the ADR names by name ---

    /// This file's own production source, up to its tests module: reused by both scans below
    /// so each states one absence claim rather than re-reading the file.
    fn production_source() -> String {
        crate::test_support::production_source(include_str!("footer.rs"))
    }

    /// [0016](../../../../docs/adr/0016-one-binding-table-feeds-every-surface.md) names
    /// `Buffer::set_stringn` as the helper that truncates silently rather than dropping
    /// whole items; this module must never call it, only the unbounded `set_string`.
    #[test]
    fn footer_never_calls_the_silently_truncating_set_stringn_helper() {
        let source = production_source();
        let offending: Vec<&str> = source
            .lines()
            .filter(|line| !line.trim_start().starts_with("//"))
            .filter(|line| line.contains("set_stringn"))
            .collect();
        assert!(
            offending.is_empty(),
            "footer.rs must never call Buffer::set_stringn, found: {offending:?}"
        );
    }

    /// [0016](../../../../docs/adr/0016-one-binding-table-feeds-every-surface.md) names
    /// lazygit's `pkg/gui/options_map.go:121` guard, `i > 0 && ...`, which exempts the first
    /// item from the width check. Scans for the shape of that guard, on top of
    /// `budget_width_checks_the_first_item_not_only_later_ones` above, which proves the same
    /// absence behaviourally.
    #[test]
    fn footer_never_reintroduces_the_first_item_exemption_guard() {
        let banned = [
            format!("{} {} 0", "i", ">"),
            format!("{} {} 0", "index", ">"),
            format!("{}(1)", ".skip"),
        ];
        let source = production_source();
        let offending: Vec<&str> = source
            .lines()
            .filter(|line| !line.trim_start().starts_with("//"))
            .filter(|line| banned.iter().any(|needle| line.contains(needle.as_str())))
            .collect();
        assert!(
            offending.is_empty(),
            "found a first-item exemption guard: {offending:?}"
        );
    }

    // --- draw wires render into the buffer at the right row ---

    #[test]
    fn draw_writes_the_rendered_text_at_the_areas_own_row() {
        let table = default_table();
        let backend = TestBackend::new(87, 3);
        let mut terminal = Terminal::new(backend).expect("create test terminal");
        terminal
            .draw(|frame| {
                let area = Rect::new(0, 2, 87, 1);
                draw(frame, area, Context::List, &table, &crate::theme::DEFAULT);
            })
            .expect("draw the frame");
        let buf = terminal.backend().buffer();
        let row: String = (0..87).map(|x| buf[(x, 2)].symbol().to_string()).collect();
        assert_eq!(row.trim_end(), render(&table, Context::List, 87));
    }

    // --- criterion 3: the footer's key/label split takes its colour from the theme's own
    // accent/dim roles, per theming.md's per-surface assignment, rather than the interim
    // uniform `.dim()` this ticket replaces ---

    #[test]
    fn draw_paints_a_hints_key_in_accent_and_its_label_in_dim() {
        let table = default_table();
        let backend = TestBackend::new(40, 1);
        let mut terminal = Terminal::new(backend).expect("create test terminal");
        let theme = crate::theme::DEFAULT;
        terminal
            .draw(|frame| {
                draw(frame, frame.area(), Context::List, &table, &theme);
            })
            .expect("draw the frame");
        let buf = terminal.backend().buffer();

        // The first item is `Enter`'s own chord, per `list_items`; whichever key it is, the
        // rendered row's own first character is that key's own first character, since no
        // hint's key is empty.
        assert_eq!(
            buf[(0, 0)].fg,
            theme.role_color(Role::Accent),
            "expected the first hint's key painted in the theme's accent role"
        );

        let rendered = render(&table, Context::List, 40);
        let first_space = rendered
            .find(' ')
            .expect("the first hint has a non-empty label after its key");
        assert_eq!(
            buf[(first_space as u16 + 1, 0)].fg,
            theme.role_color(Role::Dim),
            "expected the first hint's label, after the key and its separating space, \
             painted in the theme's dim role"
        );
    }
}