shep 0.6.4

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

use ratatui::style::Style;
use ratatui::text::{Line, Span};
use shep_core::protocol::ProcessInfo;
use shep_core::status::ProcStatus;

use super::super::app::{App, GroupTotals, Row, RowKey};
use super::super::theme::Palette;
use super::cell;
use crate::output::width::char_columns;
use crate::output::{cfg_cell, exit_cell, human_bytes, human_duration};

/// The narrowest terminal the table will draw into.
///
/// `ID` + `NAME` (floor 8) + `STATUS` (15, the width of `waiting-restart`)
/// plus two separators. This is the table's own floor, not the terminal's:
/// the terminal also needs room for [`GUTTER`], the selection marker's
/// column.
pub const MIN_WIDTH: u16 = 31;

/// The shortest terminal the pane will draw into: title, banner, header,
/// rule, one data row, status bar.
pub const MIN_HEIGHT: u16 = 6;

/// The floor on the NAME column, which takes whatever the fixed columns
/// leave.
pub const NAME_MIN: u16 = 8;

/// The ceiling on the NAME column.
///
/// NAME takes the remainder, which is right up to a point and absurd past
/// it: on a 224-column terminal the remainder is 84 cells for names that
/// are rarely longer than twenty, so the table becomes a field of
/// whitespace with the numbers pushed to the far right, where they are
/// harder to read against each other than they were before. Past this
/// width the table simply ends and the rest of the row stays empty, which
/// is what the design's own frames did with their right margin.
///
/// 32 rather than the frames' 24: it clears the longest name in this
/// repository's own example Flockfile, `http-server-gated-by-sentinel`.
pub const NAME_MAX: u16 = 32;

/// The columns the selection marker takes, to the left of the table.
///
/// One for the marker, one for the gap. The table itself is rendered into
/// `width - GUTTER` starting at `x + GUTTER`, so every threshold in
/// [`TIERS`] and every arithmetic in [`name_width`] is untouched by the
/// marker.
pub const GUTTER: u16 = 2;

/// The marker for the selected row, or a blank for every other row.
///
/// A plain ASCII `>`, not a colour and not a `REVERSED` modifier: every
/// signal on this screen survives `NO_COLOR` and a 16-colour terminal, and a
/// decoration-only cursor does not. `â–¸` is East-Asian *Ambiguous* width, and a
/// terminal that renders it double-wide would shift every column of that one
/// row by a cell.
#[must_use]
pub const fn mark(selected: bool) -> &'static str {
    if selected { ">" } else { " " }
}

/// The selected row's edge: a painted space, or the ASCII marker when
/// there is no colour to paint with.
///
/// A space rather than `▌`, for the reason [`mark`] gives about `▸`:
/// every block glyph in this pane's vocabulary is East-Asian
/// *Ambiguous*, and a doubled cell in the gutter shifts the whole row.
/// A space is one column on every terminal, and the background carries
/// the whole signal.
#[must_use]
pub fn gutter(selected: bool, palette: Palette) -> (&'static str, Style) {
    match (selected, palette.ground()) {
        (false, _) => (" ", Style::default()),
        (true, ground) if ground.bg.is_some() => (" ", ground),
        (true, _) => (mark(true), Style::default()),
    }
}

/// One column of the flock table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Column {
    /// The sheep's stable numeric id.
    Id,
    /// Its name. The flexible column.
    Name,
    /// Its lifecycle status, the one coloured cell.
    Status,
    /// Its OS pid while running.
    Pid,
    /// Restarts since registration.
    Restarts,
    /// Its last exit, once it is not running. Rendered by
    /// [`crate::output::exit_cell`], the same function
    /// `output::rows::FlockRows`'s own EXIT column calls.
    Exit,
    /// Whether a config load has parked a change for this sheep's next
    /// spawn, or an operator has overridden a field its Flockfile no longer
    /// declares. Rendered by [`crate::output::cfg_cell`], the same function
    /// `output::rows::FlockRows`'s own CFG column calls.
    Cfg,
    /// The last twenty seconds of tree CPU, one cell per sample. `shep flock`
    /// draws no equivalent; a still frame has nowhere to put one.
    CpuSpark,
    /// Tree CPU as a percentage of one core.
    Cpu,
    /// Resident set size against [`ProcessInfo::max_memory`], as a filled
    /// bar. `shep flock` draws no equivalent, for the same reason as
    /// [`Self::CpuSpark`].
    MemCeil,
    /// Tree resident set size.
    Mem,
    /// Time since its last successful start.
    Uptime,
    /// Fold membership.
    Fold,
    /// A short marker a dog attaches to a sheep over the client protocol's
    /// `SetSmit` request, last in the header order to match
    /// `output::rows::FlockRows`'s. shep paints what a dog wrote and never
    /// parses it.
    Smit,
}

impl Column {
    /// The header text. Every column `output::rows::FlockRows` also draws
    /// shares its vocabulary, enforced by
    /// `every_shared_header_still_matches_flock_rows_exactly` below.
    #[must_use]
    pub const fn header(self) -> &'static str {
        match self {
            Self::Id => "ID",
            Self::Name => "NAME",
            Self::Status => "STATUS",
            Self::Pid => "PID",
            Self::Restarts => "RESTARTS",
            Self::Exit => "EXIT",
            Self::Cfg => "CFG",
            Self::CpuSpark => "CPU 20s",
            Self::Cpu => "CPU",
            Self::MemCeil => "MEM/CEIL",
            Self::Mem => "MEM",
            Self::Uptime => "UPTIME",
            Self::Fold => "FOLD",
            Self::Smit => "SMIT",
        }
    }

    /// The fixed width of this column's cells. `Name` reports `0`: it is
    /// the column that takes the remainder, and [`name_width`] computes it.
    #[must_use]
    pub const fn width(self) -> u16 {
        match self {
            Self::Id => 4,
            Self::Name => 0,
            // 15: `waiting-restart`, the longest word `Reported::word`
            // returns.
            Self::Status => 15,
            Self::Pid => 7,
            Self::Restarts => 8,
            // 9: `SIGVTALRM`/`SIGSTKFLT`, the longest names
            // `nix::sys::signal::Signal::as_str` returns.
            Self::Exit => 9,
            // 4: `!12`/`*12`, a `cfg_cell`'s own longest realistic value.
            Self::Cfg => 4,
            Self::CpuSpark => 10,
            Self::Cpu => 6,
            Self::MemCeil => 10,
            Self::Mem => 8,
            Self::Uptime => 8,
            Self::Fold => 10,
            // 13: `visible_width("â–² main@a1b2c3")`, the measured width of the
            // real strings a deploy dog paints. A longer smit truncates via
            // [`fit`] rather than growing the column.
            Self::Smit => 13,
        }
    }
}

/// Every column, including the two the terminal must be widest to keep.
///
/// `CpuSpark` and `MemCeil` sit beside `Cpu` and `Mem`, the cells they add
/// context to, rather than up front where the header test's ordering
/// (`every_shared_header_still_matches_flock_rows_exactly`) would put them
/// ahead of `Pid`/`Restarts`/`Exit`/`Cfg` and break that vocabulary check.
const ALL: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Restarts,
    Column::Exit,
    Column::Cfg,
    Column::CpuSpark,
    Column::Cpu,
    Column::MemCeil,
    Column::Mem,
    Column::Uptime,
    Column::Fold,
    Column::Smit,
];
/// `ALL` minus `MemCeil`, the first column a narrowing terminal sheds.
const NO_CEIL: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Restarts,
    Column::Exit,
    Column::Cfg,
    Column::CpuSpark,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
    Column::Fold,
    Column::Smit,
];
/// `NO_CEIL` minus `CpuSpark`: today's full set, and today's threshold.
const NO_SPARK: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Restarts,
    Column::Exit,
    Column::Cfg,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
    Column::Fold,
    Column::Smit,
];
// `NO_SPARK` minus CFG, the next column dropped. See `TIERS`'s own doc for
// the drop order.
const NO_CFG: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Restarts,
    Column::Exit,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
    Column::Fold,
    Column::Smit,
];
const NO_SMIT: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Restarts,
    Column::Exit,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
    Column::Fold,
];
const NO_FOLD: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Restarts,
    Column::Exit,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
];
const NO_EXIT: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Restarts,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
];
const NO_RESTARTS: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Pid,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
];
const NO_PID: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Cpu,
    Column::Mem,
    Column::Uptime,
];
const NO_MEM: &[Column] = &[
    Column::Id,
    Column::Name,
    Column::Status,
    Column::Cpu,
    Column::Uptime,
];
const NO_CPU: &[Column] = &[Column::Id, Column::Name, Column::Status, Column::Uptime];
const FLOOR: &[Column] = &[Column::Id, Column::Name, Column::Status];

/// The narrowest terminal that still draws the `CFG` column.
///
/// Read by the status bar's own test: the legend explaining `*` and `!`
/// only has to fit where the glyphs it explains are drawn.
#[cfg(test)]
pub(super) fn cfg_tier_width() -> u16 {
    TIERS
        .iter()
        .filter(|(_, columns)| columns.contains(&Column::Cfg))
        .map(|(threshold, _)| *threshold)
        .min()
        .expect("a tier draws CFG")
}

/// Width thresholds, widest first. Each entry is the narrowest terminal that
/// still gets that column set.
///
/// The drop order is least-diagnostic first: FOLD is grouping metadata,
/// RESTARTS and PID answer follow-up questions, CPU and MEM explain why a
/// running sheep is behaving badly, and EXIT renders `-` for every running
/// sheep, the common case. `ID NAME STATUS` is the floor.
///
/// CFG has its own drop tier, one tier before SMIT's, keeping `NO_CFG`'s
/// threshold at 116 so a 120-column terminal, the gallery's fixture width,
/// still shows SMIT.
///
/// `MemCeil` and `CpuSpark` drop first of all, ahead of `Cfg`: both restate
/// a number another column already carries, so a terminal too narrow for
/// them still shows the value, just not its shape over time.
const TIERS: &[(u16, &[Column])] = &[
    (146, ALL),
    (134, NO_CEIL),
    (122, NO_SPARK),
    (116, NO_CFG),
    (101, NO_SMIT),
    (89, NO_FOLD),
    (78, NO_EXIT),
    (68, NO_RESTARTS),
    (59, NO_PID),
    (49, NO_MEM),
    (41, NO_CPU),
    (MIN_WIDTH, FLOOR),
];

/// The widest column set that fits `width`.
#[must_use]
pub fn columns_for(width: u16) -> &'static [Column] {
    TIERS
        .iter()
        .find(|(threshold, _)| width >= *threshold)
        .map_or(FLOOR, |(_, columns)| *columns)
}

/// What NAME gets, once the fixed columns and the separators are paid for.
#[must_use]
pub fn name_width(width: u16, columns: &[Column]) -> u16 {
    let fixed: u16 = columns.iter().map(|column| column.width()).sum();
    let gaps = u16::try_from(columns.len().saturating_sub(1)).unwrap_or(0) * 2;
    width
        .saturating_sub(fixed)
        .saturating_sub(gaps)
        .clamp(NAME_MIN, NAME_MAX)
}

/// `text` in exactly `width` display columns: padded on the right, or
/// truncated with a trailing `…`.
///
/// Counted in terminal columns, never bytes or `char`s: bytes over-pad a
/// multi-byte name, and `char`s under-pad a double-width one, shoving every
/// column after it out of line. A truncated name looking whole would be one
/// an operator types into `shep stop`.
///
/// An ANSI escape counts as the literal text a `Span` draws it as, unlike
/// [`crate::output::width::visible_width`], since nothing here writes to a
/// real terminal that would interpret it.
#[must_use]
pub fn fit(text: &str, width: u16) -> String {
    let width = usize::from(width);
    let columns: usize = text.chars().map(char_columns).sum();
    if columns <= width {
        let mut out = String::from(text);
        out.extend(core::iter::repeat_n(' ', width - columns));
        return out;
    }
    if width == 0 {
        return String::new();
    }
    // One column pays for the `…`. A double-width character straddling the
    // boundary is dropped rather than split, and its column is padded below
    // so the cell still measures `width`.
    let budget = width - 1;
    let mut out = String::new();
    let mut used = 0;
    for c in text.chars() {
        let c_width = char_columns(c);
        if used + c_width > budget {
            break;
        }
        out.push(c);
        used += c_width;
    }
    out.push('…');
    out.extend(core::iter::repeat_n(' ', budget - used));
    out
}

/// The header line: every column name, muted.
#[must_use]
pub fn header_line(columns: &[Column], width: u16, style: Style) -> Line<'static> {
    let name = name_width(width, columns);
    let mut text = String::new();
    for (index, column) in columns.iter().enumerate() {
        if index > 0 {
            text.push_str("  ");
        }
        let cell_width = if *column == Column::Name {
            name
        } else {
            column.width()
        };
        text.push_str(&fit(column.header(), cell_width));
    }
    Line::from(Span::styled(text, style))
}

/// One line for a row the table draws: a real sheep, the header above an
/// app's grouped instances, or a [`RowKey::Section`] header.
///
/// `key`'s `Sheep` ids always name a row still in the flock in practice, so
/// the blank fallback below is never drawn; it exists rather than an
/// `expect`, on the same "no honest value" rule this table applies to a
/// missing pid.
///
/// A `Sheep` row under a group header draws as a slot rather than a
/// standalone sheep ([`App::is_grouped`]), so a header reading `web ×3` is
/// not followed by three rows each repeating `web`.
///
/// `selected` paints the row's own ground ([`Palette::ground`]) rather than
/// relying on the gutter marker alone; a section header ignores it, since
/// the cursor never lands on one.
#[must_use]
pub fn key_line(
    app: &App,
    key: &RowKey,
    columns: &[Column],
    width: u16,
    selected: bool,
) -> Line<'static> {
    match key {
        RowKey::Sheep(id) => app.row(*id).map_or_else(
            || Line::from(Span::raw(" ".repeat(usize::from(width)))),
            |row| {
                row_line(
                    app,
                    row,
                    columns,
                    width,
                    app.is_grouped(&row.info.name),
                    selected,
                )
            },
        ),
        RowKey::Group(name) => group_line(app, name, columns, width, selected),
        RowKey::Section(label) => section_line(label, width, app.palette().muted()),
    }
}

/// A [`RowKey::Section`] header: the label, then a rule filling the rest of
/// the table's width.
fn section_line(label: &str, width: u16, style: Style) -> Line<'static> {
    let used = label.chars().count() + 1;
    let rule = "─".repeat(usize::from(width).saturating_sub(used));
    Line::from(Span::styled(format!("{label} {rule}"), style))
}

/// An app's group header row: [`App::group_totals`]'s own rollup, in the
/// same columns [`row_line`] uses for a real sheep. Mirrors
/// `output::rows::FlockRows`'s own group row so the two surfaces never
/// disagree about what an app's instances add up to.
///
/// The selected row's own ground ([`Palette::ground`]) paints these cells
/// too, on top of STATUS/`CpuSpark`/`MemCeil`; the gutter marker
/// ([`gutter`]) is no longer the only tell.
fn group_line(
    app: &App,
    name: &str,
    columns: &[Column],
    width: u16,
    selected: bool,
) -> Line<'static> {
    let palette = app.palette();
    let totals = app.group_totals(name);
    let name_width = self::name_width(width, columns);
    let ground = if selected {
        palette.ground()
    } else {
        Style::default()
    };
    let mut spans: Vec<Span<'static>> = Vec::with_capacity(columns.len() * 2 + 1);
    let mut used: u16 = 0;
    for (index, column) in columns.iter().enumerate() {
        if index > 0 {
            spans.push(Span::styled("  ", ground));
            used += 2;
        }
        let cell_width = if *column == Column::Name {
            name_width
        } else {
            column.width()
        };
        let text = fit(&group_cell(app, name, *column, &totals), cell_width);
        // `palette.status`, not `palette.reported`: a group row is always an
        // app's own instances, never a dog, so it has nothing to be silent
        // about.
        let status = app.group_uniform_status(name);
        let status_style = status.map_or(Style::default(), |status| palette.status(status));
        let style = cell_style(palette, *column, status_style, status, None);
        // A group has no single history or ceiling ([`group_cell`]), so its
        // `MemCeil` text is always empty and there is nothing to fill.
        let tail_style = mem_ceil_tail_style(palette, status, None, style);
        push_row_cell(
            &mut spans,
            *column,
            text,
            style.patch(ground),
            tail_style.patch(ground),
            0,
        );
        used += cell_width;
    }
    pad_ground(&mut spans, used, width, ground);
    Line::from(spans)
}

/// One cell of an app's group header row.
///
/// ID, PID, EXIT and CFG are blank, not `-`: there is no single value for a
/// group row to have "no honest value" about, since a load can park a
/// different set of fields on each slot. `CpuSpark` and `MemCeil` join them
/// for the same reason: a group has no single history and no single
/// ceiling. FOLD and SMIT read the first member's, since both are per-app
/// facts every instance shares.
fn group_cell(app: &App, name: &str, column: Column, totals: &GroupTotals) -> String {
    match column {
        Column::Id
        | Column::Pid
        | Column::Exit
        | Column::Cfg
        | Column::CpuSpark
        | Column::MemCeil => String::new(),
        Column::Name => format!("{name} \u{d7}{}", totals.count),
        Column::Status => app.group_status_text(name),
        Column::Restarts => totals.restarts.to_string(),
        Column::Cpu => totals
            .cpu
            .map_or_else(|| "-".to_string(), |cpu| format!("{cpu:.1}%")),
        Column::Mem => totals.memory.map_or_else(|| "-".to_string(), human_bytes),
        Column::Uptime => totals
            .uptime_ms
            .map_or_else(|| "-".to_string(), human_duration),
        Column::Fold => app
            .group_members(name)
            .first()
            .and_then(|row| row.info.fold.clone())
            .unwrap_or_else(|| "-".to_string()),
        Column::Smit => app
            .group_members(name)
            .first()
            .and_then(|row| row.info.smit.clone())
            .unwrap_or_else(|| "-".to_string()),
    }
}

/// One sheep's line. STATUS, `CpuSpark` and `MemCeil` are the cells that
/// carry colour.
///
/// `selected` paints the row's own ground ([`Palette::ground`]) over every
/// cell, padded to `width` by [`pad_ground`] so the paint reaches the last
/// column rather than stopping where the text does; the gutter marker
/// ([`gutter`]) is no longer the only tell.
///
/// `grouped` says whether a group header sits above this row, which is the
/// only thing that changes NAME, FOLD and SMIT. See [`cell`].
#[must_use]
pub fn row_line(
    app: &App,
    row: &Row,
    columns: &[Column],
    width: u16,
    grouped: bool,
    selected: bool,
) -> Line<'static> {
    let palette = app.palette();
    let name = name_width(width, columns);
    let status_style = palette.reported(row.reported());
    let status = Some(row.info.status);
    let mem_ceil_ratio = mem_ceil_ratio(&row.info);
    let mem_ceil_fill = self::mem_ceil_fill(&row.info);
    let ground = if selected {
        palette.ground()
    } else {
        Style::default()
    };
    let mut spans: Vec<Span<'static>> = Vec::with_capacity(columns.len() * 2 + 1);
    let mut used: u16 = 0;
    for (index, column) in columns.iter().enumerate() {
        if index > 0 {
            spans.push(Span::styled("  ", ground));
            used += 2;
        }
        let cell_width = if *column == Column::Name {
            name
        } else {
            column.width()
        };
        let text = fit(&cell(app, row, *column, grouped), cell_width);
        let style = cell_style(palette, *column, status_style, status, mem_ceil_ratio);
        let tail_style = mem_ceil_tail_style(palette, status, mem_ceil_ratio, style);
        push_row_cell(
            &mut spans,
            *column,
            text,
            style.patch(ground),
            tail_style.patch(ground),
            mem_ceil_fill,
        );
        used += cell_width;
    }
    pad_ground(&mut spans, used, width, ground);
    Line::from(spans)
}

/// One cell's text.
///
/// `-` rather than an empty cell for every unknown: an empty cell in a
/// padded table is indistinguishable from a rendering bug, and `0.0%` would
/// claim a measurement the shepherd never made.
///
/// `grouped` changes three cells, matching `output::rows::slot_row`. NAME
/// becomes `↳ :2`, teaching the `web:2` selector by sitting under the name
/// the header already printed; FOLD and SMIT go blank rather than `-`,
/// since the group row above carries both.
fn cell(app: &App, row: &Row, column: Column, grouped: bool) -> String {
    let info = &row.info;
    match column {
        Column::Id => info.id.to_string(),
        Column::Name if grouped => info
            .instance
            .map_or_else(String::new, |slot| format!(" \u{21b3} :{slot}")),
        Column::Name => info.name.clone(),
        // `Row::reported`, not `info.status.to_string()`: a dog that has
        // never handshook must not read `online` here any more than it does
        // in `shep flock`'s own table.
        Column::Status => row.reported().word(),
        Column::Pid => info
            .pid
            .map_or_else(|| "-".to_string(), |pid| pid.to_string()),
        Column::Restarts => info.restarts.to_string(),
        // `crate::output::exit_cell`, not a second implementation of the
        // code/signal split.
        Column::Exit => exit_cell(info.pid, info.last_exit),
        // `crate::output::cfg_cell`, not a second implementation of the
        // pending-over-overridden precedence.
        Column::Cfg => cfg_cell(info.pending.as_deref(), info.overridden.as_deref()),
        Column::CpuSpark => cpu_spark_cell(app, info),
        Column::Cpu => info
            .cpu_percent
            .map_or_else(|| "-".to_string(), |cpu| format!("{cpu:.1}%")),
        Column::MemCeil => mem_ceil_cell(info),
        Column::Mem => info
            .memory_bytes
            .map_or_else(|| "-".to_string(), human_bytes),
        // The live value, not the snapshot's: `App::uptime_ms` advances a
        // running sheep between polls and stops once the link is lost.
        Column::Uptime => app
            .uptime_ms(info.id)
            .map_or_else(|| "-".to_string(), human_duration),
        Column::Fold | Column::Smit if grouped => String::new(),
        Column::Fold => info.fold.clone().unwrap_or_else(|| "-".to_string()),
        Column::Smit => info.smit.clone().unwrap_or_else(|| "-".to_string()),
    }
}

/// The `CPU 20s` cell: [`App::cpu_history`], rendered into ten cells by
/// [`cell::sparkline`].
fn cpu_spark_cell(app: &App, info: &ProcessInfo) -> String {
    cell::sparkline(app.cpu_history(info.id), 10, app.cpu_ceiling())
}

/// The `MEM/CEIL` cell: [`ProcessInfo::memory_bytes`] against
/// [`ProcessInfo::max_memory`], rendered into ten cells by [`cell::gauge`].
/// A missing reading counts as `0`, matching [`cell::gauge`]'s own
/// no-ceiling case: an idle-looking bar rather than a guessed denominator.
fn mem_ceil_cell(info: &ProcessInfo) -> String {
    cell::gauge(info.memory_bytes.unwrap_or(0), info.max_memory, 10)
}

/// Where [`mem_ceil_cell`]'s ten characters split into filled and tail, so
/// [`push_row_cell`] can style the two runs separately without re-deriving
/// the fill from `info` a second time.
fn mem_ceil_fill(info: &ProcessInfo) -> usize {
    cell::gauge_fill(info.memory_bytes.unwrap_or(0), info.max_memory, 10)
}

/// `memory_bytes` over `max_memory`, or `None` when either is missing or the
/// ceiling is zero. Feeds [`cell_style`]'s butter threshold; the bar itself
/// is drawn by [`mem_ceil_cell`], which never divides.
fn mem_ceil_ratio(info: &ProcessInfo) -> Option<f64> {
    let value = info.memory_bytes?;
    let ceiling = info.max_memory?;
    if ceiling == 0 {
        return None;
    }
    Some(value as f64 / ceiling as f64)
}

/// Whether `MemCeil` has anything to measure: a live reading against a real
/// ceiling, on a sheep that is actually running. A stopped sheep's last
/// known reading and a sheep with no ceiling at all share the same "nothing
/// to show" rendering (decision 7), so both read `false` here.
fn mem_ceil_measuring(status: Option<ProcStatus>, ratio: Option<f64>) -> bool {
    status == Some(ProcStatus::Online) && ratio.is_some()
}

/// The per-column style [`row_line`] and [`group_line`] both apply, so the
/// STATUS rule they already shared does not get a second, drifting copy now
/// that `CpuSpark` and `MemCeil` need one too.
///
/// `status_style` is resolved by the caller, since a sheep and a group
/// header read status through different paths. `status` and `mem_ceil_ratio`
/// are `None` for a group row: it has no single status or ceiling to be
/// near. This is the style [`push_row_cell`] gives `MemCeil`'s *filled* run;
/// see [`mem_ceil_tail_style`] for its unfilled tail.
fn cell_style(
    palette: Palette,
    column: Column,
    status_style: Style,
    status: Option<ProcStatus>,
    mem_ceil_ratio: Option<f64>,
) -> Style {
    match column {
        Column::Status => status_style,
        // The role a healthy sheep's own STATUS cell wears.
        Column::CpuSpark => palette.status(ProcStatus::Online),
        Column::MemCeil if !mem_ceil_measuring(status, mem_ceil_ratio) => palette.muted(),
        Column::MemCeil => {
            if mem_ceil_ratio.is_some_and(|ratio| ratio >= 0.9) {
                palette.attention()
            } else {
                palette.sky()
            }
        }
        _ => Style::default(),
    }
}

/// `MemCeil`'s unfilled tail: `gauge_rest` against a real ceiling on a
/// running sheep, the same muted role as `fill_style` everywhere else so the
/// bar reads as one flat colour rather than two competing ones.
fn mem_ceil_tail_style(
    palette: Palette,
    status: Option<ProcStatus>,
    mem_ceil_ratio: Option<f64>,
    fill_style: Style,
) -> Style {
    if mem_ceil_measuring(status, mem_ceil_ratio) {
        palette.gauge_rest()
    } else {
        fill_style
    }
}

/// Pushes one column's text as one span, except `MemCeil`, which splits at
/// `fill` into a filled run styled `style` and an unfilled tail styled
/// `tail_style` (decision 7's rule that the tail must not compete with the
/// fill). `fill` is clamped to the text's own length, so a group row's
/// always-empty `MemCeil` cell and a stopped sheep's cell both split
/// harmlessly.
fn push_row_cell(
    spans: &mut Vec<Span<'static>>,
    column: Column,
    text: String,
    style: Style,
    tail_style: Style,
    fill: usize,
) {
    if column == Column::MemCeil {
        let fill = fill.min(text.chars().count());
        let mut chars = text.chars();
        let filled: String = chars.by_ref().take(fill).collect();
        let rest: String = chars.collect();
        spans.push(Span::styled(filled, style));
        spans.push(Span::styled(rest, tail_style));
    } else {
        spans.push(Span::styled(text, style));
    }
}

/// Fills the gap between `used` and `width` with a trailing span in
/// `ground`, so a painted row's background reaches every column of the
/// table rather than stopping where its last cell's text does.
///
/// Ratatui only paints a `Span`'s background under the cells its own text
/// occupies. `NAME` is the only column [`name_width`] can leave short of
/// the table's full width (it floors at [`NAME_MIN`] on a narrow
/// terminal), so without this the selected row's ground would end mid-row
/// on exactly the terminals narrow enough to need the signal most. A no-op
/// when `used >= width` or `ground` carries no colour.
fn pad_ground(spans: &mut Vec<Span<'static>>, used: u16, width: u16, ground: Style) {
    let short = width.saturating_sub(used);
    if short > 0 {
        spans.push(Span::styled(" ".repeat(usize::from(short)), ground));
    }
}

/// Which slice of the flock is on screen, given where the cursor is.
///
/// Derived every frame from [`super::super::app::App::selected_index`] rather
/// than stored beside it: a stored offset and a stored cursor can disagree,
/// and this way they cannot. The selection is centred where the flock is long
/// enough to allow it and pinned at both ends where it is not, so the last row
/// of the flock is always the last row of the pane.
#[must_use]
pub fn scroll_offset(selected: usize, viewport: usize, total: usize) -> usize {
    if viewport == 0 || total <= viewport {
        return 0;
    }
    let last = total - viewport;
    selected.saturating_sub(viewport / 2).min(last)
}

#[cfg(test)]
mod tests {
    use super::super::fixtures;
    use super::*;
    use std::ffi::OsStr;

    #[test]
    fn the_painted_gutter_is_one_column_and_holds_no_glyph() {
        let deep = Palette::detect(None, None, Some(OsStr::new("truecolor")));
        let (text, style) = gutter(true, deep);
        assert_eq!(
            text, " ",
            "a space, not a block: a block is Ambiguous width"
        );
        assert_eq!(
            crate::output::width::char_columns(text.chars().next().unwrap()),
            1
        );
        assert!(style.bg.is_some());
    }

    #[test]
    fn without_colour_the_gutter_falls_back_to_the_ascii_marker() {
        let off = Palette::detect(Some(OsStr::new("1")), None, None);
        let (text, style) = gutter(true, off);
        assert_eq!(text, ">");
        assert_eq!(style, Style::default());
        assert_eq!(gutter(false, off).0, " ");
    }

    /// FOLD goes first (grouping metadata), then EXIT (silent for a running
    /// sheep, the common case), then RESTARTS and PID, then CPU and MEM (the
    /// last to explain why a running sheep misbehaves). ID/NAME/STATUS is
    /// the floor.
    #[test]
    fn columns_drop_in_a_fixed_order_as_the_terminal_narrows() {
        assert_eq!(columns_for(300).len(), 14);
        assert_eq!(columns_for(122).len(), 12);
        // CFG is the first column gone, ahead of even SMIT. See `TIERS`'s
        // own doc for the reasoning.
        assert!(!columns_for(121).contains(&Column::Cfg));
        assert!(columns_for(121).contains(&Column::Smit));
        assert_eq!(columns_for(116).len(), 11);
        assert!(!columns_for(115).contains(&Column::Smit));
        assert!(columns_for(115).contains(&Column::Fold));
        assert_eq!(columns_for(101).len(), 10);
        assert!(!columns_for(100).contains(&Column::Fold));
        assert!(columns_for(100).contains(&Column::Exit));
        assert!(!columns_for(88).contains(&Column::Exit));
        assert!(columns_for(88).contains(&Column::Restarts));
        assert!(!columns_for(77).contains(&Column::Restarts));
        assert!(!columns_for(67).contains(&Column::Pid));
        assert!(!columns_for(58).contains(&Column::Mem));
        assert!(!columns_for(48).contains(&Column::Cpu));
        assert_eq!(columns_for(31), &[Column::Id, Column::Name, Column::Status]);
        // Every tier keeps the three that are the pane.
        for width in [31u16, 40, 48, 58, 67, 77, 88, 100, 300] {
            let cols = columns_for(width);
            for required in [Column::Id, Column::Name, Column::Status] {
                assert!(
                    cols.contains(&required),
                    "width {width} dropped {required:?}"
                );
            }
        }
    }

    /// The gallery's own fixtures render at 120 columns, so this pins the
    /// one width a future column's drop-order choice must not narrow past.
    #[test]
    fn smit_survives_the_gallerys_own_wide_fixtures() {
        assert!(columns_for(120).contains(&Column::Smit));
    }

    #[test]
    fn the_two_new_rungs_restore_todays_table_before_shedding_anything_old() {
        assert_eq!(columns_for(146), ALL);
        assert!(!columns_for(134).contains(&Column::MemCeil));
        assert!(columns_for(134).contains(&Column::CpuSpark));
        assert!(!columns_for(122).contains(&Column::CpuSpark));
        assert_eq!(
            columns_for(122),
            NO_SPARK,
            "122 is today's full set, unchanged"
        );
    }

    /// Enforces `Column::header`'s claim of one vocabulary across both
    /// surfaces, rather than leaving it aspirational. Replaces
    /// `the_full_column_set_matches_flock_rows_headers_exactly`, which
    /// compared `ALL` to `FlockRows::headers()` directly and broke the
    /// moment `ALL` grew two headers `shep flock` cannot draw.
    #[test]
    fn every_shared_header_still_matches_flock_rows_exactly() {
        use crate::output::Render;

        let shared: Vec<&str> = ALL
            .iter()
            .map(|column| column.header())
            .filter(|header| crate::output::FlockRows::headers().contains(header))
            .collect();
        assert_eq!(shared, crate::output::FlockRows::headers());
    }

    #[test]
    fn the_only_headers_lookout_adds_are_the_two_shep_flock_cannot_draw() {
        use crate::output::Render;

        let extra: Vec<&str> = ALL
            .iter()
            .map(|column| column.header())
            .filter(|header| !crate::output::FlockRows::headers().contains(header))
            .collect();
        assert_eq!(extra, vec!["CPU 20s", "MEM/CEIL"]);
    }

    /// Not a "-": the column is a bar, and an all-tail bar reads as
    /// "no ceiling set" without a second rendering to learn.
    #[test]
    fn a_running_sheep_with_no_ceiling_draws_an_empty_gauge() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let info = ProcessInfo::builder(1, "web", ProcStatus::Online)
            .memory_bytes(Some(48 * 1024 * 1024))
            .build();
        assert_eq!(mem_ceil_cell(&info), "â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘");
    }

    #[test]
    fn a_sheep_at_its_ceiling_fills_the_gauge() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let info = ProcessInfo::builder(1, "hungry", ProcStatus::Online)
            .memory_bytes(Some(52 * 1024 * 1024))
            .max_memory(Some(52 * 1024 * 1024))
            .build();
        assert_eq!(mem_ceil_cell(&info), "██████████");
    }

    /// Decision 7: the unfilled tail must not compete with the fill, so the
    /// two runs need distinct spans and distinct roles, not one style over
    /// the whole ten-cell text.
    #[test]
    fn the_gauges_unfilled_tail_carries_gauge_rest_not_the_fill_role() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let palette = fixtures::coloured();
        assert_ne!(
            palette.sky().fg,
            palette.gauge_rest().fg,
            "the two roles must actually differ for this test to mean anything"
        );
        let info = ProcessInfo::builder(1, "hungry", ProcStatus::Online)
            .memory_bytes(Some(26 * 1024 * 1024))
            .max_memory(Some(52 * 1024 * 1024))
            .build();
        let app = fixtures::app_with(vec![info], palette);
        let row = app.row(1).unwrap();

        let line = row_line(&app, row, ALL, 200, false, false);
        let fill: Vec<&str> = line
            .spans
            .iter()
            .filter(|span| span.style.fg == palette.sky().fg && !span.content.is_empty())
            .map(|span| span.content.as_ref())
            .collect();
        let tail: Vec<&str> = line
            .spans
            .iter()
            .filter(|span| span.style.fg == palette.gauge_rest().fg && !span.content.is_empty())
            .map(|span| span.content.as_ref())
            .collect();
        assert_eq!(fill, vec!["█████"], "got fill spans {fill:?}");
        assert_eq!(tail, vec!["â–‘â–‘â–‘â–‘â–‘"], "got tail spans {tail:?}");
    }

    /// Decision 7: a sheep with nothing to measure against reads as muted,
    /// not as though `sky` had something to report.
    #[test]
    fn a_running_sheep_with_no_ceiling_draws_muted_not_sky() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let palette = fixtures::coloured();
        let info = ProcessInfo::builder(1, "web", ProcStatus::Online)
            .memory_bytes(Some(48 * 1024 * 1024))
            .build();
        let app = fixtures::app_with(vec![info], palette);
        let row = app.row(1).unwrap();

        let line = row_line(&app, row, ALL, 200, false, false);
        let mem_ceil_text: Vec<&str> = line
            .spans
            .iter()
            .filter(|span| span.content.as_ref() == "â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘")
            .map(|span| span.content.as_ref())
            .collect();
        assert_eq!(mem_ceil_text, vec!["â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘"]);
        assert!(
            line.spans
                .iter()
                .any(|span| span.content.as_ref() == "â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘"
                    && span.style.fg == palette.muted().fg),
            "expected the all-tail bar in muted, got {:?}",
            line.spans
                .iter()
                .map(|s| (s.content.as_ref(), s.style.fg))
                .collect::<Vec<_>>()
        );
        assert!(
            !line
                .spans
                .iter()
                .any(|span| span.content.as_ref() == "â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘â–‘"
                    && span.style.fg == palette.sky().fg),
            "must not read sky, which claims a real measurement"
        );
    }

    /// Decision 7's other muted case: a sheep that is not running, even one
    /// with a ceiling, since a stopped process has nothing live to gauge.
    #[test]
    fn a_stopped_sheeps_gauge_draws_muted() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let palette = fixtures::coloured();
        let info = ProcessInfo::builder(1, "stopped", ProcStatus::Stopped)
            .memory_bytes(Some(26 * 1024 * 1024))
            .max_memory(Some(52 * 1024 * 1024))
            .build();
        let app = fixtures::app_with(vec![info], palette);
        let row = app.row(1).unwrap();

        let line = row_line(&app, row, ALL, 200, false, false);
        assert!(
            !line
                .spans
                .iter()
                .any(|span| span.style.fg == palette.sky().fg),
            "a stopped sheep has nothing live to gauge, so no span reads sky"
        );
    }

    /// `cfg(unix)`: the fixture carries a signalled exit, which
    /// `output::rows::signal_label` resolves against the running platform's
    /// own signal table. A Windows `ExitOutcome` never carries a signal at
    /// all, so this arm is only ever reached by a synthetic fixture.
    #[cfg(unix)]
    #[test]
    fn the_exit_cell_reuses_the_same_rendering_flock_rows_uses() {
        use shep_core::protocol::{ExitInfo, ProcessInfo};
        use shep_core::status::ProcStatus;

        let crashed = ProcessInfo::builder(1, "crashed", ProcStatus::Errored)
            .last_exit(Some(ExitInfo {
                code: Some(1),
                signal: None,
            }))
            .build();
        let killed = ProcessInfo::builder(2, "killed", ProcStatus::Stopped)
            .last_exit(Some(ExitInfo {
                code: None,
                signal: Some(9),
            }))
            .build();
        let running = ProcessInfo::builder(3, "running", ProcStatus::Online)
            .pid(Some(4_242))
            .last_exit(Some(ExitInfo {
                code: Some(1),
                signal: None,
            }))
            .build();

        let app = fixtures::app_with(vec![crashed, killed, running], fixtures::plain());
        let rows = app.rows();
        let cell_for = |id: u32| {
            let row = rows.iter().find(|row| row.info.id == id).unwrap();
            cell(&app, row, Column::Exit, false)
        };

        assert_eq!(cell_for(1), "1");
        assert_eq!(cell_for(2), "SIGKILL");
        assert_eq!(
            cell_for(3),
            "-",
            "a running sheep has nothing for EXIT to say"
        );
    }

    #[test]
    fn every_tier_fits_the_width_it_claims() {
        for width in MIN_WIDTH..=200 {
            let cols = columns_for(width);
            let fixed: u16 = cols.iter().map(|c| c.width()).sum();
            let gaps = u16::try_from(cols.len() - 1).unwrap() * 2;
            assert!(
                fixed + gaps + NAME_MIN <= width,
                "width {width} chose {} columns needing {}",
                cols.len(),
                fixed + gaps + NAME_MIN
            );
        }
    }

    #[test]
    fn a_name_too_long_for_its_column_ends_in_an_ellipsis() {
        let cut = fit("payments-reconciliation-worker", 12);
        assert_eq!(cut.chars().count(), 12);
        assert!(cut.ends_with('…'));
        assert!(cut.starts_with("payments"));
        assert_eq!(fit("web", 12), "web         ");
    }

    /// Asserts on content, not length: `fit(..).chars().count() == width`
    /// alone is `width` either way, blind to a byte-vs-char mutation. The
    /// pad branch under-pads a multi-byte name; the truncate branch cuts a
    /// string that already fits.
    #[test]
    fn fit_counts_columns_not_bytes_when_it_pads_and_when_it_truncates() {
        // Pad branch. `日本語` is 9 bytes and 6 columns: measured correctly
        // it fills a 6-wide cell, byte-counted it falls into the truncate
        // branch.
        assert_eq!(fit("日本語", 6), "日本語");
        // Exactly fits: 7 columns, 11 bytes. A byte count would cut it to
        // `ünïcöd…`.
        assert_eq!(fit("ünïcödé", 7), "ünïcödé");
    }

    /// A `char` count gives `日本語` three and lets it into a 3-wide cell it
    /// draws six columns in, and gives `日本語アプリ` a five-`char` prefix
    /// of `日本語ア…` that draws nine.
    ///
    /// Asserts on content and on measured columns: `chars().count()` alone
    /// is blind to the mutation, and here so is `len()`.
    #[test]
    fn a_double_width_name_is_cut_to_the_columns_it_draws_in() {
        // Truncate branch. Budget is 4 columns plus the `…`: two characters
        // fit, the third would draw past the cell.
        assert_eq!(fit("日本語アプリ", 5), "日本…");
        assert_eq!(columns_of(&fit("日本語アプリ", 5)), 5);
        // A `char` count would call this a pad (3 chars into 3 columns) and
        // emit `日本語`, six columns wide, with no `…` to say it was cut.
        assert_eq!(fit("日本語", 3), "日…");
        // The odd-width case the padding exists for: `æ—¥` fits the 2-column
        // budget, `本` does not, and half a character is not drawable, so
        // the leftover column is a space rather than a short cell.
        assert_eq!(fit("日本語", 4), "日… ");
        assert_eq!(columns_of(&fit("日本語", 4)), 4);
        // Nothing but the marker fits, at either width.
        assert_eq!(fit("日本語", 1), "…");
        assert_eq!(fit("日本語", 2), "… ");
    }

    /// Every caller concatenates cells with two-space separators and no
    /// caller re-measures, so one short cell shifts every column after it
    /// on that row, invisibly in a single cell's own test.
    #[test]
    fn every_cell_measures_exactly_the_width_it_was_given() {
        let names = [
            "web",
            "payments-reconciliation-worker",
            "日本語アプリ",
            "café",
            "cafe\u{301}",
            "羊",
            "",
        ];
        for name in names {
            for width in 0..=12u16 {
                let cell = fit(name, width);
                assert_eq!(
                    columns_of(&cell),
                    usize::from(width),
                    "fit({name:?}, {width}) == {cell:?}"
                );
            }
        }
    }

    /// An ANSI escape is text here, not styling. Measuring it as zero, which
    /// [`crate::output::width::visible_width`] does on its own path, would
    /// let a hostile log line claim more columns than the cell it was cut
    /// to fit.
    #[test]
    fn an_escape_sequence_is_measured_as_the_text_it_will_be_drawn_as() {
        let styled = "\u{1b}[32mup";
        // ESC is zero-width; `[32mup` is six columns.
        assert_eq!(columns_of(styled), 6);
        assert_eq!(columns_of(&fit(styled, 4)), 4);
        assert!(fit(styled, 4).ends_with('…'));
    }

    /// The columns a rendered cell actually draws in, by the same rule
    /// [`fit`] pads by. Not `chars().count()`: that is the measurement
    /// under test.
    fn columns_of(s: &str) -> usize {
        s.chars().map(char_columns).sum()
    }

    /// Colour and a `REVERSED` modifier are both rejected: every signal on
    /// this screen has to survive `NO_COLOR` and a 16-colour terminal. `>`
    /// rather than `â–¸`, since `â–¸` is East-Asian Ambiguous width and a
    /// terminal rendering it double-wide shifts every column of that row.
    #[test]
    fn the_marker_is_one_ascii_column_wide_in_both_states() {
        // The two literals are the test: `">"` is one ASCII char by
        // inspection, so a separate length/`is_ascii()` check is redundant.
        assert_eq!(
            mark(true),
            ">",
            "not `â–¸`: East-Asian Ambiguous width would shift the row"
        );
        assert_eq!(mark(false), " ");
    }

    #[test]
    fn the_offset_keeps_the_selection_visible_and_centred_where_it_can() {
        // Everything fits: no scrolling, wherever the cursor is.
        assert_eq!(scroll_offset(0, 10, 6), 0);
        assert_eq!(scroll_offset(5, 10, 6), 0);
        // Taller than the viewport: centred in the middle, pinned at the ends.
        assert_eq!(scroll_offset(0, 5, 20), 0);
        assert_eq!(scroll_offset(2, 5, 20), 0);
        assert_eq!(scroll_offset(3, 5, 20), 1);
        assert_eq!(scroll_offset(10, 5, 20), 8);
        assert_eq!(scroll_offset(19, 5, 20), 15, "the last page, not past it");
        assert_eq!(scroll_offset(usize::MAX, 5, 20), 15);
        // Degenerate: a viewport of zero rows scrolls nowhere.
        assert_eq!(scroll_offset(3, 0, 20), 0);
        // And the selection is always inside the window it returns.
        for total in [1usize, 2, 7, 40, 200] {
            for viewport in [1usize, 3, 8, 25] {
                for selected in 0..total {
                    let offset = scroll_offset(selected, viewport, total);
                    assert!(
                        selected >= offset && selected < offset + viewport,
                        "selected {selected} fell outside [{offset}, {}) for total {total}",
                        offset + viewport
                    );
                }
            }
        }
    }

    /// `web x3` in NAME, memory summed across instances, ID/PID/EXIT blank,
    /// and UPTIME the minimum rather than any one instance's own reading.
    /// Asserted on the rendered [`Line`], not on `App::group_totals`
    /// directly, so a change in either the arithmetic or the rendering has
    /// to redden this.
    #[test]
    fn a_group_rows_cells_show_the_apps_rollup() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let app = fixtures::app_with(
            vec![
                ProcessInfo::builder(1, "web", ProcStatus::Online)
                    .instance(Some(0))
                    .memory_bytes(Some(100 << 20))
                    .uptime_ms(120_000)
                    .build(),
                ProcessInfo::builder(2, "web", ProcStatus::Online)
                    .instance(Some(1))
                    .memory_bytes(Some(150 << 20))
                    .uptime_ms(30_000)
                    .build(),
                ProcessInfo::builder(3, "web", ProcStatus::Online)
                    .instance(Some(2))
                    .memory_bytes(Some(50 << 20))
                    .uptime_ms(600_000)
                    .build(),
            ],
            fixtures::plain(),
        );

        let line = key_line(&app, &RowKey::Group("web".to_string()), ALL, 200, false);
        let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();

        // The exact row, column by column: a substring check on a run of
        // blank cells can pass by accident on neighbouring padding.
        let name = name_width(200, ALL);
        let expected = [
            fit("", Column::Id.width()),           // ID: blank, no single id
            fit("web \u{d7}3", name),              // NAME: app x instance count
            fit("online", Column::Status.width()), // STATUS: every instance agrees
            fit("", Column::Pid.width()),          // PID: blank, no single pid
            fit("0", Column::Restarts.width()),    // RESTARTS: summed, all zero
            fit("", Column::Exit.width()),         // EXIT: blank, no single exit
            fit("", Column::Cfg.width()),          // CFG: blank, per-instance fact
            fit("", Column::CpuSpark.width()),     // CPU 20s: blank, no single history
            fit("-", Column::Cpu.width()),         // CPU: no reading on any instance
            fit("", Column::MemCeil.width()),      // MEM/CEIL: blank, no single ceiling
            // 100 + 150 + 50 = 300 MiB, summed rather than averaged.
            fit("300.0M", Column::Mem.width()),
            // The MINIMUM across the three instances (30s), not the first
            // one's (120s) or the last one's (600s).
            fit("30s", Column::Uptime.width()),
            fit("-", Column::Fold.width()),
            fit("-", Column::Smit.width()),
        ]
        .join("  ");

        // Trailing pad compared separately: since NAME gained a ceiling
        // ([`NAME_MAX`]), the columns no longer fill a wide terminal and the
        // row is padded out to it. Both facts are worth pinning, but the
        // cells are the ones this test is about.
        assert_eq!(rendered.trim_end(), expected.trim_end(), "got {rendered:?}");
        assert_eq!(
            crate::output::width::visible_width(&rendered),
            200,
            "the row is padded to the table's width, so its ground reaches the edge"
        );
    }

    /// A slot row drawn like a standalone sheep repeats FOLD and SMIT down
    /// every row and shows no slot number, unlike `shep flock`'s own `↳ :1`.
    ///
    /// Asserted on the rendered line rather than on `cell`, since the
    /// defect was in which caller `key_line` picked.
    #[test]
    fn a_slot_row_under_a_group_header_renders_as_a_slot() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let member = |id: u32, slot: u32| {
            ProcessInfo::builder(id, "web", ProcStatus::Online)
                .instance(Some(slot))
                .pid(Some(4_000 + id))
                .fold(Some("edge".to_string()))
                .smit(Some("web".to_string()))
                .uptime_ms(30_000)
                .build()
        };
        let app = fixtures::app_with(vec![member(1, 0), member(2, 1)], fixtures::plain());

        let line = key_line(&app, &RowKey::Sheep(2), ALL, 200, false);
        let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();

        let name = name_width(200, ALL);
        let expected = [
            fit("2", Column::Id.width()),
            // NAME: the slot alone, indented under the name the header
            // above already printed.
            fit(" \u{21b3} :1", name),
            fit("online", Column::Status.width()),
            fit("4002", Column::Pid.width()),
            fit("0", Column::Restarts.width()),
            fit("-", Column::Exit.width()),
            fit("-", Column::Cfg.width()),
            // CPU 20s: one sample recorded by `app_with`'s own snapshot,
            // 0.0 since neither member reports a reading.
            fit("         \u{2581}", Column::CpuSpark.width()),
            fit("-", Column::Cpu.width()),
            // MEM/CEIL: an all-tail bar, no memory reading and no ceiling.
            fit(
                "\u{2591}\u{2591}\u{2591}\u{2591}\u{2591}\u{2591}\u{2591}\u{2591}\u{2591}\u{2591}",
                Column::MemCeil.width(),
            ),
            fit("-", Column::Mem.width()),
            fit("30s", Column::Uptime.width()),
            // FOLD and SMIT blank, not `-`: the group row carries both.
            fit("", Column::Fold.width()),
            fit("", Column::Smit.width()),
        ]
        .join("  ");

        // Same as the group-row test: NAME has a ceiling now, so a wide

        // terminal leaves the row padded past its last cell.

        assert_eq!(rendered.trim_end(), expected.trim_end(), "got {rendered:?}");
    }

    /// The guard on the test above: an app with one instance never gets a
    /// header, so `is_grouped` keeps it drawing as it always did.
    #[test]
    fn an_ungrouped_sheep_still_shows_its_own_name_and_fold() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let app = fixtures::app_with(
            vec![
                ProcessInfo::builder(7, "solo", ProcStatus::Online)
                    .instance(Some(0))
                    .fold(Some("edge".to_string()))
                    .build(),
            ],
            fixtures::plain(),
        );

        let line = key_line(&app, &RowKey::Sheep(7), ALL, 200, false);
        let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();

        assert!(rendered.contains("solo"), "got {rendered:?}");
        assert!(rendered.contains("edge"), "got {rendered:?}");
        assert!(!rendered.contains('\u{21b3}'), "got {rendered:?}");
    }

    /// The process is alive, so nothing but `handshook` can catch this.
    #[test]
    fn a_silent_dog_reads_silent_not_online() {
        use shep_core::protocol::{DogSource, ProcessInfo};
        use shep_core::status::ProcStatus;

        let dog = ProcessInfo::builder(9, "log-rotate", ProcStatus::Online)
            .pid(Some(4_242))
            .dog(Some(DogSource::Adopted {
                path: "/usr/local/bin/shep-log-rotate".to_string(),
            }))
            .handshook(Some(false))
            .build();
        let app = fixtures::app_with(vec![dog], fixtures::plain());
        let row = app.row(9).unwrap();

        let line = row_line(&app, row, ALL, 200, false, false);
        let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            rendered.contains("silent"),
            "expected silent, got {rendered:?}"
        );
        assert!(
            !rendered.contains("online"),
            "must not say online: {rendered:?}"
        );
    }

    /// The guard on [`a_silent_dog_reads_silent_not_online`] above.
    #[test]
    fn a_dog_that_has_handshook_still_reads_online() {
        use shep_core::protocol::{DogSource, ProcessInfo};
        use shep_core::status::ProcStatus;

        let dog = ProcessInfo::builder(9, "log-rotate", ProcStatus::Online)
            .pid(Some(4_242))
            .dog(Some(DogSource::Adopted {
                path: "/usr/local/bin/shep-log-rotate".to_string(),
            }))
            .handshook(Some(true))
            .build();
        let app = fixtures::app_with(vec![dog], fixtures::plain());
        let row = app.row(9).unwrap();

        let line = row_line(&app, row, ALL, 200, false, false);
        let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(rendered.contains("online"), "got {rendered:?}");
        assert!(!rendered.contains("silent"), "got {rendered:?}");
    }

    /// A sheep's `handshook` is always `None`; it must never get caught by
    /// the same silent rule a dog does.
    #[test]
    fn a_sheep_still_reads_online_and_has_no_handshake() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let sheep = ProcessInfo::builder(1, "web", ProcStatus::Online)
            .pid(Some(4_000))
            .build();
        assert_eq!(sheep.handshook, None, "a sheep is never sent one");
        let app = fixtures::app_with(vec![sheep], fixtures::plain());
        let row = app.row(1).unwrap();

        let line = row_line(&app, row, ALL, 200, false, false);
        let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(rendered.contains("online"), "got {rendered:?}");
        assert!(!rendered.contains("silent"), "got {rendered:?}");
    }

    /// The daemon never sends a sheep `handshook: Some(false)`; a sheep has
    /// no version relationship with the shepherd to fail. Exercises the
    /// `dog.is_none()` guard in `Row::reported` with an input no other test
    /// drives.
    #[test]
    fn a_sheep_never_reads_as_silent() {
        use shep_core::protocol::ProcessInfo;
        use shep_core::status::ProcStatus;

        let mut impossible = ProcessInfo::builder(1, "web", ProcStatus::Online)
            .pid(Some(4_000))
            .build();
        impossible.handshook = Some(false);
        let app = fixtures::app_with(vec![impossible], fixtures::plain());
        let row = app.row(1).unwrap();

        let line = row_line(&app, row, ALL, 200, false, false);
        let rendered: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(
            rendered.contains("online"),
            "the sheep table has no dogs in it, and no silence rule either: {rendered:?}"
        );
        assert!(!rendered.contains("silent"), "got {rendered:?}");
    }
}