mecha-cli 0.1.13

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

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};

/// Which level the modal is showing.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum Level {
    Queues,
    Proposers,
    Candidates,
    Groups,
    Items,
}

/// One store's backlog, as `mecha review queues --json` reports it.
pub struct QueueRow {
    pub name: String,
    /// `None` when the store could not be read. Rendered as a dash and never
    /// as zero — "nothing waiting" and "could not look" are opposite findings,
    /// and the whole reason this modal exists is that a queue grew unnoticed.
    pub depth: Option<usize>,
    pub detail: String,
    /// The `mecha …` verb that owns this queue, shown so the modal never
    /// becomes the only way to reach it.
    pub opens: String,
}

impl QueueRow {
    /// Whether this row is reviewed inside this modal or hands off.
    ///
    /// Keyed on the queue name the command emits, which is the same string on
    /// both sides of one process boundary — a second enum here would be a
    /// second list of queues to keep in step.
    pub fn is_graph(&self) -> bool {
        self.name == "graph candidates"
    }
}

/// One proposing mechanism.
pub struct ProposerRow {
    pub proposer: String,
    pub pending: usize,
    pub classes: usize,
    pub accepted: i64,
    pub rejected: i64,
    pub machine_rejected: i64,
    /// Wilson lower bound, `None` when no human has voted.
    pub accept_lb: Option<f64>,
}

impl ProposerRow {
    pub fn judged(&self) -> i64 {
        self.accepted + self.rejected
    }
    pub fn rate(&self) -> Option<f64> {
        match self.judged() {
            0 => None,
            n => Some(self.accepted as f64 / n as f64),
        }
    }
    /// How much the rate rests on, as a word. A bare percentage reads the
    /// same at n=2 and n=200.
    pub fn tier(&self) -> Tier {
        Tier::of(self.judged())
    }
    pub fn evidence(&self) -> &'static str {
        self.tier().as_str()
    }
}

/// How much of your own judgement a rate rests on.
///
/// The bucket is displayed on every row and is also selectable, because the
/// work that actually moves this queue is concentrated in one tier: 660
/// classes have no human verdict at all, and they sit scattered through a
/// list ordered by size, interleaved with the eighteen that are already
/// settled. Reading the label on every row to find them is how a backlog
/// stays a backlog.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum Tier {
    Unjudged,
    Thin,
    Some,
    Solid,
}

impl Tier {
    /// The bucket a verdict count falls in. One definition, used by the
    /// label and by the filter — two would drift, and a filter that
    /// disagreed with the column beside it is worse than no filter.
    pub fn of(judged: i64) -> Tier {
        match judged {
            0 => Tier::Unjudged,
            1..=9 => Tier::Thin,
            10..=29 => Tier::Some,
            _ => Tier::Solid,
        }
    }
    pub fn as_str(self) -> &'static str {
        match self {
            Tier::Unjudged => "unjudged",
            Tier::Thin => "thin",
            Tier::Some => "some",
            Tier::Solid => "solid",
        }
    }
    /// `t` cycles through the tiers and back to everything. Ordered
    /// least-evidence first, because that is the end of the list somebody
    /// opening this filter is looking for.
    pub fn next(current: Option<Tier>) -> Option<Tier> {
        match current {
            None => Option::Some(Tier::Unjudged),
            Option::Some(Tier::Unjudged) => Option::Some(Tier::Thin),
            Option::Some(Tier::Thin) => Option::Some(Tier::Some),
            Option::Some(Tier::Some) => Option::Some(Tier::Solid),
            Option::Some(Tier::Solid) => None,
        }
    }
}

/// One individual candidate, as `mecha review sample --json` reports it.
pub struct ItemRow {
    pub id: i64,
    pub statement: String,
    pub confidence: f64,
    /// The candidate's full payload, pretty-printed. The list shows one
    /// truncated line; this is where the rest of it lives — the same split
    /// `/tasks` makes, and for the same reason: a verdict on text you could
    /// not read is the approving-unread failure the outbox exists to
    /// prevent, one store over.
    pub payload: String,
    /// When the graph recorded the proposal.
    pub created_at: String,
}

/// One similarity group, as `mecha review groups --json` reports it.
///
/// Its face is the leader's own statement — a real member, never a
/// model-written summary: a verdict lands on these rows, and approving a
/// paraphrase is approving unread (the outbox rule, one store over).
pub struct GroupRow {
    pub leader_id: i64,
    pub statement: String,
    /// Members beyond the leader.
    pub member_ids: Vec<i64>,
    /// A few member statements, shown under the selected row.
    pub sample: Vec<String>,
    /// Class → member count, present only on cross-class (global) groups:
    /// the blast radius, shown before the keystroke that covers it.
    pub classes: Vec<(String, u64)>,
}

impl GroupRow {
    pub fn size(&self) -> usize {
        self.member_ids.len() + 1
    }
    /// Leader first — the id list a dive fetches, and the order it shows.
    pub fn all_ids_csv(&self) -> String {
        std::iter::once(self.leader_id)
            .chain(self.member_ids.iter().copied())
            .map(|i| i.to_string())
            .collect::<Vec<_>>()
            .join(",")
    }
}

/// One pending class, as `mecha review list --json` reports it. The graph
/// clusters by (proposer, predicate), so a row here is a class rather than a
/// single fact — which is the unit the queue is actually decidable in.
pub struct CandidateRow {
    pub proposer: String,
    pub predicate: String,
    pub pending: usize,
    pub accepted: i64,
    pub rejected: i64,
    pub samples: Vec<String>,
}

impl CandidateRow {
    pub fn judged(&self) -> i64 {
        self.accepted + self.rejected
    }
    pub fn tier(&self) -> Tier {
        Tier::of(self.judged())
    }
}

pub struct QueuesModal {
    pub level: Level,
    pub queues: Vec<QueueRow>,
    pub proposers: Vec<ProposerRow>,
    pub candidates: Vec<CandidateRow>,
    pub groups: Vec<GroupRow>,
    /// The cosine floor the current `groups` were computed at — the child's
    /// own report, which is what `[`/`]` step from. Zero until a load lands.
    pub group_threshold: f64,
    pub items: Vec<ItemRow>,
    pub selected: usize,
    /// The class the item level is drawn from.
    pub item_class: Option<(String, String)>,
    /// When the item level was entered from a similarity group: the ids it
    /// shows (leader first). Esc returns to the groups, and a reload
    /// re-fetches these ids instead of redrawing a sample.
    pub from_group: Option<String>,
    /// The seed that produced `items`, so the footer can name it — a sample
    /// nobody can redraw is a sample nobody can check.
    pub item_seed: Option<u64>,
    /// Full view of the selected item (`Enter` at the item level). j/k keep
    /// working and flip through items in place, so a sitting can be reviewed
    /// entirely from the detail — which is the reading a one-line truncation
    /// cannot give.
    pub item_detail: bool,
    /// How far the detail is scrolled. Reset on every move: an offset
    /// carried onto another item is a position in a different document —
    /// the `/tasks` detail_scroll lesson.
    pub detail_scroll: u16,
    /// Show only classes/mechanisms at this evidence tier. `None` is
    /// everything. Applied at render, not at load: the rows are already in
    /// hand, and a filter that re-ran the child process would make a display
    /// toggle cost a subprocess.
    pub tier: Option<Tier>,
    /// The mechanism the candidate list is narrowed to, if any.
    pub filter: Option<String>,
    pub status: Option<String>,
    pub help: bool,
}

impl QueuesModal {
    pub fn new(queues: Vec<QueueRow>) -> Self {
        Self {
            level: Level::Queues,
            queues,
            proposers: vec![],
            candidates: vec![],
            groups: vec![],
            group_threshold: 0.0,
            items: vec![],
            selected: 0,
            item_class: None,
            from_group: None,
            item_seed: None,
            item_detail: false,
            detail_scroll: 0,
            tier: None,
            filter: None,
            status: None,
            help: false,
        }
    }

    /// The mechanisms the tier filter admits.
    ///
    /// Every consumer — the row count, the cursor, the rendering — goes
    /// through this, so a filtered list cannot end up with a cursor pointing
    /// at a row nobody can see. That is the `/outbox` hidden-items bug in a
    /// list where the next keypress may be `r`.
    pub fn visible_proposers(&self) -> Vec<&ProposerRow> {
        self.proposers
            .iter()
            .filter(|p| self.tier.is_none_or(|t| p.tier() == t))
            .collect()
    }

    pub fn visible_candidates(&self) -> Vec<&CandidateRow> {
        self.candidates
            .iter()
            .filter(|c| self.tier.is_none_or(|t| c.tier() == t))
            .collect()
    }

    pub fn len(&self) -> usize {
        match self.level {
            Level::Queues => self.queues.len(),
            Level::Proposers => self.visible_proposers().len(),
            Level::Candidates => self.visible_candidates().len(),
            Level::Groups => self.groups.len(),
            Level::Items => self.items.len(),
        }
    }

    /// Cycle the tier filter, and put the cursor back at the top.
    ///
    /// Resetting is the safe direction: the filtered list is a different
    /// list, so an index carried across names a different row to the next
    /// keypress — and at the class level the next keypress may verdict
    /// everything in it.
    pub fn cycle_tier(&mut self) {
        self.tier = Tier::next(self.tier);
        self.selected = 0;
    }

    /// Whether the current level has evidence to filter on at all. Items are
    /// individual candidates and carry no verdict history of their own.
    pub fn tier_applies(&self) -> bool {
        matches!(self.level, Level::Proposers | Level::Candidates)
    }

    pub fn move_sel(&mut self, delta: i32) {
        let len = self.len();
        if len == 0 {
            return;
        }
        let cur = self.selected.min(len - 1) as i32;
        self.selected = (cur + delta).clamp(0, len as i32 - 1) as usize;
    }

    pub fn selected_queue(&self) -> Option<&QueueRow> {
        self.queues.get(self.selected)
    }
    pub fn selected_proposer(&self) -> Option<&ProposerRow> {
        self.visible_proposers().get(self.selected).copied()
    }
    pub fn selected_candidate(&self) -> Option<&CandidateRow> {
        self.visible_candidates().get(self.selected).copied()
    }
    pub fn selected_group(&self) -> Option<&GroupRow> {
        self.groups.get(self.selected)
    }
    pub fn selected_item(&self) -> Option<&ItemRow> {
        self.items.get(self.selected)
    }

    fn list_scroll(&self, visible: u16) -> u16 {
        let visible = visible.max(1) as usize;
        (self.selected + 1).saturating_sub(visible) as u16
    }

    /// The filter, spelled for the title. A narrowed list that does not say
    /// so is a list that looks like the queue got smaller.
    fn tier_suffix(&self) -> String {
        match self.tier {
            Some(t) => format!(" · {} only", t.as_str()),
            None => String::new(),
        }
    }

    fn title(&self) -> String {
        match self.level {
            Level::Queues => {
                let total: usize = self.queues.iter().filter_map(|q| q.depth).sum();
                format!(" review — {total} waiting ")
            }
            Level::Proposers => {
                let shown: Vec<_> = self.visible_proposers();
                let total: usize = shown.iter().map(|p| p.pending).sum();
                format!(
                    " review · proposers — {total} pending in {}{} ",
                    shown.len(),
                    self.tier_suffix()
                )
            }
            Level::Candidates => {
                let total: usize = self.visible_candidates().iter().map(|c| c.pending).sum();
                let sfx = self.tier_suffix();
                match &self.filter {
                    Some(f) => format!(" review · {f}{total} pending{sfx} "),
                    None => format!(" review · classes — {total} pending{sfx} "),
                }
            }
            Level::Groups => {
                let cls = self
                    .item_class
                    .as_ref()
                    .map(|(p, pr)| format!("{p} · {pr}"))
                    .unwrap_or_else(|| "across all classes".into());
                let covered: usize = self.groups.iter().map(|g| g.size()).sum();
                format!(
                    " {cls}{} group(s) covering {covered} · cosine ≥ {:.2} ",
                    self.groups.len(),
                    self.group_threshold,
                )
            }
            Level::Items => {
                let cls = self
                    .item_class
                    .as_ref()
                    .map(|(p, pr)| format!("{p} · {pr}"))
                    .unwrap_or_else(|| "items".into());
                match (self.item_seed, &self.from_group) {
                    (Some(sd), _) => format!(
                        " {cls} — random sample of {} · seed {sd} ",
                        self.items.len()
                    ),
                    (None, Some(_)) => {
                        format!(" {cls} — one group, {} item(s) ", self.items.len())
                    }
                    (None, None) => format!(" {cls}{} item(s) ", self.items.len()),
                }
            }
        }
    }

    fn key_strip(&self) -> String {
        match self.level {
            Level::Queues => "j/k move · Enter open · ? help · Esc close".into(),
            Level::Proposers => {
                "j/k · Enter classes · s similar EVERYWHERE · t evidence filter · Esc · ? help"
                    .into()
            }
            Level::Candidates => {
                "j/k · Enter sample · s similar groups · a/r verdict WHOLE class · t filter · Esc"
                    .into()
            }
            Level::Groups => {
                "j/k · Enter items · a/r whole group · b bind · A accept new · [/] threshold"
                    .into()
            }
            Level::Items => {
                "j/k · Enter full · a accept · r reject · b bind subject · A accept new · n resample".into()
            }
        }
    }

    pub fn draw(&self, frame: &mut Frame) {
        if self.help {
            self.draw_help(frame);
            return;
        }
        // Only while there is an item to show: a verdict can empty the
        // sample from inside the detail, and a blank box would strand the
        // keys — fall through to the list, which says what happened.
        if self.level == Level::Items && self.item_detail && self.selected_item().is_some() {
            self.draw_item_detail(frame);
            return;
        }
        let strip_text = format!("  {}", self.key_strip());
        let strip = Line::styled(strip_text.clone(), Style::new().fg(Color::Cyan));
        let body = match self.level {
            Level::Queues => self.queue_lines(),
            Level::Proposers => self.proposer_lines(),
            Level::Candidates => self.candidate_lines(),
            Level::Groups => self.group_lines(),
            Level::Items => self.item_lines(),
        };

        let width = 122u16.min(frame.area().width);
        let strip_lines = strip_height(&strip_text, width.saturating_sub(2));
        // Status occupies a line when present, so it is reserved with the
        // strip rather than allowed to push the list past the box.
        let reserved = strip_lines + u16::from(self.status.is_some());
        let height = super::list_height_reserving(body.len() as u16, frame.area().height, reserved);
        let area = super::centered(frame.area(), width, height);
        frame.render_widget(Clear, area);
        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(Style::new().fg(Color::Cyan))
            .title(self.title());
        let inner = block.inner(area);
        frame.render_widget(block, area);
        if inner.height == 0 {
            return;
        }
        let lines = strip_height(&strip_text, inner.width);
        frame.render_widget(
            Paragraph::new(strip).wrap(Wrap { trim: false }),
            Rect {
                height: lines.min(inner.height),
                ..inner
            },
        );
        let mut used = lines;
        if let Some(s) = &self.status {
            if used < inner.height {
                frame.render_widget(
                    Paragraph::new(Line::styled(
                        format!("  {s}"),
                        Style::new().fg(Color::Yellow),
                    )),
                    Rect {
                        y: inner.y + used,
                        height: 1,
                        ..inner
                    },
                );
                used += 1;
            }
        }
        let list = Rect {
            y: inner.y + used,
            height: inner.height.saturating_sub(used),
            ..inner
        };
        frame.render_widget(
            Paragraph::new(body).scroll((self.list_scroll(list.height), 0)),
            list,
        );
    }

    fn queue_lines(&self) -> Vec<Line<'static>> {
        self.queues
            .iter()
            .enumerate()
            .map(|(i, q)| {
                let sel = i == self.selected;
                let marker = if sel { "" } else { " " };
                let depth = match q.depth {
                    Some(n) => format!("{n:>6}"),
                    None => format!("{:>6}", ""),
                };
                let here = if q.is_graph() { "review here" } else { "opens" };
                let text = format!(
                    "{marker} {depth}  {:<22} {:<11} {}",
                    q.name,
                    here,
                    truncate(&q.detail, 62)
                );
                style_row(text, sel, q.depth.is_none(), q.depth == Some(0))
            })
            .collect()
    }

    fn proposer_lines(&self) -> Vec<Line<'static>> {
        let visible = self.visible_proposers();
        if visible.is_empty() {
            return vec![Line::styled(
                format!(
                    "  no mechanism at tier `{}` — t cycles",
                    self.tier.map(Tier::as_str).unwrap_or("all")
                ),
                Style::new().fg(Color::DarkGray),
            )];
        }
        visible
            .iter()
            .enumerate()
            .map(|(i, p)| {
                let sel = i == self.selected;
                let marker = if sel { "" } else { " " };
                // A dash, never 0% — the distinction this whole surface turns on.
                let rate = match p.rate() {
                    Some(r) => format!("{:>4.0}% of {:<5}", r * 100.0, p.judged()),
                    None => format!("{:>4}  {:<7}", "", "none"),
                };
                let text = format!(
                    "{marker} {:>6} in {:<4} {:<24} {rate} {:<9} {} auto-dropped",
                    p.pending,
                    p.classes,
                    truncate(&p.proposer, 24),
                    p.evidence(),
                    p.machine_rejected
                );
                let weak = p.accept_lb.is_some_and(|lb| lb < 0.25);
                style_row(text, sel, false, weak)
            })
            .collect()
    }

    fn candidate_lines(&self) -> Vec<Line<'static>> {
        let visible = self.visible_candidates();
        if visible.is_empty() {
            let msg = match self.tier {
                Some(t) => format!("  no class at tier `{}` here — t cycles", t.as_str()),
                None => "  nothing pending here".to_string(),
            };
            return vec![Line::styled(msg, Style::new().fg(Color::DarkGray))];
        }
        visible
            .iter()
            .enumerate()
            .map(|(i, c)| {
                let sel = i == self.selected;
                let marker = if sel { "" } else { " " };
                let hist = match c.judged() {
                    0 => "".to_string(),
                    n => format!("{:.0}% of {n}", 100.0 * c.accepted as f64 / n as f64),
                };
                let sample = c.samples.first().map(String::as_str).unwrap_or("");
                let text = format!(
                    "{marker} {:>5}  {:<22} {:<12} {:<9} {}",
                    c.pending,
                    truncate(&c.predicate, 22),
                    hist,
                    c.tier().as_str(),
                    truncate(sample, 46)
                );
                style_row(text, sel, false, c.judged() == 0)
            })
            .collect()
    }

    fn group_lines(&self) -> Vec<Line<'static>> {
        if self.groups.is_empty() {
            return vec![Line::styled(
                "  nothing here repeats above the threshold — review the class item by item",
                Style::new().fg(Color::DarkGray),
            )];
        }
        let mut out = Vec::new();
        for (i, g) in self.groups.iter().enumerate() {
            let sel = i == self.selected;
            let marker = if sel { "" } else { " " };
            let text = format!(
                "{marker} ×{:<4} #{:<7} {}",
                g.size(),
                g.leader_id,
                truncate(&g.statement, 92)
            );
            out.push(style_row(text, sel, false, false));
            // The selected group's samples, under it: what the fan-out
            // covers, readable before the keystroke that covers it. A
            // cross-class group leads with the classes it spans — the
            // verdict reaches every one of them.
            if sel {
                if !g.classes.is_empty() {
                    let span: Vec<String> =
                        g.classes.iter().map(|(c, n)| format!("{c} ×{n}")).collect();
                    out.push(Line::styled(
                        format!("            spans: {}", truncate(&span.join(", "), 96)),
                        Style::new().fg(Color::Yellow),
                    ));
                }
                for sm in &g.sample {
                    out.push(Line::styled(
                        format!("            ~ {}", truncate(sm, 96)),
                        Style::new().fg(Color::DarkGray),
                    ));
                }
            }
        }
        out
    }

    fn item_lines(&self) -> Vec<Line<'static>> {
        if self.items.is_empty() {
            return vec![Line::styled(
                "  nothing left in this class",
                Style::new().fg(Color::DarkGray),
            )];
        }
        self.items
            .iter()
            .enumerate()
            .map(|(i, it)| {
                let sel = i == self.selected;
                let marker = if sel { "\u{203a}" } else { " " };
                let text = format!(
                    "{marker} #{:<7} {:.2}  {}",
                    it.id,
                    it.confidence,
                    truncate(&it.statement, 96)
                );
                style_row(text, sel, false, false)
            })
            .collect()
    }

    /// The whole candidate: full statement, then the payload the graph
    /// holds. What a verdict is actually about, readable before it is given.
    fn draw_item_detail(&self, frame: &mut Frame) {
        let Some(it) = self.selected_item() else {
            return;
        };
        let strip = "  j/k next · a accept · r reject · b bind subject · A accept new · Esc back";
        let mut body: Vec<Line> = vec![
            Line::styled(strip.to_string(), Style::new().fg(Color::Cyan)),
            Line::raw(""),
        ];
        // The statement first and wrapped — it is the thing being judged.
        for chunk in wrap_text(&it.statement, 96) {
            body.push(Line::styled(
                format!("  {chunk}"),
                Style::new().fg(Color::White).add_modifier(Modifier::BOLD),
            ));
        }
        body.push(Line::raw(""));
        let mut meta = format!("  #{} · confidence {:.2}", it.id, it.confidence);
        if !it.created_at.is_empty() {
            meta.push_str(&format!(" · proposed {}", it.created_at));
        }
        body.push(Line::styled(meta, Style::new().fg(Color::DarkGray)));
        body.push(Line::raw(""));
        body.push(Line::styled(
            "  ─ payload ─",
            Style::new().fg(Color::DarkGray),
        ));
        for l in it.payload.lines() {
            body.push(Line::styled(format!("  {l}"), Style::new().fg(Color::Gray)));
        }
        let width = 110u16.min(frame.area().width);
        let height = super::list_height(body.len() as u16, frame.area().height);
        let area = super::centered(frame.area(), width, height);
        frame.render_widget(Clear, area);
        let title = format!(
            " #{} — item {} of {} · {} ",
            it.id,
            self.selected + 1,
            self.items.len(),
            self.item_class
                .as_ref()
                .map(|(p, pr)| format!("{p} · {pr}"))
                .unwrap_or_default()
        );
        frame.render_widget(
            Paragraph::new(body)
                .wrap(Wrap { trim: false })
                .scroll((self.detail_scroll, 0))
                .block(
                    Block::default()
                        .borders(Borders::ALL)
                        .border_style(Style::new().fg(Color::Cyan))
                        .title(title),
                ),
            area,
        );
    }

    fn draw_help(&self, frame: &mut Frame) {
        let body: Vec<Line> = HELP
            .lines()
            .map(|l| Line::styled(l.to_string(), Style::new().fg(Color::White)))
            .collect();
        let width = 100u16.min(frame.area().width);
        let height = super::list_height(body.len() as u16, frame.area().height);
        let area = super::centered(frame.area(), width, height);
        frame.render_widget(Clear, area);
        frame.render_widget(
            Paragraph::new(body).wrap(Wrap { trim: false }).block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::new().fg(Color::Cyan))
                    .title(" review — keys "),
            ),
            area,
        );
    }
}

const HELP: &str = "
  Everything waiting on a human, in one place.

  QUEUES
    Enter    open — the graph queue is reviewed here; the others hand
             off to /outbox, /frontdoor and the proposals command, which
             own their own confirmations.
    A dash in the count means the store could not be read, which is not
    the same as nothing waiting.

  PROPOSERS  (the graph queue, by proposing mechanism)
    The rate is YOUR verdicts only. Rejections this pipeline made itself
    — duplicates, ephemerals — are shown separately as auto-dropped and
    never folded in, because a mechanism that mostly repeats itself is a
    different problem from one that is mostly wrong.
    'unjudged' means no human has ever voted on it. It is not a zero.

  t  (proposers and classes)
    Cycle the evidence filter: all → unjudged → thin → some → solid.
    The tier is how many verdicts of YOUR OWN the rate rests on, so
    `unjudged` is the set with no basis at all — 660 classes here, and
    the only ones sampling actually buys anything on. The cursor returns
    to the top on every change, because a filtered list is a different
    list and the next keypress may verdict a whole class.

  PROPOSERS
    s        near-repeats grouped across the WHOLE queue, every class at
             once — the top layer for clearing bulk. Stricter floor than
             a class grouping (out there the class no longer vouches for
             kinship), and every group names the classes it spans.
             Embedding the queue runs a minute or two.

  CLASSES
    Enter    a RANDOM sample of this class, to review one at a time
    s        the class grouped by SEMANTIC SIMILARITY — the queue's bulk
             is the same thing said many ways, and this is the filter
             that shows it
    a        accept the whole class
    r        reject the whole class
    Verdicts on a whole class are for one you have already decided about.
    To learn whether a class is any good, sample it.

  GROUPS  (near-repeats gathered — one class's, or the whole queue's)
    A group's face is a real member's own words plus samples — never a
    model-written summary, because a verdict lands on these rows and
    approving a paraphrase is approving unread.
    Enter    the group's items in full, one at a time
    a        accept the whole group
    r        reject the whole group
    b        an accept failed on `cannot resolve subject`? bind the
             seed's subject to the graph's closest entity — the group
             shares its subject (that is what made it a group), so one
             bind unblocks the whole cascade
    A        accept creating the subject as a NEW topic node, for a
             subject that is genuinely new rather than misspelled
    A group verdict is ONE human verdict — yours, on the top item — and
    the rest follow as a labeled machine cascade the autonomy ladder
    never counts. One keystroke must not manufacture N verdicts.

  ITEMS  (a random sample, seeded so it can be redrawn)
    Enter    the full item — whole statement and payload; j/k flips
             through items without leaving it
    a        accept this one (returns to the list, row removed)
    r        reject this one (same)
    b        an accept failed on `cannot resolve subject`? bind the
             subject to the graph's closest entity — the old spelling
             becomes an alias, so the fix outlives this item — then a
    A        accept creating the subject as a NEW topic node, for a
             subject that is genuinely new rather than misspelled
    n        draw a new sample
    The draw is random because the queue is ordered, and every order it
    could have is correlated with something. Judging the first dozen and
    calling the result the class's accept rate measures the ordering.
    The seed is in the title: quote it and the sample can be checked.

    Both levels run mecha-graph as a child process. Nothing a model can
    call accepts a candidate — that is the point of the split.

  Esc backs out one level at a time.
";

/// One row's styling. Selection wins, then unreadable, then dimmed.
fn style_row(text: String, selected: bool, unreadable: bool, dim: bool) -> Line<'static> {
    if selected {
        Line::styled(text, Style::new().fg(Color::Black).bg(Color::Cyan))
    } else if unreadable {
        Line::styled(text, Style::new().fg(Color::Red))
    } else if dim {
        Line::styled(text, Style::new().fg(Color::DarkGray))
    } else {
        Line::styled(text, Style::new().fg(Color::White))
    }
}

/// Greedy word wrap. `Paragraph::wrap` exists, but the statement needs its
/// own lines so the styling (bold) survives — a single styled Line wraps as
/// one span and keeps its style, so this is belt over braces only for the
/// indent staying even on continuation lines.
fn wrap_text(s: &str, width: usize) -> Vec<String> {
    let mut out = Vec::new();
    let mut line = String::new();
    for word in s.split_whitespace() {
        if !line.is_empty() && line.chars().count() + 1 + word.chars().count() > width {
            out.push(std::mem::take(&mut line));
        }
        if !line.is_empty() {
            line.push(' ');
        }
        line.push_str(word);
    }
    if !line.is_empty() {
        out.push(line);
    }
    if out.is_empty() {
        out.push(String::new());
    }
    out
}

fn truncate(s: &str, n: usize) -> String {
    let s = s.replace('\n', " ");
    if s.chars().count() <= n {
        return s;
    }
    s.chars()
        .take(n.saturating_sub(1))
        .chain(std::iter::once(''))
        .collect()
}

fn strip_height(strip: &str, width: u16) -> u16 {
    let width = width.max(1) as usize;
    (strip.chars().count().div_ceil(width) as u16).max(1)
}

// ─── JSON in ─────────────────────────────────────────────────────────────────

pub fn queues_from_json(text: &str) -> anyhow::Result<Vec<QueueRow>> {
    let v: serde_json::Value = serde_json::from_str(text)?;
    Ok(v.as_array()
        .map(|rows| {
            rows.iter()
                .map(|r| QueueRow {
                    name: r["queue"].as_str().unwrap_or("?").to_string(),
                    // `null` is unreadable, and must not become 0.
                    depth: r["depth"].as_u64().map(|n| n as usize),
                    detail: r["detail"].as_str().unwrap_or("").to_string(),
                    opens: r["opens"].as_str().unwrap_or("").to_string(),
                })
                .collect()
        })
        .unwrap_or_default())
}

/// Groups as `mecha review groups --json` reports them: an envelope of
/// `{threshold, groups}`, where `members` is `[[id, cosine], …]` and only
/// the ids matter here. The threshold comes back so `[`/`]` step from the
/// value that actually ran, never from a local copy of the constant.
pub fn groups_from_json(text: &str) -> anyhow::Result<(f64, Vec<GroupRow>)> {
    let v: serde_json::Value = serde_json::from_str(text)?;
    let threshold = v["threshold"].as_f64().unwrap_or(0.0);
    Ok((
        threshold,
        v["groups"]
            .as_array()
            .map(|rows| {
                rows.iter()
                    .map(|r| GroupRow {
                        leader_id: r["leader_id"].as_i64().unwrap_or(0),
                        statement: r["leader_statement"].as_str().unwrap_or("?").to_string(),
                        member_ids: r["members"]
                            .as_array()
                            .map(|ms| {
                                ms.iter()
                                    .filter_map(|m| m.get(0).and_then(|x| x.as_i64()))
                                    .collect()
                            })
                            .unwrap_or_default(),
                        sample: r["sample"]
                            .as_array()
                            .map(|a| {
                                a.iter()
                                    .filter_map(|s| s.as_str().map(String::from))
                                    .collect()
                            })
                            .unwrap_or_default(),
                        classes: r["classes"]
                            .as_object()
                            .map(|o| {
                                o.iter()
                                    .map(|(k, n)| (k.clone(), n.as_u64().unwrap_or(0)))
                                    .collect()
                            })
                            .unwrap_or_default(),
                    })
                    .collect()
            })
            .unwrap_or_default(),
    ))
}

pub fn proposers_from_json(text: &str) -> anyhow::Result<Vec<ProposerRow>> {
    let v: serde_json::Value = serde_json::from_str(text)?;
    Ok(v.as_array()
        .map(|rows| {
            rows.iter()
                .map(|r| ProposerRow {
                    proposer: r["proposer"].as_str().unwrap_or("?").to_string(),
                    pending: r["pending"].as_u64().unwrap_or(0) as usize,
                    classes: r["classes"].as_u64().unwrap_or(0) as usize,
                    accepted: r["accepted_hist"].as_i64().unwrap_or(0),
                    rejected: r["rejected_hist"].as_i64().unwrap_or(0),
                    machine_rejected: r["machine_rejected"].as_i64().unwrap_or(0),
                    accept_lb: r["accept_lb"].as_f64(),
                })
                .collect()
        })
        .unwrap_or_default())
}

/// Individual candidates, as `mecha-graph review --json` serialises a
/// `FactCandidate`. The statement lives under `payload`, with `what` as the
/// commitment-shaped alternative — the same two keys the graph's own views
/// look under, so a commitment does not render blank here alone.
pub fn items_from_json(text: &str) -> anyhow::Result<Vec<ItemRow>> {
    let v: serde_json::Value = serde_json::from_str(text)?;
    Ok(v.as_array()
        .map(|rows| {
            rows.iter()
                .map(|r| ItemRow {
                    id: r["id"].as_i64().unwrap_or(0),
                    statement: r["payload"]["statement"]
                        .as_str()
                        .or_else(|| r["payload"]["what"].as_str())
                        .unwrap_or("(no statement)")
                        .to_string(),
                    confidence: r["confidence"].as_f64().unwrap_or(0.0),
                    payload: serde_json::to_string_pretty(&r["payload"])
                        .unwrap_or_else(|_| "{}".into()),
                    created_at: r["created_at"].as_str().unwrap_or("").to_string(),
                })
                .collect()
        })
        .unwrap_or_default())
}

pub fn candidates_from_json(text: &str) -> anyhow::Result<Vec<CandidateRow>> {
    let v: serde_json::Value = serde_json::from_str(text)?;
    Ok(v.as_array()
        .map(|rows| {
            rows.iter()
                .map(|r| CandidateRow {
                    proposer: r["proposed_by"].as_str().unwrap_or("?").to_string(),
                    predicate: r["predicate"].as_str().unwrap_or("?").to_string(),
                    pending: r["pending"].as_u64().unwrap_or(0) as usize,
                    accepted: r["accepted_hist"].as_i64().unwrap_or(0),
                    rejected: r["rejected_hist"].as_i64().unwrap_or(0),
                    samples: r["samples"]
                        .as_array()
                        .map(|a| {
                            a.iter()
                                .filter_map(|s| s.as_str().map(String::from))
                                .collect()
                        })
                        .unwrap_or_default(),
                })
                .collect()
        })
        .unwrap_or_default())
}

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

    /// An unreadable store must not render as an empty one.
    ///
    /// `depth: null` is what the command emits when it could not open a
    /// store, and the whole reason this modal exists is that a queue grew to
    /// 6,434 without anyone noticing — a reader that reported its own failure
    /// as "nothing waiting" would reproduce that exactly.
    #[test]
    fn an_unreadable_queue_is_none_and_not_zero() {
        let rows = queues_from_json(
            r#"[{"queue":"graph candidates","depth":null,"detail":"binary missing","opens":"x"},
                {"queue":"outbox drafts","depth":0,"detail":"","opens":"y"}]"#,
        )
        .unwrap();
        assert_eq!(rows[0].depth, None, "null stays unknown");
        assert_eq!(rows[1].depth, Some(0), "a real zero is a real zero");
        assert!(rows[0].is_graph());
        assert!(!rows[1].is_graph());
    }

    /// A proposer nobody has judged has no rate, and no evidence word that
    /// could be mistaken for one.
    #[test]
    fn an_unjudged_proposer_has_no_rate() {
        let rows = proposers_from_json(
            r#"[{"proposer":"bee:suggested","pending":1084,"classes":1,
                 "accepted_hist":0,"rejected_hist":0,"machine_rejected":16,"accept_lb":null},
                {"proposer":"llm","pending":4841,"classes":726,
                 "accepted_hist":1175,"rejected_hist":809,"machine_rejected":1167,
                 "accept_lb":0.5717}]"#,
        )
        .unwrap();
        assert_eq!(rows[0].rate(), None);
        assert_eq!(rows[0].evidence(), "unjudged");
        assert_eq!(rows[0].machine_rejected, 16);
        assert_eq!(rows[1].evidence(), "solid");
        assert!((rows[1].rate().unwrap() - 0.5923).abs() < 0.001);
    }

    /// Moving the cursor never leaves the list, and never panics on an empty
    /// one — the modal opens on whatever the stores happen to hold.
    #[test]
    fn selection_stays_inside_the_list() {
        let mut m = QueuesModal::new(vec![]);
        m.move_sel(1);
        assert_eq!(m.selected, 0, "an empty list has nowhere to go");
        m.queues = queues_from_json(
            r#"[{"queue":"a","depth":1,"detail":"","opens":""},
                {"queue":"b","depth":2,"detail":"","opens":""}]"#,
        )
        .unwrap();
        m.move_sel(5);
        assert_eq!(m.selected, 1, "clamped to the last row");
        m.move_sel(-5);
        assert_eq!(m.selected, 0, "and to the first");
    }

    /// A commitment-shaped candidate has `what`, not `statement`, and must
    /// not render blank — it is the one payload shape that differs.
    #[test]
    fn an_item_renders_from_either_payload_shape() {
        let rows = items_from_json(
            r#"[{"id":12,"confidence":0.9,"payload":{"statement":"A works at B","predicate":"works_at"}},
                {"id":13,"confidence":0.5,"payload":{"what":"send the draft","kind":"commitment"}},
                {"id":14,"confidence":0.1,"payload":{}}]"#,
        )
        .unwrap();
        assert_eq!(rows[0].statement, "A works at B");
        assert_eq!(
            rows[1].statement, "send the draft",
            "commitments use `what`"
        );
        assert_eq!(rows[2].statement, "(no statement)", "and never blank");
        assert_eq!(rows[0].id, 12);
        assert!(
            rows[0].payload.contains("works_at"),
            "the detail view gets the whole payload: {}",
            rows[0].payload
        );
    }

    /// The detail shows the full statement the list truncated.
    ///
    /// The list clips at ~96 characters, and a verdict on text you could not
    /// read is the approving-unread failure the outbox exists to prevent —
    /// this is the screenshot bug: an item whose statement ended in "and pe…"
    /// with no way to see the rest.
    #[test]
    fn the_detail_carries_what_the_list_truncates() {
        let long = "Possible duplicate: person node person-5ef7b325 (Grace Choi) and person node person-9a1b2c3d (Grace H. Choi) share an email identifier and forty-one overlapping calendar events".to_string();
        let rows = items_from_json(&format!(
            r#"[{{"id":1737,"confidence":0.8,"payload":{{"statement":"{long}"}}}}]"#
        ))
        .unwrap();
        assert_eq!(
            rows[0].statement, long,
            "nothing lost between JSON and detail"
        );
        let wrapped = wrap_text(&rows[0].statement, 96);
        assert!(wrapped.len() > 1, "and it wraps rather than clips");
        assert_eq!(
            wrapped.join(" "),
            long,
            "wrapping reflows; it never drops a word"
        );
    }

    fn proposer(name: &str, pending: usize, a: i64, r: i64) -> ProposerRow {
        ProposerRow {
            proposer: name.into(),
            pending,
            classes: 1,
            accepted: a,
            rejected: r,
            machine_rejected: 0,
            accept_lb: if a + r == 0 { None } else { Some(0.5) },
        }
    }

    /// The filter selects on the same buckets the column displays.
    ///
    /// One definition (`Tier::of`) behind both. Two would drift, and a filter
    /// that disagreed with the word printed beside it is worse than no
    /// filter — you would reject a class believing it was in a tier it was
    /// not.
    #[test]
    fn the_tier_filter_and_the_tier_label_agree() {
        let mut m = QueuesModal::new(vec![]);
        m.level = Level::Proposers;
        m.proposers = vec![
            proposer("bee:suggested", 1084, 0, 0),   // unjudged
            proposer("rule:x", 29, 3, 2),            // thin (5)
            proposer("llm:commitment", 421, 10, 14), // some (24)
            proposer("llm", 4841, 1175, 809),        // solid
        ];
        assert_eq!(m.len(), 4, "no filter shows everything");

        for (tier, expect) in [
            (Tier::Unjudged, "bee:suggested"),
            (Tier::Thin, "rule:x"),
            (Tier::Some, "llm:commitment"),
            (Tier::Solid, "llm"),
        ] {
            m.tier = Some(tier);
            m.selected = 0;
            let vis = m.visible_proposers();
            assert_eq!(vis.len(), 1, "exactly one at {tier:?}");
            assert_eq!(vis[0].proposer, expect);
            assert_eq!(
                vis[0].evidence(),
                tier.as_str(),
                "the printed label is the bucket the filter selected on"
            );
        }
    }

    /// `t` cycles through every tier and back to everything, and the cursor
    /// never survives the change.
    ///
    /// A filtered list is a different list, so an index carried across names
    /// a different row — and at the class level the next keypress verdicts
    /// everything in that row.
    #[test]
    fn cycling_the_tier_resets_the_cursor_and_returns_to_all() {
        let mut m = QueuesModal::new(vec![]);
        m.level = Level::Proposers;
        m.proposers = vec![proposer("a", 1, 0, 0), proposer("b", 1, 0, 0)];
        m.selected = 1;
        let mut seen = vec![];
        for _ in 0..5 {
            m.cycle_tier();
            assert_eq!(m.selected, 0, "cursor home on every change");
            seen.push(m.tier);
        }
        assert_eq!(
            seen,
            vec![
                Some(Tier::Unjudged),
                Some(Tier::Thin),
                Some(Tier::Some),
                Some(Tier::Solid),
                None
            ],
            "least evidence first, then back to everything"
        );
    }

    /// Selection reads the filtered list, never the raw one.
    ///
    /// If `selected_proposer` indexed `self.proposers` while the rows drawn
    /// came from the filtered view, a keystroke would act on a row that is
    /// not on screen.
    #[test]
    fn selection_follows_the_filter_not_the_raw_list() {
        let mut m = QueuesModal::new(vec![]);
        m.level = Level::Proposers;
        m.proposers = vec![
            proposer("solid-one", 10, 40, 10),
            proposer("unjudged-one", 20, 0, 0),
        ];
        m.tier = Some(Tier::Unjudged);
        m.selected = 0;
        assert_eq!(
            m.selected_proposer().map(|p| p.proposer.as_str()),
            Some("unjudged-one"),
            "row 0 of the FILTERED list, not of the raw one"
        );
        m.move_sel(1);
        assert_eq!(m.selected, 0, "and it cannot move past the filtered end");
    }

    /// The box must draw at sizes where the naive clamp panics.
    ///
    /// `rows.clamp(1, height - 4)` asserts `min <= max` the moment the
    /// terminal is four rows or fewer, which took whole sessions down from
    /// seven other modals. The assertion here IS the draw.
    #[test]
    fn it_draws_at_tiny_sizes() {
        let mut m = QueuesModal::new(
            queues_from_json(
                r#"[{"queue":"graph candidates","depth":6434,"detail":"d","opens":"o"}]"#,
            )
            .unwrap(),
        );
        m.status = Some("accepted 12".into());
        for h in 1..=8u16 {
            for w in [8u16, 40, 130] {
                let backend = ratatui::backend::TestBackend::new(w, h);
                let mut term = Terminal::new(backend).unwrap();
                term.draw(|f| m.draw(f)).unwrap();
            }
        }
        m.groups = groups_from_json(
            r#"{"v":1,"threshold":0.83,"groups":[
                {"leader_id":9281,"leader_statement":"Luke has a child named Emmy",
                 "members":[[9302,0.91],[9310,0.88]],
                 "sample":["Luke has a child named Sage"]}]}"#,
        )
        .unwrap()
        .1;
        for level in [Level::Candidates, Level::Groups, Level::Items] {
            m.level = level;
            for h in 1..=6u16 {
                let backend = ratatui::backend::TestBackend::new(30, h);
                let mut term = Terminal::new(backend).unwrap();
                term.draw(|f| m.draw(f)).unwrap();
            }
        }
        // The item detail, including at sizes where the naive clamp panics,
        // and the emptied-sample fall-through.
        m.level = Level::Items;
        m.items = items_from_json(
            r#"[{"id":9,"confidence":0.8,"created_at":"2026-08-22 04:54:25",
                 "payload":{"statement":"A very long statement that will need wrapping across several lines to be read in full","predicate":"related_to","subject":"A","object":"B"}}]"#,
        )
        .unwrap();
        m.item_detail = true;
        for h in 1..=8u16 {
            let backend = ratatui::backend::TestBackend::new(40, h);
            let mut term = Terminal::new(backend).unwrap();
            term.draw(|f| m.draw(f)).unwrap();
        }
        m.items.clear();
        let backend = ratatui::backend::TestBackend::new(40, 8);
        let mut term = Terminal::new(backend).unwrap();
        term.draw(|f| m.draw(f)).unwrap(); // detail open, nothing left — must not blank
    }

    /// A group row carries the ids a cascade will land on, leader first —
    /// and parses the graph's `[[id, cosine], …]` member shape.
    #[test]
    fn a_group_parses_and_names_its_ids_leader_first() {
        let (threshold, rows) = groups_from_json(
            r#"{"v":1,"threshold":0.83,"groups":[
                {"leader_id":9281,"leader_statement":"Luke has a child named Emmy",
                 "members":[[9302,0.91],[9310,0.88]],
                 "sample":["Luke has a child named Sage"]}]}"#,
        )
        .unwrap();
        assert!(
            (threshold - 0.83).abs() < 1e-9,
            "the envelope reports what ran"
        );
        assert_eq!(rows[0].size(), 3);
        assert_eq!(rows[0].member_ids, vec![9302, 9310]);
        assert_eq!(rows[0].all_ids_csv(), "9281,9302,9310");
        assert_eq!(rows[0].sample, vec!["Luke has a child named Sage"]);
    }
    /// The global envelope's `classes` object becomes the spans line, and
    /// its absence (a class grouping) parses to an empty blast radius —
    /// one parser for both shapes, so the level cannot fork.
    #[test]
    fn a_global_group_carries_its_blast_radius_and_a_class_group_carries_none() {
        let (t, rows) = groups_from_json(
            r#"{"v":1,"threshold":0.9,"across_classes":true,"considered":6929,"groups":[
                {"leader_id":1,"leader_statement":"Luke has twins",
                 "leader_class":"llm . has",
                 "members":[[2,0.95]],
                 "classes":{"bee:suggested . family":1,"llm . has":1},
                 "sample":["Luke has twin girls"]}]}"#,
        )
        .unwrap();
        assert_eq!(t, 0.9);
        assert_eq!(
            rows[0].classes,
            vec![
                ("bee:suggested . family".to_string(), 1),
                ("llm . has".to_string(), 1)
            ]
        );
        let (_, rows) = groups_from_json(
            r#"{"v":1,"threshold":0.83,"groups":[
                {"leader_id":1,"leader_statement":"x","members":[],"sample":[]}]}"#,
        )
        .unwrap();
        assert!(rows[0].classes.is_empty());
    }

    /// The proposer level's strip names the global entry: a modal whose
    /// actions are invisible is a modal with one action (the /mail rule).
    #[test]
    fn the_proposer_strip_names_the_global_similarity_key() {
        let mut m = QueuesModal::new(vec![]);
        m.level = Level::Proposers;
        assert!(
            m.key_strip().contains("s similar EVERYWHERE"),
            "{}",
            m.key_strip()
        );
    }
}