shep 0.8.0

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
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
//! Renders a `Buffer` to plain text or ANSI, and holds the scene list the
//! pinned snapshots and the gallery share.
//!
//! `docs/lookout/frames.txt` and `docs/lookout/frames.ansi` are generated
//! from this module's output, doubling as a rendered layout reference.
//!
//! Gated at the `mod` declaration with `#[cfg(test)]` rather than
//! `pub mod`: `lib.rs` exposes only three entry points, so an ordinary
//! `pub mod` here is unreachable from outside the crate and fails
//! `dead_code`.

use std::fmt::Write as _;
use std::path::PathBuf;
use std::time::{Duration, Instant};

use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};

use shep_client::RequestError;
use shep_core::config::AppConfig;
use shep_core::protocol::{
    DogSource, ExitInfo, Lamb, ProcessInfo, Response, RpcError, RpcErrorCode, SheepConfigView,
};
use shep_core::status::ProcStatus;

use super::app::{
    ActionVerb, App, Control, KeyPress, Msg, RevealedValue, RowKey, Sent, SettingsRow,
};
use super::secrets::{SecretRow, SecretsModel, Source};
use super::source::HostSample;
use super::tail::{Stream, Tail, TailLine};
use super::theme::Palette;
use super::view::fixtures::select_field;
use super::view::{body_rows, draw};
use crate::commands::settings::{
    DogView, ScalarView, SettingField, SettingsSnapshot, load_settings,
};
use crate::commands::shep_toml::ShepToml;
use crate::secret_readers::Reader;
use crate::style::{StyleLevel, StyleSource};

/// One rendered buffer as plain text: one line per row, trailing spaces
/// kept, no escapes.
///
/// Trailing spaces stay because a frame is a fixed-size grid: trimming
/// would make a right-aligned cell look like it moved.
///
/// Cells are read by their rendered symbol, not by byte length, so a
/// multi-byte cell round-trips exactly as drawn. Indexed with
/// `Buffer[(x, y)]`, not the deprecated `Buffer::get`.
#[must_use]
pub fn render_text(buffer: &Buffer) -> String {
    let area = buffer.area;
    (0..area.height)
        .map(|row| {
            (0..area.width)
                .map(|col| buffer[(area.x + col, area.y + row)].symbol())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The same buffer with SGR escapes, for reading through `less -R`.
///
/// Every line ends with a reset before its newline, so an unreset colour
/// does not bleed into the rest of the file. Reset is unconditional per
/// cell change, not incremental: a cell that sets nothing still clears
/// whatever the previous cell set, so a band or a painted ground cannot
/// bleed along the rest of the row.
#[must_use]
pub fn render_ansi(buffer: &Buffer) -> String {
    let area = buffer.area;
    let mut out = String::new();
    for row in 0..area.height {
        let mut current = String::new();
        for col in 0..area.width {
            let cell = &buffer[(area.x + col, area.y + row)];
            let wanted = sgr(cell.fg, cell.bg, cell.modifier);
            if wanted != current {
                out.push_str("\u{1b}[0m");
                out.push_str(&wanted);
                current = wanted;
            }
            out.push_str(cell.symbol());
        }
        out.push_str("\u{1b}[0m");
        out.push('\n');
    }
    out
}

/// The SGR sequence for one cell's foreground, background and reverse
/// video.
///
/// Foreground, background and `REVERSED` are the only styles any scene
/// uses (`no_scene_uses_a_modifier_the_ansi_renderer_cannot_render` still
/// guards against a scene reaching for one this function does not draw).
/// This is what makes the selected row's painted ground and the title and
/// section bands' reverse video visible in `docs/lookout/frames.ansi`
/// rather than under-representing both.
fn sgr(fg: Color, bg: Color, modifier: Modifier) -> String {
    let mut out = String::new();
    if modifier.contains(Modifier::REVERSED) {
        out.push_str("\u{1b}[7m");
    }
    match fg {
        Color::Reset => {}
        Color::Indexed(index) => {
            let _ = write!(out, "\u{1b}[38;5;{index}m");
        }
        Color::Red => out.push_str("\u{1b}[31m"),
        Color::Green => out.push_str("\u{1b}[32m"),
        Color::Yellow => out.push_str("\u{1b}[33m"),
        Color::DarkGray => out.push_str("\u{1b}[90m"),
        _ => {}
    }
    match bg {
        Color::Reset => {}
        Color::Indexed(index) => {
            let _ = write!(out, "\u{1b}[48;5;{index}m");
        }
        Color::Red => out.push_str("\u{1b}[41m"),
        Color::Green => out.push_str("\u{1b}[42m"),
        Color::Yellow => out.push_str("\u{1b}[43m"),
        Color::DarkGray => out.push_str("\u{1b}[100m"),
        _ => {}
    }
    out
}

/// Declares `Scene` and its `ALL` listing from one variant list, so the two
/// cannot diverge by construction: a variant left out of the macro call
/// simply does not exist, and one included is in both the enum and `ALL` by
/// the same repetition. `scene_after`, below, still has to be kept in step
/// by hand — its own doc explains what it catches that this macro does not.
macro_rules! scenes {
    (
        $(#[$enum_doc:meta])*
        pub enum Scene {
            $(
                $(#[$variant_doc:meta])*
                $variant:ident,
            )*
        }
    ) => {
        $(#[$enum_doc])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum Scene {
            $(
                $(#[$variant_doc])*
                $variant,
            )*
        }

        impl Scene {
            /// Every scene, in the order they appear in the gallery.
            pub const ALL: &'static [Self] = &[
                $(Self::$variant,)*
            ];
        }
    };
}

scenes! {
/// The scenes the frame snapshots pin and the gallery renders.
pub enum Scene {
    /// A healthy flock at a comfortable width, all three panes up.
    HealthyWide,
    /// One sheep errored, one waiting to restart, one stopped.
    Errored,
    /// Three instances of one app under a group header, with the cursor on
    /// the header.
    Grouped,
    /// `F` pressed: the flock gathered by fold instead of by name. Two folds
    /// of differing size, one of them collapsed, an app grouped inside the
    /// larger fold, two sheep with no fold at all, and a dog, which is
    /// never in a fold.
    Folds,
    /// Both sections at once: several sheep under Flock, a healthy
    /// built-in dog and a silent adopted one under Dogs.
    WithDogs,
    /// The `MEM/CEIL` gauge's three states in one frame: comfortably under
    /// a configured ceiling, at 94% of one (the butter warning role, where
    /// there is colour to carry it), and no ceiling configured at all.
    MemCeiling,
    /// The `CFG` column's `!N` and `*N` markers, one sheep each, plus a CPU
    /// history long enough that the `CpuSpark` column draws a shape rather
    /// than a single bar.
    CfgDrift,
    /// Nothing registered.
    Empty,
    /// A narrow terminal: four columns dropped.
    Narrow,
    /// Below the floor.
    TooNarrow,
    /// Mid-reconnect.
    Retrying,
    /// The shepherd is gone and the values are frozen.
    Frozen,
    /// The read-only refusal.
    Refused,
    /// Mid-type: the table has already narrowed and the box is still open.
    FilterEditing,
    /// Applied and no longer editing.
    FilterActive,
    /// A query nothing matches.
    FilterNoMatch,
    /// 20 rows: the 18-tier. The detail pane is gone; the strip and the feed
    /// are not.
    NoDetail,
    /// 12 rows: below every optional-pane threshold. 12a's frame.
    TableOnly,
    /// The feed under a burst: lines dropped and bytes never read.
    FeedGap,
    /// The selected sheep has never written a log in this `$SHEP_HOME`.
    FeedMissing,
    /// 33x26: the narrowest terminal that still draws all three panes.
    Cramped,
    /// `sysinfo` reports this platform unsupported.
    HostUnknown,
    /// The detail pane with a lamb list.
    Lambs,
    /// The detail pane on a sheep with no pid, where the shepherd had no tree
    /// to walk.
    LambsUnknown,
    /// An action key pressed with the gate open. Nothing has been sent.
    Confirm,
    /// Enter pressed. The request is out.
    Acting,
    /// The shepherd refused, in its own words.
    ActionRefused,
    /// The shepherd did it, and the bar says so in the non-grave style.
    ActionAccepted,
    /// An action key pressed while the link is coming back.
    ActionRefusedOffline,
    /// The settings screen on a fresh `$SHEP_HOME`: only `[interpreters]` on
    /// disk, so every scalar reads its compiled default. The state most
    /// operators open the screen in.
    SettingsFresh,
    /// The settings screen with some scalars declared, so `shep.toml` and
    /// the default sit side by side.
    SettingsSet,
    /// The settings screen with a `[daemon]` confirm armed, naming the
    /// variable and the flag it cannot see.
    SettingsConfirm,
    /// The settings screen with the `socket` editor open mid-path.
    SettingsTyping,
    /// The settings screen's dogs table, showing the drift it exists to
    /// make visible.
    SettingsDogs,
    /// The settings screen on a narrow terminal, where both of its tables
    /// have dropped a column.
    SettingsNarrow,
    /// The settings screen on a terminal too short to hold every row, with
    /// the cursor on the last one, so the view has scrolled.
    SettingsShort,
    /// The full-screen bleats pane with all three filter axes stacked: a
    /// stream, a minimum level and a regex, wrapping turned on so the one
    /// surviving line's full text is on screen rather than truncated.
    Bleats,
    /// `S` pressed: the secrets pane, with `DB_PASSWORD` revealed, a
    /// `vercel` provider group and `ELSEWHERE_ONLY` sitting unresolved for
    /// this environment, tall enough to draw both the FOCUSED and WHO
    /// READS IT panels.
    Secrets,
    /// The sheep pane at its design size, 160x48: both charts, the config
    /// and env column, and the embedded feed, all up at once.
    SheepPane,
    /// 139x48: under 140 columns, the memory chart becomes a one-line
    /// `rss` summary and the CPU chart draws alone.
    SheepPaneCpuOnly,
    /// 99x48: under 100 columns, both charts collapse into 1a's own
    /// `CPU 20s` sparkline and `MEM/CEIL` gauge, one row.
    SheepPaneSparklines,
    /// 160x25: the charts hold their design width but not their design
    /// height. The memory chart is gone; the config and feed columns,
    /// which give ground last, are still up.
    SheepPaneShort,
    /// The redrawn editing pane, fresh: no edits filed, at the design
    /// target of 160x48, where the explanation panel and the `LANDS`
    /// column both draw.
    EditPane,
    /// The same pane with two edits filed: one that lands at once and one
    /// that needs a respawn, so the pending section and the title's own
    /// count both appear.
    EditPaneEdited,
    /// The fresh pane at 120 columns: the panel still draws, `LANDS`
    /// gives way to it.
    EditPaneSqueezed,
    /// The fresh pane at 88 columns: the panel is gone, so `LANDS` is
    /// back, since nothing else on screen carries cost.
    EditPaneNarrow,
    /// The close dialog at the design size: two edits filed, one field
    /// already parked, the box centred over the dimmed editing pane.
    CloseDialog,
    /// The same dialog at the exact width its border needs.
    CloseDialogFloor,
    /// One column below that, drawn full width with no border.
    CloseDialogNarrow,
    /// The parked half alone: no edit of the operator's own, and the
    /// heading that says so.
    CloseDialogParked,
    /// `h` pressed at the design target, 160x48: boxed, all four columns,
    /// the sheep, and the gate line reading control enabled.
    Keymap,
    /// The overlay at 130 columns, the narrowest the box's own border can
    /// still hold.
    KeymapFloor,
    /// One column below the box's floor of 130, at 129: the widest borderless
    /// form, still carrying all four columns.
    KeymapBorderlessWide,
    /// 100 columns: three columns share one bank and the fourth, DOING,
    /// drops to a bank of its own.
    KeymapNarrow,
    /// 70 columns: two columns per bank, two banks stacked.
    KeymapTwoColumn,
    /// The overlay raised after the link is lost: the gate line names the
    /// dead link rather than either control state.
    KeymapFrozen,
    /// The overlay raised under `--read-only`: the gate line reads
    /// read-only rather than control enabled.
    KeymapReadOnly,
    /// 160x16: under the box's own nineteen rows, so the boxed-only sheep
    /// is already gone and the `NO_COLOR` sentence sheds too, while every
    /// key row survives.
    KeymapShort,
}
}

impl Scene {
    /// The snapshot name and the gallery heading.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::HealthyWide => "healthy_wide",
            Self::Errored => "errored",
            Self::Grouped => "grouped",
            Self::Folds => "folds",
            Self::WithDogs => "with_dogs",
            Self::MemCeiling => "mem_ceiling",
            Self::CfgDrift => "cfg_drift",
            Self::Empty => "empty",
            Self::Narrow => "narrow",
            Self::TooNarrow => "too_narrow",
            Self::Retrying => "retrying",
            Self::Frozen => "frozen",
            Self::Refused => "refused",
            Self::FilterEditing => "filter_editing",
            Self::FilterActive => "filter_active",
            Self::FilterNoMatch => "filter_no_match",
            Self::NoDetail => "no_detail",
            Self::TableOnly => "table_only",
            Self::FeedGap => "feed_gap",
            Self::FeedMissing => "feed_missing",
            Self::Cramped => "cramped",
            Self::HostUnknown => "host_unknown",
            Self::Lambs => "lambs",
            Self::LambsUnknown => "lambs_unknown",
            Self::Confirm => "confirm",
            Self::Acting => "acting",
            Self::ActionRefused => "action_refused",
            Self::ActionAccepted => "action_accepted",
            Self::ActionRefusedOffline => "action_refused_offline",
            Self::SettingsFresh => "settings_fresh",
            Self::SettingsSet => "settings_set",
            Self::SettingsConfirm => "settings_confirm",
            Self::SettingsTyping => "settings_typing",
            Self::SettingsDogs => "settings_dogs",
            Self::SettingsNarrow => "settings_narrow",
            Self::SettingsShort => "settings_short",
            Self::Bleats => "bleats",
            Self::Secrets => "secrets",
            Self::SheepPane => "sheep_pane",
            Self::SheepPaneCpuOnly => "sheep_pane_cpu_only",
            Self::SheepPaneSparklines => "sheep_pane_sparklines",
            Self::SheepPaneShort => "sheep_pane_short",
            Self::EditPane => "edit_pane",
            Self::EditPaneEdited => "edit_pane_edited",
            Self::EditPaneSqueezed => "edit_pane_squeezed",
            Self::EditPaneNarrow => "edit_pane_narrow",
            Self::CloseDialog => "close_dialog",
            Self::CloseDialogFloor => "close_dialog_floor",
            Self::CloseDialogNarrow => "close_dialog_narrow",
            Self::CloseDialogParked => "close_dialog_parked",
            Self::Keymap => "keymap",
            Self::KeymapFloor => "keymap_floor",
            Self::KeymapBorderlessWide => "keymap_borderless_wide",
            Self::KeymapNarrow => "keymap_narrow",
            Self::KeymapTwoColumn => "keymap_two_column",
            Self::KeymapFrozen => "keymap_frozen",
            Self::KeymapReadOnly => "keymap_read_only",
            Self::KeymapShort => "keymap_short",
        }
    }

    /// One sentence saying what this frame is for, printed above it in the
    /// gallery.
    ///
    /// `every_scene_shows_the_thing_it_is_named_for` pins each clause: a
    /// caption may not claim what the frame is not asserted to show.
    #[must_use]
    pub const fn caption(self) -> &'static str {
        match self {
            Self::HealthyWide => {
                "All three panes at 120x30: the host strip under the title, the detail pane and the bleats feed under the table. The selected row is marked, painted where the palette has a ground to paint with and shown with a `>` where it does not, and every pane below the table describes that sheep, whose log row reads a real size off disk rather than the placeholder every other scene's fictional path leaves blank."
            }
            Self::Errored => {
                "One errored, one waiting to restart, one stopped, with the selection parked on the errored sheep. Each row's own STATUS cell is the only coloured cell in that row, and EXIT carries why each of the three stopped: a code for the two that crashed, a signal name for the one shep stopped itself."
            }
            Self::Grouped => {
                "Three instances of one app under a group header, with the cursor parked on the header. The header sums their restarts, CPU and memory and takes the SHORTEST of their uptimes, so a group reads as time since the app was last disturbed rather than as the age of its luckiest instance. The detail pane repeats that rollup and says lambs are per-instance; the feed will not guess which instance to tail."
            }
            Self::Folds => {
                "160 columns, wide enough for the full fold-view column set including SHARE and NOTES. `batch` and `core` are two folds of differing size, `batch` collapsed so only its header shows; `edge` is the largest, holding the grouped app `web` \u{d7}3 alongside standalone `api`, and the cursor is parked on its header. `cron` and `metrics` carry no fold and sit under a `no fold` band that is not selectable, and `bark`, a dog, sits under its own band because a dog is never in a fold. Each fold header sums its members' restarts, CPU and memory and takes the shortest of their uptimes, and its SHARE gauge and NOTES percentage both read that fold's share of the whole flock's memory."
            }
            Self::WithDogs => {
                "Three sheep under a FLOCK band and two dogs under a DOGS band: bark is built-in and healthy, log-rotate is adopted from /usr/local/bin/shep-log-rotate and has never handshaken, so its STATUS reads silent rather than online, and the cursor is parked on it."
            }
            Self::MemCeiling => {
                "Three sheep with a max_memory ceiling configured, or not: web-headroom sits at a quarter of its limit and its MEM/CEIL gauge fills a little, web-hot sits at 94 percent of its own limit and its gauge fills almost all the way, and where there is colour the fuller gauge also switches to the butter warning role. batch-worker has no ceiling at all, so its gauge reads the same muted bar a stopped sheep's does. The cursor is parked on web-hot, the row this frame exists to show."
            }
            Self::CfgDrift => {
                "140 columns: wide enough for the CFG and CPU 20s columns beside the ones every other scene shows. web has two fields parked for the next spawn and reads !2, api has one field an operator set that its Flockfile does not declare and reads *1, and cron has neither and reads a bare -. The status bar's own legend explains both glyphs; this is where they actually appear in a cell. web's counter is differenced across several two-second polls at varying deltas, so its CPU history draws a shape over time rather than one static bar, and the cursor is parked on web so the detail pane's own cfg !2 pending cell is on screen too."
            }
            Self::Empty => {
                "No sheep registered. Each of the three panes says why it is empty, and the three sentences are different because the three reasons are."
            }
            Self::Narrow => {
                "51 columns: FOLD, EXIT, RESTARTS, PID and MEM are gone, in that order. CPU and UPTIME survive because they explain WHY a RUNNING sheep is behaving badly, a question EXIT cannot even ask. The host strip truncates with an ellipsis rather than disappearing; the detail pane and the feed do not fit at all, at 14 rows."
            }
            Self::TooNarrow => {
                "28 columns: below the floor, the pane refuses rather than drawing overlapping garbage. Two short lines, so the refusal still fits the terminal it is refusing about."
            }
            Self::Retrying => {
                "The shepherd stopped answering. Five attempts over about eight seconds before this becomes the next frame. Every pane below the table keeps describing the selected sheep from the last listing."
            }
            Self::Frozen => {
                "The ladder ran out. The band says so in bark, the whole table and the host strip go to one muted ink so no cell reads as live, and UPTIME becomes FROZEN over a duration that has stopped advancing. The detail band and the feed give their rows to the link panel: they describe a shepherd that is gone, and it describes what happened."
            }
            Self::Refused => {
                "`x` with actions gated off. The refusal is literal, nothing about damage gets charming, and the panes below carry on."
            }
            Self::FilterEditing => {
                "Mid-type at 100x14. The table has already narrowed to the two sheep whose names contain the query, the title counts the narrowed set and the whole flock, and the status bar carries the query, a cursor, and the three keys that mean anything while the box is open."
            }
            Self::FilterActive => {
                "The same query applied. The box is closed, the table is still narrowed, and the bar has changed to name the two keys that now touch the filter."
            }
            Self::FilterNoMatch => {
                "A query nothing matches. The table names the query rather than claiming the flock is empty, and the title keeps the flock's real size on screen."
            }
            Self::NoDetail => {
                "20 rows: the detail pane is the first to go, because every number on it but the log paths is already in the row above it."
            }
            Self::TableOnly => {
                "12 rows: no optional panes at all. This is 12a's frame, and the only thing that changed is the two-column gutter that marks the selection, painted where there is a ground to paint with and shown with `>` where there is not."
            }
            Self::FeedGap => {
                "The feed under a burst: 3.8 megabytes were never read and some hundreds of lines were read and dropped. The pane counts both, and counts them separately, because it knows the second exactly and cannot know how many lines are in the first."
            }
            Self::FeedMissing => {
                "The selected sheep has never written a log in this $SHEP_HOME. The feed names that cause rather than sitting blank."
            }
            Self::Cramped => {
                "33 columns: the narrowest terminal that draws. 26 rows (a couple more than the 24-row floor for all three panes being up), so this frame has a little breathing room rather than sitting exactly on the edge. Everything truncates with an ellipsis; nothing overlaps."
            }
            Self::HostUnknown => {
                "`sysinfo` reports this platform unsupported. The strip says so and keeps the flock's own totals, which lookout can always compute."
            }
            Self::Lambs => {
                "The detail pane with a lamb list: how many descendants the shepherd's walk found, how old that reading is, and each lamb's pid and executable name. The stamp sits before the list so a narrow terminal truncates lambs rather than the caveat."
            }
            Self::LambsUnknown => {
                "The same pane on a stopped sheep. The shepherd had no pid to walk from and left the field unset rather than empty, and the line says which of the two it is looking at rather than reporting none found."
            }
            Self::Confirm => {
                "`R` pressed with the gate open. Nothing has been sent: the bar asks a question naming the verb and the exact sheep, and `api` is still online in the table behind it."
            }
            Self::Acting => {
                "Enter pressed. The request is out and nothing on the table has changed, because nothing the shepherd has said has changed: `api` is still online and the cursor has not moved."
            }
            Self::ActionAccepted => {
                "The shepherd answered. The bar says what it did, in the non-grave style a refusal does not get, and the table shows the row the reply carried rather than waiting for the next poll."
            }
            Self::ActionRefused => {
                "The shepherd refused while the request was out, and its own sentence is forwarded rather than rewritten. The sheep has left the flock in the listing behind it, so the table is one row shorter and the cursor has moved to the row below."
            }
            Self::ActionRefusedOffline => {
                "An action key pressed while the link is coming back. The refusal names the same reconnect attempt the banner above it does, rather than the exhausted-ladder sentence. Phase 16 review Minor #8 caught the two disagreeing on one frame."
            }
            Self::SettingsFresh => {
                "The settings screen on a fresh $SHEP_HOME: shep.toml holds only [interpreters], so every scalar's SOURCE column reads `the default` and its VALUE is the compiled fallback. The state most operators open this screen in."
            }
            Self::SettingsSet => {
                "The settings screen with some scalars declared. `shep.toml` and `the default` sit side by side in the SOURCE column, so what the operator wrote and what shep assumes are both visible at once."
            }
            Self::SettingsConfirm => {
                "A [daemon] confirm armed on log_level, naming the variable and the flag it cannot see: SHEP_LOG_LEVEL and --log-level, and the shep daemon reload the edit needs."
            }
            Self::SettingsTyping => {
                "The socket editor open mid-path. The status bar names the field being typed, not the dashboard's own filter box, which is what it showed here before the fix this frame now pins."
            }
            Self::SettingsDogs => {
                "The dogs table showing the drift it exists to reveal: otel running while disabled in the file, ledger enabled and absent, and bark enabled, running, and silent."
            }
            Self::SettingsNarrow => {
                "The same screen at 45 columns. Both of its tables have dropped a column rather than clipping: the scalar rows have lost the apply cost and kept SOURCE, and the dogs table has lost SOURCE and kept RUNNING. Each keeps whichever half is not said anywhere else."
            }
            Self::SettingsShort => {
                "The same screen at 14 rows, which is fewer than it has to draw. The cursor is on the last dog, so the view has scrolled to reach it and `... 5 above` says how much is off the top. The scroll is counted in LINES rather than in rows: a section header and the dogs caption cost the same height a row does."
            }
            Self::Bleats => {
                "The full-screen bleats pane, pinned to api, with a stream, a minimum level and a regex all stacked: only out, only warn and above, only a line mentioning retrying or jitter. The filter row states the composition and counts one surviving line out of sixteen, and that one line is also the longest in the fixture, so wrapping is on and its full text runs onto a second row instead of an ellipsis."
            }
            Self::Secrets => {
                "The secrets pane, opened with `S`. DB_PASSWORD is revealed and named by one reader; vercel/API_TOKEN sits in its own read-only provider group; ELSEWHERE_ONLY has a slot in ci but not here, so it reads unresolved for this tab. The frame is tall enough to carry both the FOCUSED panel and WHO READS IT below the table."
            }
            Self::SheepPane => {
                "The sheep pane on web, at its design size: 160 = 8 gutter + 140 body + 12 margin for each chart, and 160 = 76 config + 1 divider + 83 feed across the row below them. Both charts draw their full body, the config and env column lists web's own fields, and the embedded feed carries its own lines, all on one screen. web's cpu_ms counter is differenced across several two-second polls, rising by varying deltas, so both charts draw a shape rather than a single repeated bar."
            }
            Self::SheepPaneCpuOnly => {
                "139 columns: one cell under the 140 the full two-chart body needs. The CPU chart still draws at its own body width, but the memory chart is gone, replaced by a one-line `rss` summary and a ten-cell gauge: memory still has a gauge to fall back on, and the CPU chart is the more diagnostic of the two, so it is the one that stays."
            }
            Self::SheepPaneSparklines => {
                "99 columns: one cell under the 100 the CPU-only tier needs. Both charts are gone, and the pane falls back to 1a's own pair: the `CPU 20s` sparkline and the `MEM/CEIL` gauge, on one row."
            }
            Self::SheepPaneShort => {
                "160 columns, 25 rows: the charts hold their design width but not their design height. Under 26 rows the memory chart goes; the CPU chart and the config and env column, which give ground last, are still up."
            }
            Self::EditPane => {
                "The redrawn editing pane on api, fresh: no edits filed, at 160x48. The tab row names all eight groups with only the active one chipped, the header reads FIELD / VALUE / LANDS, the explanation panel sits beside the field list naming the field under the cursor, and every env value reads (set) rather than the value itself."
            }
            Self::EditPaneEdited => {
                "The same pane with two edits filed: cwd, which needs a respawn, and max_memory, which lands at once. The pending edits section lists both under the active group's own fields, and the title band reads 2 edits."
            }
            Self::EditPaneSqueezed => {
                "The same fresh pane at 120 columns: narrow enough that LANDS gives way to the explanation panel, which still names the focused field's own cost in words."
            }
            Self::EditPaneNarrow => {
                "The same fresh pane at 88 columns: narrow enough that the explanation panel is gone, so LANDS is back, since nothing else on screen carries cost."
            }
            Self::CloseDialog => {
                "esc pressed with cwd and err_file edited and listen_timeout already parked from before: the close dialog names both counts, boxed and centred at 160x48 over the dimmed editing pane."
            }
            Self::CloseDialogFloor => {
                "The same dialog at 90 columns, exactly the floor its border needs: 86 interior cells plus a border cell and a margin cell each side."
            }
            Self::CloseDialogNarrow => {
                "The same dialog one column under the floor, at 89: the border is dropped and the dialog draws full width instead of clipping."
            }
            Self::CloseDialogParked => {
                "esc pressed with no edit of the operator's own, only listen_timeout already parked: the heading names the parked half alone."
            }
            Self::Keymap => {
                "`h` pressed at 160x48, the design target: boxed at 128 columns (126 interior plus one border cell each side), all four columns drawn whole, the sheep once in the DOING column's own rows, and the gate line reading control enabled over the dimmed dashboard behind it."
            }
            Self::KeymapFloor => {
                "The same overlay at 130 columns, the narrowest the border can still hold: 130 = 128 (126 interior plus one border cell each side) plus one margin cell each side. One column narrower and the border is gone."
            }
            Self::KeymapBorderlessWide => {
                "129 columns, one below KeymapFloor's own 130: the border is gone, but columns_for(129) is still 4, so this is the widest form the overlay ever draws with all four columns and no frame around them. It sits next to KeymapFloor on purpose, so the two together pin the boundary rather than bracketing it loosely."
            }
            Self::KeymapNarrow => {
                "100 columns: columns_for(100) is 3, so MOVING, LOOKING and CHANGING share one bank and DOING drops to a bank of its own below a blank separator row."
            }
            Self::KeymapTwoColumn => {
                "70 columns: columns_for(70) is 2, so the four groups split into two banks of two, MOVING and LOOKING on top and CHANGING and DOING below."
            }
            Self::KeymapFrozen => {
                "The overlay raised after the link is already lost: the gate line names the dead link, not either control state, the same precedence the status bar's own right-hand label gives Link::Lost over Control."
            }
            Self::KeymapReadOnly => {
                "The overlay raised under --read-only: the gate line reads read-only where the design target's own reads control enabled."
            }
            Self::KeymapShort => {
                "160x16, under the nineteen rows the box needs: the sheep is boxed-only and already gone, and the borderless form has shed to its own Decoration tier, which drops the NO_COLOR sentence too, while every key row is still on screen."
            }
        }
    }

    /// Whether this scene's dashboard may act.
    ///
    /// Allowed is the fallthrough, matching the real dashboard's default.
    /// Two exceptions, and they show the closed gate in different places:
    /// `Refused` in the dashboard's own status bar, `KeymapReadOnly` in the
    /// overlay's gate line.
    #[must_use]
    pub const fn control(self) -> Control {
        match self {
            Self::Refused | Self::KeymapReadOnly => Control::ReadOnly,
            _ => Control::Allowed,
        }
    }

    /// The terminal size this scene is rendered at.
    #[must_use]
    pub const fn size(self) -> (u16, u16) {
        match self {
            Self::Empty => (100, 28),
            // 150: `columns_for` runs on `width - GUTTER`, so 150 - GUTTER =
            // 148, past `ALL`'s 146 threshold: the one scene that needs
            // both `CpuSpark` and `MemCeil` drawn, not dropped for width.
            Self::MemCeiling => (150, 30),
            // 140: `columns_for` runs on `width - GUTTER`, so 140 - GUTTER =
            // 138, past `NO_CEIL`'s 134 threshold and short of `ALL`'s 146:
            // `CpuSpark` and `Cfg` both draw, `MemCeil` does not (it has its
            // own scene above).
            Self::CfgDrift => (140, 30),
            // 51: `columns_for` runs on `width - GUTTER` (the two-column
            // selection marker), so 51 - GUTTER = 49, the `NO_MEM` tier:
            // four columns gone, CPU and UPTIME still there.
            Self::Narrow => (51, 14),
            Self::TooNarrow => (28, 8),
            Self::FilterEditing | Self::FilterActive | Self::FilterNoMatch => (100, 14),
            Self::NoDetail => (120, 20),
            Self::TableOnly => (120, 12),
            Self::Cramped => (33, 26),
            // `fold_columns_for` runs on `width - GUTTER`, so 160 - GUTTER
            // is exactly `FOLD_ALL`'s threshold: the one scene that needs the
            // full column set, SHARE and NOTES included.
            Self::Folds => (160, 30),
            // The design target, and comfortably past the floor this
            // scene actually needs. `columns_for` runs on `width - GUTTER`,
            // and `ALL`'s own threshold is the sum of what it draws:
            //
            //   ALL's fixed widths        = 112
            //   13 two-cell separators    =  26
            //   NAME at its floor         =   8  (NAME_MIN)
            //   112 + 26 + 8              = 146, `TIERS`'s widest entry
            //
            // So 148 columns is the floor and 160 leaves NAME 20 cells,
            // which is what the frame drew. `the_frozen_scene_draws_every_
            // column` pins the floor; the extra twelve are the design's.
            //
            // At the 120 this used to inherit from the default arm, the
            // table renders the NO_SPARK tier: no CPU sparkline and no
            // MEM/CEIL gauge, which is two of the cells the frame exists to
            // show frozen. 30 rows, not the design's 48: the link panel is
            // six rows where the two panes it replaces were twelve, so
            // nothing here needs the taller frame.
            Self::Frozen => (160, 30),
            Self::Confirm
            | Self::Acting
            | Self::ActionRefused
            | Self::ActionAccepted
            | Self::ActionRefusedOffline => (100, 14),
            // 180: the log_level confirm's sentence runs to 170 columns,
            // past every other scene's width. Narrower would truncate the
            // flag it shows.
            Self::SettingsConfirm => (180, 30),
            // 45: the middle tier of both `SCALAR_TIERS` and `DOG_TIERS`,
            // so both tables have dropped one column without losing a row.
            Self::SettingsNarrow => (45, 24),
            // 14 rows: twelve of body, against a screen that wants
            // eighteen lines. Short enough that the cursor cannot be
            // reached without scrolling, tall enough that what survives is
            // a legible section rather than a single row.
            Self::SettingsShort => (120, 14),
            // 100: `bleats_full`'s own text width is `width - TAG_PREFIX_WIDTH`
            // (5), so 100 - 5 = 95. The fixture's one surviving line is 153
            // characters, so it wraps onto exactly two rows at this width
            // (153 / 95, rounded up); a wider frame would still wrap it but
            // would no longer pin that arithmetic. 14 rows, the same tier
            // `Confirm` and its siblings use: a title, a filter row and two
            // wrapped rows fit inside `body_rows`'s 12 with room to spare.
            //
            // The title truncates here and that is the honest render: two
            // full log paths plus the window figures do not fit 100 columns,
            // and `fit` cuts what a real terminal would. Widening to show
            // them whole would unpin the wrap arithmetic above, which is what
            // this scene exists for. `the_title_names_the_window_and_what_
            // fell_below_it` covers the figures at a width that fits them.
            Self::Bleats => (100, 14),
            // Tall enough that `content_bottom` leaves room for both
            // `draw_panels`' FOCUSED and WHO READS IT rows below the table,
            // the frame this scene exists to show.
            Self::Secrets => (160, 48),
            // 160 = 8 gutter + 140 body + 12 margin for each chart, and
            // 160 = 76 config + 1 divider + 83 feed: the sheep pane's own
            // design size, wide enough for every column at once.
            Self::SheepPane => (160, 48),
            // 139: one cell under the 140 the full two-chart body needs, so
            // `chart_tier` downgrades to `CpuOnly` on width alone.
            Self::SheepPaneCpuOnly => (139, 48),
            // 99: one cell under the 100 `CpuOnly` needs, so `chart_tier`
            // downgrades again, to `Sparkline`.
            Self::SheepPaneSparklines => (99, 48),
            // 25 rows: one short of `FULL_TIER_MIN_HEIGHT` (26), so the
            // memory chart drops while the CPU chart, the config column and
            // the feed all still fit.
            Self::SheepPaneShort => (160, 25),
            // The design target: 45% of 160 is 72, so both the panel and
            // `LANDS` draw at their widest.
            Self::EditPane | Self::EditPaneEdited => (160, 48),
            // 120: past `panel_width`'s `LEFT_MIN` floor, so the panel
            // still draws, but short of `LANDS_WITH_PANEL_MIN` (160), so
            // `LANDS` gives way to it.
            Self::EditPaneSqueezed => (120, 48),
            // 88: short of `panel_width`'s `LEFT_MIN` floor (`88 - 50 <
            // 40`), so the panel does not draw at all and `LANDS` returns.
            Self::EditPaneNarrow => (88, 48),
            // 160: the design target. The box is 86 interior plus a border
            // cell each side, so (160 - 88) / 2 = 36 dimmed columns each
            // side of it.
            Self::CloseDialog | Self::CloseDialogParked => (160, 48),
            // 90: the floor exactly, 86 + 2 border + 2 margin. A scene
            // pinned one column short of its own box would draw the
            // borderless form and silently stop showing the border it
            // exists to show.
            Self::CloseDialogFloor => (90, 48),
            // 89: one below the floor, which is the borderless form.
            Self::CloseDialogNarrow => (89, 48),
            // 160: the design target, boxed at 128 (126 interior plus one
            // border cell each side), so (160 - 128) / 2 = 16 dimmed columns
            // each side of it.
            Self::Keymap | Self::KeymapFrozen | Self::KeymapReadOnly => (160, 48),
            // 130: `overlay::floor_for(126)`, the narrowest width the box's
            // own border can still draw at.
            Self::KeymapFloor => (130, 48),
            // 129: one below the floor of 130, the widest borderless form that
            // still carries all four columns (`columns_for(129) == 4`).
            Self::KeymapBorderlessWide => (129, 48),
            // 100: `columns_for(100) == 3`, so DOING drops to a bank of
            // its own.
            Self::KeymapNarrow => (100, 48),
            // 70: `columns_for(70) == 2`, two banks of two columns each.
            Self::KeymapTwoColumn => (70, 48),
            // 16 rows: under the box's own 19, so the sheep (boxed-only) is
            // already gone, and the borderless form has shed to its own
            // `Shed::Decoration`, which drops the NO_COLOR line too; every
            // key row stays intact. 16, not 22: at 22 the box holds whole
            // and nothing sheds.
            Self::KeymapShort => (160, 16),
            // HealthyWide, Errored, Grouped, WithDogs, Retrying, Refused,
            // FeedGap, FeedMissing, HostUnknown, Lambs, LambsUnknown: every
            // scene that carries all three optional panes at their ordinary
            // rows.
            _ => (120, 30),
        }
    }

    /// Whether this scene raises the keymap overlay before it renders.
    ///
    /// Every arm named on both sides rather than a wildcard on either, so
    /// a ninth `Keymap*` variant fails to compile here instead of
    /// rendering silently without the overlay raised.
    #[must_use]
    pub const fn is_keymap(self) -> bool {
        match self {
            Self::Keymap
            | Self::KeymapFloor
            | Self::KeymapBorderlessWide
            | Self::KeymapNarrow
            | Self::KeymapTwoColumn
            | Self::KeymapFrozen
            | Self::KeymapReadOnly
            | Self::KeymapShort => true,
            Self::HealthyWide
            | Self::Errored
            | Self::Grouped
            | Self::Folds
            | Self::WithDogs
            | Self::MemCeiling
            | Self::CfgDrift
            | Self::Empty
            | Self::Narrow
            | Self::TooNarrow
            | Self::Retrying
            | Self::Frozen
            | Self::Refused
            | Self::FilterEditing
            | Self::FilterActive
            | Self::FilterNoMatch
            | Self::NoDetail
            | Self::TableOnly
            | Self::FeedGap
            | Self::FeedMissing
            | Self::Cramped
            | Self::HostUnknown
            | Self::Lambs
            | Self::LambsUnknown
            | Self::Confirm
            | Self::Acting
            | Self::ActionRefused
            | Self::ActionAccepted
            | Self::ActionRefusedOffline
            | Self::SettingsFresh
            | Self::SettingsSet
            | Self::SettingsConfirm
            | Self::SettingsTyping
            | Self::SettingsDogs
            | Self::SettingsNarrow
            | Self::SettingsShort
            | Self::Bleats
            | Self::Secrets
            | Self::SheepPane
            | Self::SheepPaneCpuOnly
            | Self::SheepPaneSparklines
            | Self::SheepPaneShort
            | Self::EditPane
            | Self::EditPaneEdited
            | Self::EditPaneSqueezed
            | Self::EditPaneNarrow
            | Self::CloseDialog
            | Self::CloseDialogFloor
            | Self::CloseDialogNarrow
            | Self::CloseDialogParked => false,
        }
    }
}

/// The gallery's own coloured palette (`xterm-256color`, the deep tier).
/// Every pinned `.snap` test and `docs/lookout/frames.ansi` render through
/// this one, so a real terminal at that tier sees exactly what they pin.
#[must_use]
fn coloured_palette() -> Palette {
    Palette::detect(None, Some(std::ffi::OsStr::new("xterm-256color")), None)
}

/// The flattened `NO_COLOR` palette. `docs/lookout/frames.txt` renders
/// through this one, not the coloured one: a plain-text gallery cannot
/// carry a painted background, so rendering it through the palette an
/// operator with `$NO_COLOR` set actually gets is what makes it an honest
/// picture rather than a coloured frame with the color silently missing.
#[must_use]
fn no_color_palette() -> Palette {
    Palette::detect(Some(std::ffi::OsStr::new("1")), None, None)
}

/// Builds one scene and returns its label with the buffer it drew into.
///
/// Renders at ten minutes of dashboard age, the same age the pinned
/// snapshots and `docs/lookout/frames.ansi` use, through
/// [`coloured_palette`].
#[must_use]
pub fn scene(which: Scene) -> (&'static str, Buffer) {
    (
        which.label(),
        scene_with(which, Duration::from_secs(600), coloured_palette()),
    )
}

/// Parks the gallery's cursor on the sheep with id `id`.
///
/// Walks by name since `SelectDown` moves one visible row and the table
/// reads by name, not id.
///
/// # Panics
///
/// If `id` is not in the flock, or is hidden by a filter.
#[track_caller]
fn select_id(app: &mut App, id: u32) {
    select_row(app, &RowKey::Sheep(id));
}

/// Parks the gallery's cursor on `name`'s group header.
///
/// # Panics
///
/// If `name` has no group header: an app with one instance, or an
/// instance that reports no slot.
#[track_caller]
fn select_group(app: &mut App, name: &str) {
    select_row(app, &RowKey::Group(name.to_string()));
}

/// Parks the gallery's cursor on `name`'s fold header.
///
/// # Panics
///
/// If `name` has no fold header: the table is not in the fold view yet, or
/// nothing in the flock carries that fold.
#[track_caller]
fn select_fold(app: &mut App, name: &str) {
    select_row(app, &RowKey::Fold(name.to_string()));
}

/// Walks the cursor to `key`, up or down as `key`'s position relative to the
/// current one calls for.
///
/// `Folds` needs the reverse direction: pressing `F` leaves the cursor on
/// whichever sheep the flat view had selected, which can sit past a fold's
/// header in the new, by-fold order, so a downward-only walk could never
/// reach it. Every other scene's target still happens to sit at or after the
/// starting row, so this is a superset of what a forward-only walk did, not
/// a behaviour change for them.
///
/// Budgeted by [`App::visible_rows`]'s length, not the flock count: a
/// grouped app's header adds a visible row beyond its own slots.
///
/// # Panics
///
/// If `key` is not a visible row.
#[track_caller]
fn select_row(app: &mut App, key: &RowKey) {
    for _ in 0..=app.visible_rows().len() {
        if app.selected().as_ref() == Some(key) {
            return;
        }
        let target = app.visible_rows().iter().position(|row| row == key);
        let step = match (app.selected_index(), target) {
            (Some(current), Some(target)) if target < current => KeyPress::SelectUp,
            _ => KeyPress::SelectDown,
        };
        app.update(Msg::Key(step));
    }
    panic!("the gallery cannot park its cursor on {key:?}");
}

/// Runs `rows` through two polls, two seconds apart, so
/// `App::record_samples` has something to difference: a fixture built from
/// one snapshot never gets past the first insert into `App::cpu_last`,
/// which returns nothing to draw rather than a false zero (see
/// `App::record_samples`'s own doc), and every CPU cell and sparkline in
/// the gallery rendered a bare `-` for exactly that reason until this
/// existed.
///
/// The second, final poll lands at `anchor` itself, not two seconds after
/// it: every uptime and age figure below reads from `anchor`, so parking
/// the *first*, throwaway poll two seconds *before* it is what keeps this
/// helper a pure addition rather than a two-second wobble on every uptime
/// in the gallery that used to land on a round minute.
///
/// `deltas` names each running sheep's id and its two `cpu_ms` readings,
/// oldest first; a row whose id is absent from `deltas` keeps whatever
/// `cpu_ms` its caller already gave it (`None`, for every fixture below),
/// so a stopped or errored row still reads a bare `-` on purpose.
///
/// Mutates `rows` in place across both polls, the same shape
/// `Scene::SheepPane`'s own fixture uses and `Scene::CfgDrift`'s does not:
/// `CfgDrift` polls a clone and leaves its own returned row's `cpu_ms` at
/// `None`, which is why that scene's CPU cell still reads `-` despite its
/// sparkline drawing a real shape.
fn poll_twice(
    app: &mut App,
    anchor: Instant,
    mut rows: Vec<ProcessInfo>,
    deltas: &[(u32, u64, u64)],
) -> Vec<ProcessInfo> {
    for &(id, first, _) in deltas {
        if let Some(row) = rows.iter_mut().find(|row| row.id == id) {
            row.cpu_ms = Some(first);
        }
    }
    app.update(Msg::Snapshot {
        rows: rows.clone(),
        at: anchor - Duration::from_secs(2),
    });
    for &(id, _, second) in deltas {
        if let Some(row) = rows.iter_mut().find(|row| row.id == id) {
            row.cpu_ms = Some(second);
        }
    }
    app.update(Msg::Snapshot {
        rows: rows.clone(),
        at: anchor,
    });
    rows
}

/// One scene, `age` after its opening snapshot, drawn through `palette`.
///
/// Deterministic: a forced palette, an explicit `Instant` advanced by exact
/// `Duration`s, and a literal frozen timestamp, so the gallery never
/// depends on this machine's clock or environment.
///
/// `palette` exists so the gallery can render the same scene twice: once
/// through [`coloured_palette`] for `docs/lookout/frames.ansi` and the
/// pinned snapshots, and once through [`no_color_palette`] for
/// `docs/lookout/frames.txt`.
///
/// `age` exists for
/// `the_frozen_frame_does_not_move_however_long_the_link_stays_gone`,
/// which renders the frozen scene at two ages and checks for identical
/// frames.
#[must_use]
fn scene_with(which: Scene, age: Duration, palette: Palette) -> Buffer {
    let t0 = Instant::now();
    let mut app = App::new(palette, which.control(), "/home/ada/.shep".to_string(), t0);

    let flock = match which {
        Scene::Empty => Vec::new(),
        // The only flock in the gallery whose rows carry a slot, and so the
        // only one that draws a group header at all. `api` is here so the
        // frame shows a grouped app beside an ungrouped one rather than
        // implying every app gets a header.
        Scene::Grouped => poll_twice(
            &mut app,
            t0,
            vec![
                instance(0, "web", 0, 0, 3.4, 182 << 20, 4_512_000),
                // The youngest of the three, and the one carrying restarts:
                // the group row's uptime is a minimum and its restarts are a
                // sum.
                instance(1, "web", 1, 2, 2.9, 178 << 20, 300_000),
                instance(2, "web", 2, 1, 3.1, 180 << 20, 9_000_000),
                sheep(
                    3,
                    "api",
                    ProcStatus::Online,
                    Some(48_219),
                    1,
                    Some(7.1),
                    Some(241 << 20),
                    Some("edge"),
                ),
            ],
            &[(0, 60, 130), (1, 40, 98), (2, 50, 112), (3, 100, 242)],
        ),
        // Two folds of differing size (`batch` at 32MiB, `core` at 96MiB),
        // the biggest fold (`edge`, at 781MiB) carrying a grouped app beside
        // a standalone one, two sheep in no fold at all, and a dog. Every
        // memory figure is a round number of MiB precisely so the SHARE
        // gauge and the NOTES percentage can be checked by hand rather than
        // trusted on sight: batch's 32 of 928 total MiB is 3%, core's 96 is
        // 10%, edge's 781 is 84%.
        Scene::Folds => poll_twice(
            &mut app,
            t0,
            vec![
                sheep(
                    20,
                    "reindexer",
                    ProcStatus::Online,
                    Some(48_500),
                    0,
                    Some(1.2),
                    Some(20 << 20),
                    Some("batch"),
                ),
                sheep(
                    21,
                    "backfill",
                    ProcStatus::Online,
                    Some(48_501),
                    3,
                    Some(0.4),
                    Some(12 << 20),
                    Some("batch"),
                ),
                sheep(
                    22,
                    "worker",
                    ProcStatus::Online,
                    Some(48_510),
                    0,
                    Some(2.0),
                    Some(96 << 20),
                    Some("core"),
                ),
                // `instance` always sets fold to `edge`, which is exactly
                // the fold this scene wants its one grouped app in.
                instance(23, "web", 0, 0, 3.4, 182 << 20, 4_512_000),
                instance(24, "web", 1, 2, 2.9, 178 << 20, 300_000),
                instance(25, "web", 2, 1, 3.1, 180 << 20, 9_000_000),
                sheep(
                    26,
                    "api",
                    ProcStatus::Online,
                    Some(48_219),
                    1,
                    Some(7.1),
                    Some(241 << 20),
                    Some("edge"),
                ),
                sheep(
                    27,
                    "cron",
                    ProcStatus::Online,
                    Some(48_233),
                    0,
                    Some(0.1),
                    Some(8 << 20),
                    None,
                ),
                sheep(
                    28,
                    "metrics",
                    ProcStatus::Online,
                    Some(48_240),
                    0,
                    Some(0.4),
                    Some(11 << 20),
                    None,
                ),
                dog_sheep(90, "bark", DogSource::BuiltIn, None),
            ],
            &[
                (20, 30, 54),
                (21, 10, 18),
                (22, 60, 100),
                (23, 90, 158),
                (24, 70, 128),
                (25, 80, 142),
                (26, 150, 292),
                (27, 5, 7),
                (28, 10, 18),
            ],
        ),
        Scene::Errored | Scene::Frozen | Scene::LambsUnknown => poll_twice(
            &mut app,
            t0,
            vec![
                sheep(
                    0,
                    "web",
                    ProcStatus::Online,
                    Some(48_211),
                    0,
                    Some(3.4),
                    Some(182 << 20),
                    Some("edge"),
                ),
                sheep(
                    1,
                    "web",
                    ProcStatus::Online,
                    Some(48_212),
                    0,
                    Some(2.9),
                    Some(178 << 20),
                    Some("edge"),
                ),
                sheep(
                    2,
                    "api",
                    ProcStatus::Errored,
                    None,
                    14,
                    None,
                    None,
                    Some("edge"),
                ),
                sheep(
                    3,
                    "billing-reconciliation-worker",
                    ProcStatus::WaitingRestart,
                    None,
                    3,
                    None,
                    None,
                    None,
                ),
                sheep(4, "cron", ProcStatus::Stopped, None, 0, None, None, None),
                sheep(
                    5,
                    "metrics",
                    ProcStatus::Online,
                    Some(48_240),
                    0,
                    Some(0.4),
                    Some(11 << 20),
                    None,
                ),
            ],
            &[(0, 90, 158), (1, 70, 128), (5, 10, 18)],
        ),
        // Two dog processes: `otel` up and healthy, `bark` up but never
        // handshook. `ledger` has no row here, which is what "enabled and
        // absent" means in the settings snapshot below.
        Scene::SettingsDogs | Scene::SettingsNarrow | Scene::SettingsShort => vec![
            dog_sheep(90, "otel", DogSource::BuiltIn, None),
            dog_sheep(91, "bark", DogSource::BuiltIn, Some(false)),
        ],
        // A flock's two sections at once: three sheep, a healthy built-in
        // dog and a silent adopted one.
        Scene::WithDogs => poll_twice(
            &mut app,
            t0,
            vec![
                sheep(
                    0,
                    "web",
                    ProcStatus::Online,
                    Some(48_211),
                    0,
                    Some(3.4),
                    Some(182 << 20),
                    Some("edge"),
                ),
                sheep(
                    1,
                    "api",
                    ProcStatus::Online,
                    Some(48_219),
                    1,
                    Some(7.1),
                    Some(241 << 20),
                    Some("edge"),
                ),
                sheep(
                    2,
                    "cron",
                    ProcStatus::Online,
                    Some(48_233),
                    0,
                    Some(0.1),
                    Some(8 << 20),
                    None,
                ),
                dog_sheep(90, "bark", DogSource::BuiltIn, None),
                dog_sheep(
                    91,
                    "log-rotate",
                    DogSource::Adopted {
                        path: "/usr/local/bin/shep-log-rotate".to_string(),
                    },
                    Some(false),
                ),
            ],
            &[(0, 90, 158), (1, 150, 292), (2, 5, 7)],
        ),
        // Decision 7's three MEM/CEIL states, which no other scene's
        // fixtures exercise: every other call to `sheep` leaves
        // `max_memory` at the wire default, `None`.
        Scene::MemCeiling => poll_twice(
            &mut app,
            t0,
            vec![
                sheep_with_ceiling(0, "web-headroom", 128 << 20, 512 << 20),
                sheep_with_ceiling(1, "web-hot", 480 << 20, 512 << 20),
                sheep(
                    2,
                    "batch-worker",
                    ProcStatus::Online,
                    Some(48_303),
                    0,
                    Some(1.0),
                    Some(64 << 20),
                    None,
                ),
            ],
            &[(0, 40, 74), (1, 90, 168), (2, 10, 30)],
        ),
        // The CFG column's two markers, `!N` and `*N`, plus a CPU history
        // long enough that `CpuSpark` draws a shape rather than one bar.
        // Neither has a fixture anywhere else in the gallery: no other
        // scene sets `pending` or `overridden`, and every other scene's
        // flock is built by one `Msg::Snapshot`, giving each sheep exactly
        // one CPU sample.
        Scene::CfgDrift => {
            let mut pending_row = sheep(
                10,
                "web",
                ProcStatus::Online,
                Some(48_410),
                0,
                Some(4.0),
                Some(64 << 20),
                Some("edge"),
            );
            pending_row.pending = Some(vec!["env".to_string(), "port".to_string()]);
            let mut overridden_row = sheep(
                11,
                "api",
                ProcStatus::Online,
                Some(48_411),
                0,
                Some(3.0),
                Some(96 << 20),
                Some("edge"),
            );
            overridden_row.overridden = Some(vec!["instances".to_string()]);
            let plain_row = sheep(
                12,
                "cron",
                ProcStatus::Online,
                Some(48_412),
                0,
                Some(0.5),
                Some(8 << 20),
                None,
            );
            // Nine snapshots ahead of the shared one below, each two seconds
            // apart and each moving `web`'s CPU counter by a distinct
            // delta, so the sparkline differences into a varying shape
            // rather than a single bar padded with blanks. The first of
            // the nine only records a baseline (see `Self::record_samples`),
            // so the history holds eight differenced samples plus the
            // trailing one below, which carries the loop's final reading.
            let mut cpu_ms = 0_u64;
            let mut at = t0;
            for delta_ms in [20_u64, 120, 50, 160, 70, 140, 40, 100, 130] {
                cpu_ms += delta_ms;
                at += Duration::from_secs(2);
                let mut warming_up = pending_row.clone();
                warming_up.cpu_ms = Some(cpu_ms);
                app.update(Msg::Snapshot {
                    rows: vec![warming_up, overridden_row.clone(), plain_row.clone()],
                    at,
                });
            }
            // The returned row has to carry the same reading the loop's
            // last snapshot sent, not the pre-loop clone: this used to
            // mutate `warming_up` only, leaving `pending_row.cpu_ms` at
            // `None` forever.
            pending_row.cpu_ms = Some(cpu_ms);
            vec![pending_row, overridden_row, plain_row]
        }
        // The one sheep every sheep-pane scene draws, `web`, run through
        // six real polls two seconds apart, cpu_ms and memory_bytes both
        // rising by varying deltas: task 4's counter differencing needs a
        // poll to differ against, so a scene built from a single snapshot
        // would draw an idle-looking chart while looking fine, the same
        // trap `Scene::CfgDrift`'s own fixture above exists to avoid.
        Scene::SheepPane
        | Scene::SheepPaneCpuOnly
        | Scene::SheepPaneSparklines
        | Scene::SheepPaneShort => {
            let mut at = t0;
            let mut row = sheep(
                20,
                "web",
                ProcStatus::Online,
                Some(48_500),
                0,
                Some(0.0),
                Some(10 << 20),
                Some("edge"),
            );
            row.max_memory = Some(64 << 20);
            for (cpu_ms, memory) in [
                (400_u64, 14 << 20),
                (900, 20 << 20),
                (1_300, 28 << 20),
                (2_000, 34 << 20),
                (2_400, 30 << 20),
            ] {
                at += Duration::from_secs(2);
                row.cpu_ms = Some(cpu_ms);
                row.memory_bytes = Some(memory);
                app.update(Msg::Snapshot {
                    rows: vec![row.clone()],
                    at,
                });
            }
            vec![row]
        }
        _ => {
            let mut rows = vec![
                sheep(
                    0,
                    "web",
                    ProcStatus::Online,
                    Some(48_211),
                    0,
                    Some(3.4),
                    Some(182 << 20),
                    Some("edge"),
                ),
                sheep(
                    1,
                    "web",
                    ProcStatus::Online,
                    Some(48_212),
                    0,
                    Some(2.9),
                    Some(178 << 20),
                    Some("edge"),
                ),
                sheep(
                    2,
                    "api",
                    ProcStatus::Online,
                    Some(48_219),
                    1,
                    Some(7.1),
                    Some(241 << 20),
                    Some("edge"),
                ),
                sheep(
                    3,
                    "billing-reconciliation-worker",
                    ProcStatus::Online,
                    Some(48_230),
                    0,
                    Some(0.8),
                    Some(96 << 20),
                    None,
                ),
                sheep(
                    4,
                    "cron",
                    ProcStatus::Online,
                    Some(48_233),
                    0,
                    Some(0.1),
                    Some(8 << 20),
                    None,
                ),
                sheep(
                    5,
                    "metrics",
                    ProcStatus::Online,
                    Some(48_240),
                    0,
                    Some(0.4),
                    Some(11 << 20),
                    None,
                ),
            ];
            // `log_row`'s on-disk size had never rendered anywhere in the
            // gallery, because every fixture's
            // `out_file`/`err_file` name a path (`/home/ada/.shep/logs/...`)
            // that never exists on the machine running the test, so
            // `fs::metadata` always failed silently. `HealthyWide`'s
            // selected sheep, `api`, points at two real files instead,
            // committed under `crates/shep-cli/tests/fixtures/gallery-logs/`,
            // fixed at 1024 bytes each so the rendered size (`2.0K`) is the
            // same on every machine and every run.
            //
            // The path is relative rather than the fictional absolute shape
            // every other fixture uses: cargo sets a test binary's cwd to
            // its own crate's manifest directory on every platform, so
            // `fs::metadata` resolves this same string against the same
            // real file wherever the gallery is regenerated. An absolute
            // path would either stay fictional (the `/home/ada/...` shape,
            // never real) or, made real, would have to embed either a
            // random tempdir name (breaking `write_the_gallery`'s
            // idempotency: it must diff clean run twice) or the actual
            // checkout's home directory, which must never land in a file
            // this repository commits.
            //
            // Applied here, before `poll_twice` runs, rather than after: the
            // two polls below are this scene's only delivery into
            // `self.flock` now, so a patch applied afterward would never
            // reach it.
            if which == Scene::HealthyWide
                && let Some(api) = rows.iter_mut().find(|sheep| sheep.id == 2)
            {
                api.out_file = Some("tests/fixtures/gallery-logs/api-out.log".to_string());
                api.err_file = Some("tests/fixtures/gallery-logs/api-err.log".to_string());
            }
            poll_twice(
                &mut app,
                t0,
                rows,
                &[
                    (0, 90, 158),
                    (1, 70, 128),
                    (2, 150, 292),
                    (3, 10, 26),
                    (4, 5, 7),
                    (5, 10, 18),
                ],
            )
        }
    };

    // `Empty` and the settings-dogs trio never call `App::update` while
    // building `flock` above: `Empty`'s flock is empty and the dogs table
    // carries no CPU column, so neither needs `poll_twice`'s two-poll
    // shape, and this is the only snapshot either of them gets. Every other
    // scene already delivered its own final state through `poll_twice` (or,
    // for `CfgDrift` and the sheep-pane group, its own inline loop);
    // resending the same rows here at `t0`, older than that already-applied
    // poll, would difference against a zero or negative window and corrupt
    // the very last sample `poll_twice` just recorded back to `0.0` or
    // `None`: the bug this round exists to fix, not reintroduce.
    if matches!(
        which,
        Scene::Empty | Scene::SettingsDogs | Scene::SettingsNarrow | Scene::SettingsShort
    ) {
        app.update(Msg::Snapshot {
            rows: flock,
            at: t0,
        });
    }
    app.update(Msg::Tick {
        now: t0 + Duration::from_secs(7),
    });

    // Every `Keymap*` scene uses the healthy flock fixture above (the
    // default arm of the match) and raises the overlay right after: `h`
    // toggles `App::keymap_open` and nothing else, so it does not matter
    // that this runs ahead of the selection, the host sample or (for
    // `KeymapFrozen`) the freeze below.
    if which.is_keymap() {
        app.update(Msg::Key(KeyPress::Help));
    }

    // Selects `api` (id 2) so the panes below describe a fixed sheep,
    // walked by id since the table sorts by name. Skipped where there is
    // no flock, no pane below the table, or the cursor belongs elsewhere
    // (`Grouped`, `Folds`, and the three settings scenes with no id 2).
    if !matches!(
        which,
        Scene::Empty
            | Scene::Narrow
            | Scene::TooNarrow
            | Scene::TableOnly
            | Scene::Grouped
            | Scene::Folds
            | Scene::WithDogs
            | Scene::MemCeiling
            | Scene::CfgDrift
            | Scene::SettingsDogs
            | Scene::SettingsNarrow
            | Scene::SettingsShort
            | Scene::SheepPane
            | Scene::SheepPaneCpuOnly
            | Scene::SheepPaneSparklines
            | Scene::SheepPaneShort
    ) {
        select_id(&mut app, 2);
    }

    // Onto `web`'s group header, which is the one row in the gallery that is
    // not a sheep. Every pane below the table renders its own group state
    // from it: the rollup line, the per-instance lamb sentence, and the
    // feed's refusal to pick an instance to tail.
    if which == Scene::Grouped {
        select_group(&mut app, "web");
    }

    // `Folds` presses `F` to switch the table into the fold view, collapses
    // `batch` (the smallest fold, so `z`'s effect is visible without hiding
    // much), and parks the cursor on `edge`'s own header, the fold that
    // carries the grouped app.
    if which == Scene::Folds {
        app.update(Msg::Key(KeyPress::FoldView));
        select_fold(&mut app, "batch");
        app.update(Msg::Key(KeyPress::Collapse));
        select_fold(&mut app, "edge");
    }

    // `LambsUnknown` wants `cron`, id 4, instead.
    if which == Scene::LambsUnknown {
        select_id(&mut app, 4);
    }

    // `WithDogs` parks on the silent adopted dog, id 91, the row this
    // scene exists to show.
    if which == Scene::WithDogs {
        select_id(&mut app, 91);
    }

    // `MemCeiling` parks on `web-hot`, id 1, the row at 94% of its
    // ceiling: the butter warning this scene exists to show.
    if which == Scene::MemCeiling {
        select_id(&mut app, 1);
    }

    // `CfgDrift` parks on `web`, id 10, the row carrying the pending
    // fields: the detail pane's own `cfg !2 pending` cell only renders
    // for the selected sheep.
    if which == Scene::CfgDrift {
        select_id(&mut app, 10);
    }

    // Every sheep-pane scene parks on `web`, id 20 (the only row in its
    // own flock), opens the pane the same way the event loop does (`Enter`
    // on the selected row), and answers the config request it fires so the
    // config column has real fields to draw rather than "reading config…".
    if matches!(
        which,
        Scene::SheepPane
            | Scene::SheepPaneCpuOnly
            | Scene::SheepPaneSparklines
            | Scene::SheepPaneShort
    ) {
        select_id(&mut app, 20);
        app.update(Msg::Key(KeyPress::Confirm));
        app.update(Msg::Replied {
            sent: Sent::SheepConfig {
                name: "web".to_string(),
            },
            result: Ok(Response::SheepConfig(Box::new(sheep_pane_config_view()))),
        });
    }

    match which {
        Scene::FilterEditing | Scene::FilterNoMatch | Scene::FilterActive => {
            app.update(Msg::Key(KeyPress::FilterStart));
            let query = if which == Scene::FilterNoMatch {
                "zzz"
            } else {
                "web"
            };
            for typed in query.chars() {
                app.update(Msg::Key(KeyPress::TextChar(typed)));
            }
            if which == Scene::FilterActive {
                app.update(Msg::Key(KeyPress::TextApply));
            }
        }
        _ => {}
    }

    // Every live scene gets a host sample, frozen included: without a
    // baseline sample the strip would read "not read yet" regardless of
    // the freeze guard. `Scene::Frozen` below sends a second, older
    // sample that exercises the guard itself.
    if which == Scene::HostUnknown {
        app.update(Msg::Host { sample: None });
    } else {
        app.update(Msg::Host {
            sample: Some(HostSample {
                load: (2.31, 4.10, 3.88),
                cores: Some(10),
                memory_total_bytes: 32 << 30,
                memory_used_bytes: 12 * (1 << 30) + (410 << 20),
                uptime_seconds: 6 * 86_400 + 3 * 3_600,
            }),
        });
    }

    app.update(Msg::Bleats {
        tail: feed_for(which),
    });

    // Opens the pane on `api` (already selected above) and stacks all
    // three filter axes: `o` once for `out`, `m` four times for `None ->
    // Trace -> Debug -> Info -> Warn`, then a regex typed into the match
    // box. `w` last, since it toggles independently of the filters and
    // this is the one fixture line worth wrapping.
    if which == Scene::Bleats {
        app.update(Msg::Key(KeyPress::Bleats));
        app.update(Msg::Key(KeyPress::StreamCycle));
        for _ in 0..4 {
            app.update(Msg::Key(KeyPress::LevelCycle));
        }
        app.update(Msg::Key(KeyPress::FilterStart));
        for typed in "/retry|jitter/".chars() {
            app.update(Msg::Key(KeyPress::TextChar(typed)));
        }
        app.update(Msg::Key(KeyPress::TextApply));
        app.update(Msg::Key(KeyPress::WrapToggle));
    }

    // Applied while the link is still `Live`: `on_lambs` refuses once it
    // is `Lost`, the same guard `Msg::Bleats` carries.
    if matches!(which, Scene::Lambs | Scene::Frozen) {
        app.update(Msg::Replied {
            sent: Sent::Lambs { id: 2 },
            result: Ok(Response::Described(vec![
                ProcessInfo::builder(2, "api", ProcStatus::Online)
                    .pid(Some(48_219))
                    .lambs(Some(vec![
                        Lamb::new(48_220, "node"),
                        Lamb::new(48_221, "node"),
                        Lamb::new(48_222, "node"),
                    ]))
                    .build(),
            ])),
        });
    }

    // `cron` (id 4) has no pid, so the shepherd's walk never ran and
    // `lambs_for(4)` stays `None`.
    if which == Scene::LambsUnknown {
        app.update(Msg::Replied {
            sent: Sent::Lambs { id: 4 },
            result: Ok(Response::Described(vec![
                ProcessInfo::builder(4, "cron", ProcStatus::Stopped)
                    .lambs(None)
                    .build(),
            ])),
        });
    }

    // `Msg::Host` and the `SelectDown`s run before `Msg::Frozen`: the
    // reducer refuses both once frozen.
    match which {
        Scene::Retrying => {
            app.update(Msg::Retrying { attempt: 3 });
        }
        Scene::Frozen | Scene::KeymapFrozen => {
            app.update(Msg::Frozen {
                at_local: "2026-08-14 14:32:07".to_string(),
                why: super::view::fixtures::FROZEN_WHY.to_string(),
            });
            // Sent after `Msg::Frozen`, with a load average that varies
            // with `age`: the guard's refusal keeps
            // `the_frozen_frame_does_not_move_however_long_the_link_stays_gone`
            // byte-identical across ages.
            app.update(Msg::Host {
                sample: Some(HostSample {
                    load: (2.31 + age.as_secs_f64(), 4.10, 3.88),
                    cores: Some(10),
                    memory_total_bytes: 32 << 30,
                    memory_used_bytes: 12 * (1 << 30) + (410 << 20),
                    uptime_seconds: 6 * 86_400 + 3 * 3_600,
                }),
            });
        }
        Scene::Refused => {
            app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
        }
        _ => {}
    }

    // The last tick, `age` after the opening snapshot: advances the
    // uptime column on a live scene, and does nothing on the frozen one,
    // since the reducer stops accepting `now` once the link is lost.
    app.update(Msg::Tick { now: t0 + age });

    // Applied after the last tick: `scene()` renders at `age` = 600s past
    // `CONFIRM_EXPIRY` (10s), so an armed confirm built before the tick
    // would already show expired.
    match which {
        Scene::ActionRefusedOffline => {
            // The link must stop being live before the key is pressed, or
            // `arm` would accept it.
            app.update(Msg::Retrying { attempt: 3 });
            app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
        }
        Scene::Confirm | Scene::Acting | Scene::ActionRefused | Scene::ActionAccepted => {
            app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
            if which != Scene::Confirm {
                app.update(Msg::Key(KeyPress::Confirm));
            }
            if which == Scene::ActionAccepted {
                app.update(Msg::Replied {
                    sent: Sent::Action {
                        verb: ActionVerb::Restart,
                        target: RowKey::Sheep(2),
                        name: "api".to_string(),
                    },
                    result: Ok(Response::Restarted {
                        accepted: vec![restarted_api()],
                        refused: Vec::new(),
                    }),
                });
            }
            if which == Scene::ActionRefused {
                // The sheep leaves the flock while the request is out, which
                // is what makes the daemon's own sentence the true one.
                app.update(Msg::Snapshot {
                    rows: flock_without_api(),
                    at: t0,
                });
                app.update(Msg::Replied {
                    sent: Sent::Action {
                        verb: ActionVerb::Restart,
                        target: RowKey::Sheep(2),
                        name: "api".to_string(),
                    },
                    result: Err(RequestError::Rpc(RpcError {
                        code: RpcErrorCode::NotFound,
                        message: "selector matched no registered sheep".to_string(),
                        daemon_version: None,
                    })),
                });
            }
        }
        _ => {}
    }

    // Applied last, for the same reason: `SettingsConfirm` and `Secrets`
    // each arm a candidate that expires (on `CONFIRM_EXPIRY` or
    // `REVEAL_HOLDS`), so both must be armed after the tick at `age`.
    match which {
        Scene::Secrets => {
            // Opens the secrets pane on `production`: an operator row
            // revealed, a provider group, and a row with a slot
            // elsewhere but not here. `Msg::Revealed` is handed the
            // value directly; the reducer only checks the gate below.
            app.update(Msg::Key(KeyPress::Secrets));
            app.update(Msg::Secrets {
                environment: "production".to_string(),
                result: Ok(Box::new(SecretsModel {
                    environments: vec![
                        "all".to_string(),
                        "ci".to_string(),
                        "production".to_string(),
                    ],
                    rows: vec![
                        SecretRow {
                            key: "DB_PASSWORD".to_string(),
                            source: Source::Operator,
                            in_force: Some("production".to_string()),
                            set_in: vec!["production".to_string()],
                            byte_len: Some("hunter2-not-really".len()),
                            readers: vec![Reader {
                                name: "catcher".to_string(),
                                environment: "production".to_string(),
                                online: true,
                            }],
                        },
                        SecretRow {
                            key: "ELSEWHERE_ONLY".to_string(),
                            source: Source::Operator,
                            in_force: None,
                            set_in: vec!["ci".to_string()],
                            byte_len: None,
                            readers: Vec::new(),
                        },
                        SecretRow {
                            key: "vercel/API_TOKEN".to_string(),
                            source: Source::Namespace("vercel".to_string()),
                            in_force: Some("production".to_string()),
                            set_in: vec!["production".to_string()],
                            byte_len: Some(6),
                            readers: Vec::new(),
                        },
                    ],
                    // Every row's `readers` comes off the muster roll, and
                    // so does this: a model carrying one without the other
                    // is a state `secrets::model` cannot produce, and the
                    // frame would name a reader under a line saying no roll
                    // was ever written.
                    roll_age: Some(Duration::from_secs(184)),
                    allow_read: true,
                    ..SecretsModel::default()
                })),
            });
            app.update(Msg::Key(KeyPress::Reveal));
            app.update(Msg::Revealed {
                key: "DB_PASSWORD".to_string(),
                environment: "production".to_string(),
                value: Some(RevealedValue("hunter2-not-really".to_string())),
            });
        }
        Scene::SettingsFresh => {
            // A fresh document, not a hand-edited snapshot: first run
            // leaves only `[interpreters]`, and `load_settings` is the
            // same reader `run_ui` calls.
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("shep.toml");
            ShepToml::edit(&path, ShepToml::write_starter_interpreters).unwrap();
            let snapshot = load_settings(
                &path,
                std::path::Path::new("/home/ada/.shep/run/shep.sock"),
                (StyleLevel::Full, StyleSource::Default),
            )
            .unwrap();
            app.update(Msg::Key(KeyPress::Settings));
            app.update(Msg::Settings {
                result: Ok(snapshot),
            });
        }
        Scene::SettingsSet => {
            app.update(Msg::Key(KeyPress::Settings));
            app.update(Msg::Settings {
                result: Ok(settings_snapshot_for_gallery()),
            });
        }
        Scene::SettingsConfirm => {
            app.update(Msg::Key(KeyPress::Settings));
            app.update(Msg::Settings {
                result: Ok(settings_snapshot_for_gallery()),
            });
            // The cursor already sits on `log_level`, `Settings::rows`'s
            // first row, so arming it needs no `SelectDown` at all.
            app.update(Msg::Key(KeyPress::Cycle));
        }
        Scene::SettingsTyping => {
            app.update(Msg::Key(KeyPress::Settings));
            app.update(Msg::Settings {
                result: Ok(settings_snapshot_for_gallery()),
            });
            move_settings_cursor_to(&mut app, SettingField::Socket);
            // Opens the editor, seeded with the on-disk value.
            app.update(Msg::Key(KeyPress::Confirm));
            // Trims the seeded value back to a partial path, so the frame
            // shows the editor genuinely mid-type rather than holding the
            // whole, untouched value it opened with.
            for _ in 0..8 {
                app.update(Msg::Key(KeyPress::TextBackspace));
            }
        }
        Scene::SettingsDogs | Scene::SettingsNarrow => {
            app.update(Msg::Key(KeyPress::Settings));
            app.update(Msg::Settings {
                result: Ok(settings_snapshot_with_dog_drift()),
            });
        }
        Scene::SettingsShort => {
            app.update(Msg::Key(KeyPress::Settings));
            app.update(Msg::Settings {
                result: Ok(settings_snapshot_with_dog_drift()),
            });
            // Onto the last row, which is the one a body this short cannot
            // reach without scrolling.
            app.update(Msg::Key(KeyPress::SelectLast));
        }
        Scene::EditPane
        | Scene::EditPaneEdited
        | Scene::EditPaneSqueezed
        | Scene::EditPaneNarrow => {
            // `e` on the selected row (`api`, id 2), the way `ask_for_config`
            // reaches it, then the shepherd's own reply.
            app.update(Msg::Key(KeyPress::Edit));
            app.update(Msg::Replied {
                sent: Sent::SheepConfig {
                    name: "api".to_string(),
                },
                result: Ok(Response::SheepConfig(Box::new(edit_pane_config_view()))),
            });
            // Two edits, driven by real key presses the way
            // `select_field` always is: `cwd`, which needs a respawn, and
            // `max_memory`, which lands at once, so the pending section
            // and the title's own count both have something to show.
            if which == Scene::EditPaneEdited {
                for (key, typed) in [("cwd", "/srv/api"), ("max_memory", "256")] {
                    select_field(&mut app, key);
                    app.update(Msg::Key(KeyPress::Confirm));
                    for character in typed.chars() {
                        app.update(Msg::Key(KeyPress::TextChar(character)));
                    }
                    app.update(Msg::Key(KeyPress::TextApply));
                }
            }
        }
        Scene::CloseDialog
        | Scene::CloseDialogFloor
        | Scene::CloseDialogNarrow
        | Scene::CloseDialogParked => {
            // The same `e` on `api` (id 2) that opens every edit-pane
            // scene, but replied with a view that already carries one
            // parked field, `listen_timeout`, so the close dialog has
            // something to say about the parked half without any edit of
            // the operator's own.
            app.update(Msg::Key(KeyPress::Edit));
            app.update(Msg::Replied {
                sent: Sent::SheepConfig {
                    name: "api".to_string(),
                },
                result: Ok(Response::SheepConfig(Box::new(close_dialog_config_view()))),
            });
            // `cwd` and `err_file` both need a respawn, so the dialog's
            // heading names an unsent count alongside the parked one.
            // `CloseDialogParked` files neither, relying on the fixture's
            // own parked field alone.
            if which != Scene::CloseDialogParked {
                for (key, typed) in [("cwd", "/srv/api"), ("err_file", "/var/log/api/err.log")] {
                    select_field(&mut app, key);
                    app.update(Msg::Key(KeyPress::Confirm));
                    for character in typed.chars() {
                        app.update(Msg::Key(KeyPress::TextChar(character)));
                    }
                    app.update(Msg::Key(KeyPress::TextApply));
                }
            }
            // Raises the dialog: `esc` stops writing on its own and asks
            // first, which is the whole point of this frame.
            app.update(Msg::Key(KeyPress::Escape));
        }
        _ => {}
    }

    let (width, height) = which.size();
    // The same call `run_ui` makes before every draw. Without it
    // `Viewport::rows` stays zero, which means unlimited, so a guard on a
    // scrolled screen never triggers.
    app.note_body_rows(body_rows(Rect::new(0, 0, width, height)));
    app.note_body_width(width);
    let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
    terminal.draw(|frame| draw(&app, frame)).unwrap();
    terminal.backend().buffer().clone()
}

/// The bleats feed each scene is given, before `Msg::Bleats` carries it in.
///
/// Most scenes: six ordinary `Stream::Out` lines, no missed lines or
/// bytes.
///
/// `FeedGap`: thirty lines, `missed_lines: 500`, `missed_bytes:
/// 4_012_000`, so the header reads both a dropped-lines and a
/// never-read-bytes count.
///
/// `FeedMissing`: no lines, no counts, and a `note` mirroring
/// [`super::tail::read`]'s wording for a log file that was never created.
///
/// `WithDogs`: the selected row is the adopted `log-rotate` dog, so its
/// lines say what a log-rotate dog says rather than the default fixture's
/// web-server lines.
///
/// `Bleats`: sixteen lines, ten `out` and six `err`, eight carrying a level
/// word and eight carrying none, one of them 153 characters long. Built to
/// be filtered and wrapped, not read raw: see [`scene_with`]'s own
/// `Scene::Bleats` arm for the axes it stacks on top.
fn feed_for(which: Scene) -> Tail {
    match which {
        // Mirrors `run_ui`: an empty flock has no selected row, so no
        // `tail::read` call, just the pane's own "no sheep is selected"
        // header.
        Scene::Empty => Tail::default(),
        Scene::WithDogs => Tail {
            lines: [
                "rotated /var/log/api/access.log -> access.log.1",
                "compressed access.log.1 (4.2M -> 380K)",
                "pruned 2 archives older than 14 days",
                "next rotation in 6h",
            ]
            .into_iter()
            .map(|text| TailLine {
                stream: Stream::Out,
                text: text.to_string(),
            })
            .collect(),
            missed_lines: 0,
            missed_bytes: 0,
            read_bytes: 256,
            note: None,
        },
        Scene::FeedGap => Tail {
            lines: (0..30)
                .map(|n| TailLine {
                    stream: Stream::Out,
                    text: format!("GET /v1/orders/{n} 200 {}ms", 8 + n % 40),
                })
                .collect(),
            missed_lines: 500,
            missed_bytes: 4_012_000,
            read_bytes: 65_536,
            note: None,
        },
        Scene::FeedMissing => Tail {
            lines: Vec::new(),
            missed_lines: 0,
            missed_bytes: 0,
            read_bytes: 0,
            note: Some("this sheep has not written a log in this $SHEP_HOME".to_string()),
        },
        // Ten `out` lines and six `err`, eight carrying a real level word
        // (three `WARN`, two `DEBUG`, two `ERROR`, one `INFO`) and eight
        // carrying none, so the level axis has both a floor to apply and
        // unclassifiable lines to exempt from it. One line, the `WARN
        // retrying...` one, is 153 characters: long enough that
        // `Scene::Bleats`'s 100-column frame wraps it onto two rows.
        Scene::Bleats => Tail {
            lines: [
                (Stream::Out, "listening on 0.0.0.0:8080"),
                (
                    Stream::Err,
                    "WARN connection pool nearing capacity: 47/50 in use",
                ),
                (Stream::Out, "GET /v1/orders 200 12ms"),
                (
                    Stream::Out,
                    "WARN retrying upstream payment gateway after a timeout, backing off \
                     500ms before trying again with jitter added so the whole fleet does \
                     not retry at once",
                ),
                (
                    Stream::Err,
                    "INFO shutting down worker 2 for a rolling restart",
                ),
                (Stream::Out, "DEBUG cache warmed 128 keys in 4ms"),
                (Stream::Out, "POST /v1/orders 201 88ms"),
                (
                    Stream::Err,
                    "ERROR failed to write session cache: disk quota exceeded",
                ),
                (Stream::Out, "connection pool: 14/50 in use"),
                (
                    Stream::Out,
                    "ERROR panic recovered in worker 3: index out of bounds",
                ),
                (Stream::Err, "GET /healthz 200 3ms"),
                (Stream::Out, "GET /v1/orders/8821 200 9ms"),
                (Stream::Err, "DEBUG flushing metrics buffer"),
                (Stream::Out, "POST /v1/orders 500 210ms"),
                (
                    Stream::Err,
                    "WARN queue depth crossed 200, backpressure engaged",
                ),
                (Stream::Out, "GET /v1/orders/9013 200 7ms"),
            ]
            .into_iter()
            .map(|(stream, text)| TailLine {
                stream,
                text: text.to_string(),
            })
            .collect(),
            missed_lines: 0,
            missed_bytes: 0,
            read_bytes: 2048,
            note: None,
        },
        _ => Tail {
            lines: [
                "listening on 0.0.0.0:8080",
                "GET /healthz 200 3ms",
                "GET /v1/orders 200 44ms",
                "POST /v1/orders 201 88ms",
                "GET /v1/orders/8821 200 9ms",
                "connection pool: 14/50 in use",
            ]
            .into_iter()
            .map(|text| TailLine {
                stream: Stream::Out,
                text: text.to_string(),
            })
            .collect(),
            missed_lines: 0,
            missed_bytes: 0,
            read_bytes: 512,
            note: None,
        },
    }
}

/// One row's worth of shepherd reply, spelled out so each scene reads as
/// a plausible flock rather than six copies of one sheep.
///
/// The two log paths are derived from `name` and `id` rather than taken
/// as parameters: this already carries
/// `#[allow(clippy::too_many_arguments)]` at eight.
#[allow(clippy::too_many_arguments)]
fn sheep(
    id: u32,
    name: &str,
    status: ProcStatus,
    pid: Option<u32>,
    restarts: u32,
    cpu: Option<f32>,
    memory: Option<u64>,
    fold: Option<&str>,
) -> ProcessInfo {
    ProcessInfo::builder(id, name, status)
        .pid(pid)
        .restarts(restarts)
        .uptime_ms(4_512_000 + u64::from(id) * 91_000)
        .cpu_percent(cpu)
        .memory_bytes(memory)
        .fold(fold.map(str::to_string))
        .out_file(Some(format!("/home/ada/.shep/logs/{name}-{id}-out.log")))
        .err_file(Some(format!("/home/ada/.shep/logs/{name}-{id}-err.log")))
        // Derived from `status`, not a ninth parameter: a sheep that is
        // not running always has a reason it stopped, so no scene can
        // depict one with a blank EXIT column.
        .last_exit(match status {
            // Crashed on its own, and a restart is either pending or spent.
            ProcStatus::Errored | ProcStatus::WaitingRestart => Some(ExitInfo {
                code: Some(1),
                signal: None,
            }),
            // Stopped because shep asked it to, which is a signal.
            ProcStatus::Stopped => Some(ExitInfo {
                code: None,
                signal: Some(15),
            }),
            // Running, or on its way in or out: nothing has exited yet.
            ProcStatus::Online | ProcStatus::Starting | ProcStatus::Stopping => None,
        })
        .build()
}

/// An online sheep with `max_memory` set, [`sheep`]'s own default. Only
/// `Scene::MemCeiling` needs one, so this stays a thin wrapper rather than
/// a ninth parameter on `sheep` every other caller would have to pass
/// `None` for.
fn sheep_with_ceiling(id: u32, name: &str, memory: u64, ceiling: u64) -> ProcessInfo {
    let mut info = sheep(
        id,
        name,
        ProcStatus::Online,
        Some(48_300 + id),
        0,
        Some(2.0),
        Some(memory),
        Some("edge"),
    );
    info.max_memory = Some(ceiling);
    info
}

/// `web`'s own config, the way the shepherd would answer
/// `Request::SheepConfig`: every sheep-pane scene's config column reads
/// this rather than sitting on "reading config…".
fn sheep_pane_config_view() -> SheepConfigView {
    let mut config = AppConfig {
        name: "web".to_string(),
        script: "./srv".to_string(),
        args: vec!["--port".to_string(), "8080".to_string()],
        max_restarts: 32,
        instances: 3,
        ..AppConfig::default()
    };
    config
        .env
        .insert("DB_HOST".to_string(), "db.internal".to_string());
    config
        .env
        .insert("LOG_LEVEL".to_string(), "debug".to_string());
    SheepConfigView::new(config, Vec::new(), Vec::new())
}

/// One instance of a clustered app: the row a shepherd reports for slot
/// `slot` of `name`.
///
/// Takes an explicit `uptime_ms` rather than deriving it from the id like
/// [`sheep`] does: a group row's uptime is the minimum across its
/// members, and grouping should not depend on id arithmetic.
fn instance(
    id: u32,
    name: &str,
    slot: u32,
    restarts: u32,
    cpu: f32,
    memory: u64,
    uptime_ms: u64,
) -> ProcessInfo {
    ProcessInfo::builder(id, name, ProcStatus::Online)
        .instance(Some(slot))
        .pid(Some(48_400 + id))
        .restarts(restarts)
        .uptime_ms(uptime_ms)
        .cpu_percent(Some(cpu))
        .memory_bytes(Some(memory))
        .fold(Some("edge".to_string()))
        .out_file(Some(format!("/home/ada/.shep/logs/{name}-{id}-out.log")))
        .err_file(Some(format!("/home/ada/.shep/logs/{name}-{id}-err.log")))
        .build()
}

/// The row `ActionAccepted`'s reply carries: `api` at id 2, restarted.
///
/// Pid 48299, not the listing's 48219: a matching pid would pass whether
/// the reply's row was upserted or silently ignored.
fn restarted_api() -> ProcessInfo {
    sheep(
        2,
        "api",
        ProcStatus::Online,
        Some(48_299),
        2,
        Some(7.1),
        Some(241 << 20),
        Some("edge"),
    )
}

/// The default six-sheep flock `scene_with`'s `_` arm builds, with id 2
/// (`api`) removed: five rows, ids 0, 1, 3, 4, 5.
fn flock_without_api() -> Vec<ProcessInfo> {
    vec![
        sheep(
            0,
            "web",
            ProcStatus::Online,
            Some(48_211),
            0,
            Some(3.4),
            Some(182 << 20),
            Some("edge"),
        ),
        sheep(
            1,
            "web",
            ProcStatus::Online,
            Some(48_212),
            0,
            Some(2.9),
            Some(178 << 20),
            Some("edge"),
        ),
        sheep(
            3,
            "billing-reconciliation-worker",
            ProcStatus::Online,
            Some(48_230),
            0,
            Some(0.8),
            Some(96 << 20),
            None,
        ),
        sheep(
            4,
            "cron",
            ProcStatus::Online,
            Some(48_233),
            0,
            Some(0.1),
            Some(8 << 20),
            None,
        ),
        sheep(
            5,
            "metrics",
            ProcStatus::Online,
            Some(48_240),
            0,
            Some(0.4),
            Some(11 << 20),
            None,
        ),
    ]
}

/// One dog process: `id` and `name` as `dog_rows`'s join key. `handshook`
/// carries the three-state signal a real listing does: `None` reads
/// `online`, `Some(false)` reads `silent`, per
/// [`crate::vocabulary::Reported::of`].
fn dog_sheep(id: u32, name: &str, source: DogSource, handshook: Option<bool>) -> ProcessInfo {
    ProcessInfo::builder(id, name, ProcStatus::Online)
        .pid(Some(90_000 + id))
        .dog(Some(source))
        .handshook(handshook)
        .build()
}

/// Walks the settings screen's cursor onto `field`'s row with real
/// `SelectDown` keypresses.
///
/// # Panics
///
/// If the settings screen is not open.
#[track_caller]
fn move_settings_cursor_to(app: &mut App, field: SettingField) {
    let target = app
        .settings()
        .expect("the settings screen must already be open")
        .rows()
        .iter()
        .position(|row| *row == SettingsRow::Scalar(field))
        .expect("field is one of the six scalar rows Settings::rows always carries");
    for _ in 0..target {
        app.update(Msg::Key(KeyPress::SelectDown));
    }
}

/// A settings snapshot with `log_level`, `socket`, `max_cron_sleep` and
/// `style_level` declared in `shep.toml`, and `log_json`/`allow_control`
/// left at their compiled defaults: the mixed state
/// [`Scene::SettingsSet`] shows, reused by [`Scene::SettingsConfirm`] and
/// [`Scene::SettingsTyping`].
fn settings_snapshot_for_gallery() -> SettingsSnapshot {
    let config = |value: &str| ScalarView {
        value: value.to_string(),
        source: StyleSource::Config,
    };
    let default = |value: &str| ScalarView {
        value: value.to_string(),
        source: StyleSource::Default,
    };
    SettingsSnapshot {
        log_level: config("warn"),
        log_json: default("false"),
        socket: config("/home/ada/.shep/run/shep.sock"),
        max_cron_sleep: config("30s"),
        allow_control: default("false"),
        style_level: config("full"),
        // The document declares it, so the file and resolved value agree.
        style_level_in_file: Some("full".to_string()),
        dogs: vec![
            DogView {
                name: "bark".to_string(),
                enabled: false,
                adopted_path: None,
            },
            DogView {
                name: "metrics".to_string(),
                enabled: true,
                adopted_path: None,
            },
        ],
    }
}

/// [`settings_snapshot_for_gallery`]'s scalars, with `dogs` replaced by
/// the three-way drift [`Scene::SettingsDogs`] shows: `otel` running
/// while the file disables it, `ledger` enabled and absent from the
/// flock, and `bark` enabled with `handshook: Some(false)`, so the join
/// reads it `silent`.
fn settings_snapshot_with_dog_drift() -> SettingsSnapshot {
    SettingsSnapshot {
        dogs: vec![
            // Both carry a real path: a non-built-in dog with
            // `adopted_path: None` is not a row `load_settings` can
            // produce from a document shep wrote.
            DogView {
                name: "otel".to_string(),
                enabled: false,
                adopted_path: Some(PathBuf::from("/usr/local/bin/shep-otel")),
            },
            DogView {
                name: "ledger".to_string(),
                enabled: true,
                adopted_path: Some(PathBuf::from("/opt/ledger/bin/dog")),
            },
            DogView {
                name: "bark".to_string(),
                enabled: true,
                adopted_path: None,
            },
        ],
        ..settings_snapshot_for_gallery()
    }
}

/// `api`'s config as the shepherd would answer it, for the four
/// editing-pane scenes: two env keys whose values never reach the view (the
/// pane's own `(set)` rendering is what a scene checks, not a real secret),
/// and no edits, overrides or pending fields of its own. [`Scene::EditPane`]
/// draws it fresh; [`Scene::EditPaneEdited`] files two edits on top of it.
fn edit_pane_config_view() -> SheepConfigView {
    let mut config = AppConfig {
        name: "api".to_string(),
        script: "./api/server.js".to_string(),
        args: vec!["--port".to_string(), "8080".to_string()],
        max_restarts: 32,
        instances: 1,
        ..AppConfig::default()
    };
    config
        .env
        .insert("NODE_ENV".to_string(), "production".to_string());
    config
        .env
        .insert("DATABASE_URL".to_string(), "postgres://db/api".to_string());
    SheepConfigView::new(config, Vec::new(), Vec::new())
}

/// `api`'s config for the close-dialog scenes: the same fields
/// [`edit_pane_config_view`] carries, plus `listen_timeout` already
/// parked, so `CloseDialogParked` has something to name without any edit
/// of the operator's own, and the boxed scenes show both halves of the
/// dialog's heading at once.
fn close_dialog_config_view() -> SheepConfigView {
    let mut config = AppConfig {
        name: "api".to_string(),
        script: "./api/server.js".to_string(),
        args: vec!["--port".to_string(), "8080".to_string()],
        max_restarts: 32,
        instances: 1,
        ..AppConfig::default()
    };
    config
        .env
        .insert("NODE_ENV".to_string(), "production".to_string());
    config
        .env
        .insert("DATABASE_URL".to_string(), "postgres://db/api".to_string());
    SheepConfigView::new(config, Vec::new(), vec!["listen_timeout".to_string()])
}

/// The header both gallery files open with.
///
/// Not a doc comment on the test: this text is read by a person opening
/// `docs/lookout/frames.txt` with no context at all, and it is the only
/// place that says where those frames came from.
const GALLERY_PREAMBLE: &str = "shep lookout frames
===================

These are real frames, rendered headlessly through ratatui's TestBackend by

    cargo test -p shep --lib --all-features -- --ignored write_the_gallery

Nothing here is a mockup.

frames.ansi renders all fifty-eight scenes through the same coloured
palette the pinned `.snap` tests use; read it with `less -R`. frames.txt
renders the same fifty-eight scenes through the flattened NO_COLOR palette
instead, the one an operator with $NO_COLOR set or a 16-colour terminal
actually gets. The two files are deliberately different pictures of the
same dashboard, not one file with the colour removed.

All four panes are here: the flock table (the spine), the host-usage strip,
the sheep detail pane and the bleats feed. The selected row is a painted
gutter in frames.ansi; in frames.txt it falls back to a `>` marker, since
the NO_COLOR palette has no ground to paint with. Every pane below the
table describes whatever that row is: one sheep usually, and a rollup with
no single log where the cursor sits on a group or a fold header.

The feed reads the selected sheep's log files from disk and re-reads them with
each flock listing. It is not a live subscription, and it says so on its own
header line: `out then err` because the two files are shown end to end with no
interleaving, and `re-read with each listing` because a two-second gap in this
pane is the refresh, not the sheep.

When the pane cannot show everything, the header says what went instead. Lines
it read and dropped are counted exactly; bytes below its 64 KiB window were
never read at all, so those are reported in bytes, because nothing counted the
lines in them and guessing would be worse than saying so.

Four frames show the editing pane, `e` from the dashboard, on a sheep's own
row: fresh at the 160x48 design target, the same pane with two edits filed
(one of them needing a respawn), and the same fresh pane at 120 and at 88
columns, where the explanation panel and the LANDS column trade places as
the width falls.

The last eight are the keymap overlay, `h` or `?` from any body. Boxed and
centred at the 160x48 target, at 130 where the border only just fits,
borderless at 129 one column below that floor, at 100 where DOING drops to a
bank of its own, and at 70 where two columns are all that fit. Three more
change what the bottom line says rather than the layout: a frozen dashboard,
a read-only one, and a terminal too short for the box at all.

Before those, four show the close dialog `esc` raises over the editing pane
when a change is filed the running child cannot take. Boxed and centred at the 160x48
target, the same at 90 where the border only just fits, borderless at 89 one
column below its floor, and the parked-only heading on a sheep whose fields
were written before the pane was opened.

Before those are the four sheep-pane scenes, `↵` on a sheep, then the
secrets pane, `S`, and before them the full-screen bleats pane, `b` from
the dashboard. The seven before
that are the settings screen, `s` from the dashboard. It owns the whole body
between the title and the status bar rather than sharing it
with the flock table, so a fresh $SHEP_HOME, some scalars declared, an armed
confirm, the socket editor mid-type, the dogs table's own drift, the same
screen at 45 columns and the same screen too short to hold every row each get
a frame of their own.
";

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

    /// `sgr`/`render_ansi` were foreground-only before this task: a band's
    /// reverse video and a painted background both came out unstyled.
    #[test]
    fn the_ansi_dump_emits_a_bands_reverse_video_and_a_grounds_background() {
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
        buffer[(0, 0)].set_style(Style::default().add_modifier(Modifier::REVERSED));
        buffer[(1, 0)].set_style(Style::default().bg(Color::Indexed(235)));
        let dump = render_ansi(&buffer);
        assert!(dump.contains("\u{1b}[7m"), "reverse video");
        assert!(dump.contains("\u{1b}[48;5;235m"), "an indexed background");
    }

    /// Nine other tests read frames through this renderer: a regression
    /// here silently changes what they assert.
    #[test]
    fn the_plain_renderer_is_one_line_per_row_and_no_escapes() {
        let text = render_text(&scene(Scene::HealthyWide).1);
        assert_eq!(text.lines().count(), 30);
        assert!(!text.contains('\u{1b}'), "plain means plain");
        for line in text.lines() {
            assert_eq!(line.chars().count(), 120, "every row is the full width");
        }
    }

    /// An unreset colour bleeds into whatever prints next, which for a
    /// file read through `less -R` is the rest of the file.
    #[test]
    fn the_ansi_renderer_colours_the_errored_row_and_always_resets() {
        let ansi = render_ansi(&scene(Scene::Errored).1);
        assert!(
            ansi.contains("\u{1b}[38;5;166m"),
            "bark, on the errored status"
        );
        for line in ansi.lines() {
            assert!(
                line.is_empty() || line.ends_with("\u{1b}[0m"),
                "every line resets before its newline"
            );
        }
    }

    /// The table row for `name`, or `None` if the table does not draw one.
    ///
    /// Strips the leading `>` selection marker first, so a marked and
    /// unmarked row share the same token index.
    ///
    /// The numeric-id guard on token 0 is load bearing: the status bar's
    /// own lines also open `{verb} {name} (id {id})`, so without it this
    /// could match the bar line instead of a table row.
    #[cfg_attr(windows, allow(dead_code))]
    fn row_for<'a>(frame: &'a str, name: &str) -> Option<&'a str> {
        frame.lines().find(|line| {
            let mut tokens = line.trim_start_matches('>').split_whitespace();
            tokens.next().is_some_and(|id| id.parse::<u32>().is_ok()) && tokens.next() == Some(name)
        })
    }

    /// [`coloured_palette`] always paints a ground, so every pinned
    /// snapshot's selected row is a painted gutter rather than a `>` glyph
    /// ([`super::super::view::flock::gutter`]).
    fn gallery_ground() -> ratatui::style::Color {
        coloured_palette()
            .ground()
            .bg
            .expect("the gallery's coloured palette always paints a ground")
    }

    /// Whether row `y` of `buffer` is the selected one: its gutter cell
    /// (column 0) carries [`gallery_ground`].
    fn row_is_selected(buffer: &Buffer, y: u16) -> bool {
        buffer
            .cell((0, y))
            .is_some_and(|cell| cell.bg == gallery_ground())
    }

    /// The rendered text of whichever row of `buffer` is selected, or
    /// `None` if none is (a section header, for instance, is never
    /// selected).
    #[cfg_attr(windows, allow(dead_code))]
    fn selected_line<'a>(text: &'a str, buffer: &Buffer) -> Option<&'a str> {
        (0..buffer.area.height)
            .find(|&y| row_is_selected(buffer, y))
            .and_then(|y| text.lines().nth(usize::from(y)))
    }

    /// How many rows of `buffer`, EXCLUDING the status bar, are painted as
    /// selected: a scene invariant is exactly one, the same invariant a `>`
    /// glyph count used to check.
    ///
    /// The status bar is always the buffer's last row and now carries the
    /// same [`gallery_ground`] the selected row's gutter does
    /// (`Palette::ground`, painted by `view::status` in this task); it is
    /// chrome, not a candidate row, so it is excluded rather than counted.
    fn selected_row_count(buffer: &Buffer) -> usize {
        (0..buffer.area.height.saturating_sub(1))
            .filter(|&y| row_is_selected(buffer, y))
            .count()
    }

    /// The dogs table's own row lookup: unlike [`row_for`], a dog row opens
    /// with `mark` and a name, never a numeric id, so the same "first two
    /// tokens" shape does not apply.
    fn dog_row_for<'a>(frame: &'a str, name: &str) -> Option<&'a str> {
        frame
            .lines()
            .find(|line| line.trim_start_matches('>').split_whitespace().next() == Some(name))
    }

    /// Whether the selected row's name starts with `prefix`.
    ///
    /// Handles truncation: the NAME column's truncated string depends on
    /// terminal width, so `prefix` only needs to fit the eight-column
    /// floor `name_width` never shrinks below. Selection is read off
    /// `buffer`'s own painted gutter ([`row_is_selected`]), not a `>`
    /// glyph the gallery's palette no longer draws.
    #[cfg_attr(windows, allow(dead_code))]
    fn marked_row_name_starts_with(text: &str, buffer: &Buffer, prefix: &str) -> bool {
        selected_line(text, buffer).is_some_and(|line| {
            line.trim_start_matches('>')
                .split_whitespace()
                .nth(1)
                .is_some_and(|name| name.starts_with(prefix))
        })
    }

    /// fails if a scene stops rendering what it is named for.
    ///
    /// Each caption clause in [`Scene::caption`] is pinned by one
    /// assertion here.
    /// The preamble's own scene count matches `Scene::ALL`.
    ///
    /// `write_the_gallery` commits the preamble into
    /// `docs/lookout/frames.txt`, so a wrong count is a document that
    /// miscounts itself for an operator. Spelled out rather than a digit,
    /// which is the form a reader sees.
    #[test]
    fn the_gallery_preamble_counts_the_scenes_it_has() {
        const NUMBERS: [(usize, &str); 25] = [
            (34, "thirty-four"),
            (35, "thirty-five"),
            (36, "thirty-six"),
            (37, "thirty-seven"),
            (38, "thirty-eight"),
            (39, "thirty-nine"),
            (40, "forty"),
            (41, "forty-one"),
            (42, "forty-two"),
            (43, "forty-three"),
            (44, "forty-four"),
            (45, "forty-five"),
            (46, "forty-six"),
            (47, "forty-seven"),
            (48, "forty-eight"),
            (49, "forty-nine"),
            (50, "fifty"),
            (51, "fifty-one"),
            (52, "fifty-two"),
            (53, "fifty-three"),
            (54, "fifty-four"),
            (55, "fifty-five"),
            (56, "fifty-six"),
            (57, "fifty-seven"),
            (58, "fifty-eight"),
        ];
        let spelled = NUMBERS
            .iter()
            .find(|(n, _)| *n == Scene::ALL.len())
            .map(|(_, word)| *word)
            .expect("add the next number to NUMBERS when the gallery outgrows it");
        // `fifty` is a prefix of `fifty-one` through `fifty-eight`, so a bare
        // `contains` passes when the preamble overstates inside its own
        // decade: 50 scenes against a preamble saying "fifty-eight" satisfies
        // `contains("fifty")`. Refusing the hyphen is what makes the match a
        // whole number rather than a prefix of a larger one.
        assert!(
            !GALLERY_PREAMBLE.contains(&format!("{spelled}-")),
            "the preamble spells a larger number than {} scenes: {spelled}-…",
            Scene::ALL.len()
        );
        assert!(
            GALLERY_PREAMBLE.contains(spelled),
            "the preamble says something other than {spelled}, and \
             `write_the_gallery` commits it for an operator to read"
        );
    }

    #[test]
    /// Every [`Scene`] gets a block here except two, checked by walking
    /// `Scene::ALL` against this function's own body rather than trusted
    /// from memory: `Folds`, which has no assertion anywhere pinning what
    /// its caption claims beyond the `.snap` file, and `Secrets`, which
    /// does but in its own dedicated test,
    /// `the_secrets_scene_shows_a_revealed_row_not_a_mask`, below, rather
    /// than duplicated here.
    ///
    /// `cfg(unix)`: one fixture carries a synthetic signalled exit, and
    /// `signal_label` resolves it against the running platform's table.
    /// Windows never sets a signal on `ExitOutcome`, so this arm only
    /// runs against a synthetic fixture like this one; the pinned
    /// artifacts under `docs/lookout/` are unix renderings for the same
    /// reason.
    #[cfg(unix)]
    #[allow(clippy::too_many_lines)] // one assertion block per scene covered, each pinning its own caption clause
    fn every_scene_shows_the_thing_it_is_named_for() {
        // HealthyWide: all three panes at 120x30.
        let wide_buffer = scene(Scene::HealthyWide).1;
        let wide = render_text(&wide_buffer);
        assert!(
            wide.contains("FOLD") && wide.contains("EXIT"),
            "every column fits at 120 columns"
        );
        assert!(
            wide.contains("host  load  ██░░░░░░░░ 2.31 4.10 3.88 / 10 cores"),
            "the host strip"
        );
        assert!(
            wide.contains("SHEEP 2  api"),
            "the detail pane, on the selected sheep, behind its own chip"
        );
        assert!(wide.contains("BLEATS api"), "and the feed, on the same one");
        assert!(
            wide.contains("2.0K on disk"),
            "api's log row points at real, fixed-size fixture files, so the size renders: {wide:?}"
        );
        // `coloured_palette` paints a real ground, so the selected row's
        // gutter is a painted space rather than a `>` glyph
        // (`view::flock::gutter`); checked on the buffer's own background
        // rather than the rendered text, which cannot see one. Two rows
        // carry it, not one: the selected row's gutter, and the status bar
        // painted at the foot of the pane.
        let ground = coloured_palette()
            .ground()
            .bg
            .expect("the gallery's coloured palette always paints a ground");
        let painted_rows = (0..wide_buffer.area.height)
            .filter(|&y| {
                wide_buffer
                    .cell((0, y))
                    .is_some_and(|cell| cell.bg == ground)
            })
            .count();
        assert_eq!(
            painted_rows, 2,
            "the selected row's gutter and the status bar"
        );

        // Grouped: cursor on the group header, which rolls up restarts,
        // CPU and memory and takes the shortest uptime.
        let grouped_buffer = scene(Scene::Grouped).1;
        let grouped = render_text(&grouped_buffer);
        assert!(
            grouped.contains("web \u{d7}3"),
            "the group header names the app and how many instances it has: {grouped:?}"
        );
        assert_eq!(
            grouped
                .lines()
                .filter(|line| line.contains("web \u{d7}3"))
                .count(),
            2,
            "one in the table, one in the detail pane, and nowhere else"
        );
        assert!(
            selected_line(&grouped, &grouped_buffer)
                .is_some_and(|line| line.contains("web \u{d7}3")),
            "the cursor is on the header, not on one of its slots: {grouped:?}"
        );
        assert!(
            row_for(&grouped, "api").is_some(),
            "an ungrouped app sits beside the grouped one: {grouped:?}"
        );
        let rollup = grouped
            .lines()
            .find(|line| line.starts_with("app web "))
            .expect("the detail pane's rollup line");
        // Summed restarts, CPU and memory; uptime is the minimum (300s
        // plus the 600s this frame renders at), not the oldest member's.
        //
        // 9.5% is the three instances' differenced `cpu_ms` readings
        // (3.5 + 2.9 + 3.1) summed, not `ProcessInfo::cpu_percent`: see
        // `poll_twice`'s own doc for why this scene has anything to
        // difference at all.
        assert!(rollup.contains("restarts 3"), "summed restarts: {rollup:?}");
        assert!(rollup.contains("cpu 9.5%"), "summed cpu: {rollup:?}");
        assert!(rollup.contains("mem 540.0M"), "summed memory: {rollup:?}");
        assert!(rollup.contains("uptime 15m"), "the shortest: {rollup:?}");
        assert!(
            !rollup.contains("2h 40m"),
            "not the longest, which is what a max or a first-member read would show: {rollup:?}"
        );
        assert!(
            grouped.contains("lambs  not shown for a group; select one instance"),
            "the detail pane says lambs are per-instance: {grouped:?}"
        );
        assert!(
            grouped.contains("BLEATS web  follows one instance; select one to see its log"),
            "and the feed will not guess which instance to tail: {grouped:?}"
        );
        assert!(
            !grouped.contains("GET /healthz 200 3ms"),
            "with no instance's lines under that sentence: {grouped:?}"
        );

        // WithDogs: the flock table's two sections, sheep then dogs.
        let with_dogs_buffer = scene(Scene::WithDogs).1;
        let with_dogs = render_text(&with_dogs_buffer);
        assert!(
            with_dogs.contains("FLOCK") && with_dogs.contains("DOGS"),
            "both section bands are drawn: {with_dogs:?}"
        );
        assert!(
            row_for(&with_dogs, "bark").is_some_and(|row| row.contains("online")),
            "the built-in dog is healthy: {with_dogs:?}"
        );
        assert!(
            row_for(&with_dogs, "log-rotate").is_some_and(|row| row.contains("silent")),
            "the adopted dog has never handshaken, so it reads silent: {with_dogs:?}"
        );
        assert!(
            marked_row_name_starts_with(&with_dogs, &with_dogs_buffer, "log-rotate"),
            "the cursor is parked on the silent dog: {with_dogs:?}"
        );
        assert!(
            with_dogs.contains("dog adopted"),
            "the detail pane names it adopted, not built-in: {with_dogs:?}"
        );

        // MemCeiling: the MEM/CEIL gauge's three states in one frame.
        let ceiling_buffer = scene(Scene::MemCeiling).1;
        let ceiling = render_text(&ceiling_buffer);
        assert!(
            row_for(&ceiling, "batch-wor…").is_some_and(|row| row.contains("░░░░░░░░░░")),
            "no ceiling configured draws an empty bar: {ceiling:?}"
        );
        assert!(
            row_for(&ceiling, "web-headr…").is_some_and(|row| row.contains("███░░░░░░░")),
            "a quarter of the ceiling fills three of ten cells: {ceiling:?}"
        );
        assert!(
            row_for(&ceiling, "web-hot").is_some_and(|row| row.contains("█████████░")),
            "94 percent of the ceiling fills nine of ten cells: {ceiling:?}"
        );
        assert!(
            marked_row_name_starts_with(&ceiling, &ceiling_buffer, "web-hot"),
            "the cursor is parked on the row at 94 percent: {ceiling:?}"
        );

        // CfgDrift: the CFG column's two markers, plus a CPU history long
        // enough to draw a shape rather than one bar.
        let drift_buffer = scene(Scene::CfgDrift).1;
        let drift = render_text(&drift_buffer);
        assert!(
            row_for(&drift, "web").is_some_and(|row| row.contains("!2")),
            "two fields parked for the next spawn: {drift:?}"
        );
        assert!(
            row_for(&drift, "api").is_some_and(|row| row.contains("*1")),
            "one field an operator set outside the Flockfile: {drift:?}"
        );
        assert!(
            row_for(&drift, "cron").is_some_and(|row| row.contains(" - ")),
            "neither pending nor overridden: {drift:?}"
        );
        let web_row = row_for(&drift, "web").expect("web's own row");
        let spark: std::collections::HashSet<char> = web_row
            .chars()
            .filter(|glyph| ('\u{2581}'..='\u{2588}').contains(glyph))
            .collect();
        assert!(
            spark.len() > 1,
            "ten distinct CPU samples draw more than one sparkline step, not a single repeated bar: {web_row:?}"
        );
        assert!(
            drift.contains("cfg !2 pending"),
            "the detail pane's own cell, for the selected sheep: {drift:?}"
        );

        // Empty: each of the three panes gives its own reason.
        let empty = render_text(&scene(Scene::Empty).1);
        assert!(
            empty.contains("the flock is empty"),
            "the table's own sentence"
        );
        assert!(
            empty.contains("no sheep selected: the flock is empty"),
            "the detail pane's"
        );
        assert!(empty.contains("BLEATS no sheep is selected"), "the feed's");
        // The summary sits after both host readings now, which puts it past
        // the cut at this scene's 100 columns. Asserted as absent rather
        // than dropped: this is the visible cost of grouping the machine's
        // two numbers together, and a later reorder that brings it back
        // should have to come through here and say so. The empty-flock
        // behaviour it used to check is pinned at the unit level, in
        // `host::tests::a_flock_with_no_readings_shows_a_dash_and_not_a_zero`.
        assert!(
            !empty.contains("errored"),
            "the summary is past a 100-column cut once host memory precedes it"
        );

        // Narrow: 51 columns drops FOLD, EXIT, RESTARTS, PID and MEM but
        // keeps CPU and UPTIME.
        let narrow = render_text(&scene(Scene::Narrow).1);
        assert!(narrow.contains("CPU") && narrow.contains("UPTIME"));
        for gone in ["FOLD", "EXIT", "RESTARTS", "PID", "MEM"] {
            assert!(!narrow.contains(gone), "the narrow tier dropped {gone}");
        }
        assert!(narrow.contains("host  load"), "the strip is up at 14 rows");
        assert!(!narrow.contains("BLEATS"), "the feed is not");
        assert!(
            !narrow.contains("SHEEP 0  "),
            "and neither is the detail pane"
        );

        // TooNarrow: below the floor, refuses rather than overlapping.
        let too_narrow = render_text(&scene(Scene::TooNarrow).1);
        let mut lines = too_narrow.lines();
        assert_eq!(lines.next().unwrap().trim_end(), "too small");
        assert_eq!(lines.next().unwrap().trim_end(), "need 33x6");

        // FeedGap: dropped lines and never-read bytes, counted separately.
        let gap = render_text(&scene(Scene::FeedGap).1);
        assert!(
            gap.contains("earlier lines not shown"),
            "the lines it dropped"
        );
        assert!(gap.contains("3.8M"), "the exact figure, not a vague one");
        assert!(gap.contains("never read"), "and what it never looked at");
        assert!(
            !gap.contains("re-read with each listing"),
            "the gap replaces the header"
        );

        // FeedMissing: names the cause rather than sitting blank.
        let missing = render_text(&scene(Scene::FeedMissing).1);
        assert!(missing.contains("has not written a log in this $SHEP_HOME"));

        // NoDetail: the detail pane is the first to go at 20 rows.
        let no_detail = render_text(&scene(Scene::NoDetail).1);
        assert!(
            no_detail.contains("BLEATS api"),
            "the feed stayed, on the selection"
        );
        assert!(no_detail.contains("host  load"), "and so did the strip");
        // The log-path prefix is the detail pane's alone: the feed's body
        // lines are tagged `out  ` too, but carry log text, not a path.
        assert!(
            !no_detail.contains("out  /home/ada/.shep/logs/"),
            "the detail pane went"
        );

        // TableOnly: 12 rows, no optional panes.
        let table_only = render_text(&scene(Scene::TableOnly).1);
        assert!(!table_only.contains("host  load"));
        assert!(!table_only.contains("BLEATS"));
        assert!(table_only.contains("STATUS"), "the table is still there");

        // Cramped: 33 columns, the narrowest terminal that draws.
        let cramped = render_text(&scene(Scene::Cramped).1);
        assert!(cramped.contains('…'), "something truncated, visibly");
        // Not a row-width check, which `render_text` satisfies trivially:
        // "nothing overlaps" means each pane's marker appears exactly once.
        // `contains`, not `starts_with`: the `BLEATS` chip now leads that
        // row.
        for marker in ["host  ", "BLEATS"] {
            assert_eq!(
                cramped.lines().filter(|line| line.contains(marker)).count(),
                1,
                "{marker:?} appears once at 33 columns"
            );
        }
        // The detail pane's merged log row carries no chip of its own, so
        // `starts_with` still works, but the path itself can truncate away
        // at 33 columns; the divider is what survives to identify the row
        // instead.
        assert_eq!(
            cramped
                .lines()
                .filter(|line| line.starts_with("out  ") && line.contains('\u{2502}'))
                .count(),
            1,
            "the detail pane's merged log row appears once at 33 columns"
        );
        assert!(
            cramped.lines().last().unwrap().contains("control enabled"),
            "and the status bar is still the last row"
        );

        // Retrying: every pane keeps describing the last listing.
        let retrying = render_text(&scene(Scene::Retrying).1);
        assert!(retrying.contains("reconnecting"));
        assert!(
            retrying.contains("SHEEP 2  api"),
            "the detail pane is still up"
        );
        assert!(retrying.contains("host  load"), "and so is the strip");

        // Frozen: last known values stay, nothing keeps ticking, and the
        // panel that replaced the two lower panes says what happened.
        let frozen = render_text(&scene(Scene::Frozen).1);
        assert!(frozen.contains("THE SHEPHERD HAS DIED"));
        assert!(
            frozen.contains("host  load  ██░░░░░░░░ 2.31 4.10 3.88 / 10 cores"),
            "the strip kept its LAST values rather than blanking"
        );
        assert!(
            frozen.contains("FROZEN"),
            "UPTIME renamed over a column that stopped advancing"
        );
        assert!(
            frozen.contains(
                "refused   the shepherd did not answer: could not connect to `/home/ada/.shep/run/shep.sock`: Connection refused (os error 61)"
            ),
            "the link panel quotes the last dial's own error, whole"
        );
        assert!(
            frozen.contains("█ 250ms  █ 500ms  █ 1s  █ 2s  █ 4s"),
            "and draws every rung the ladder climbed"
        );
        // The design's own copy offers `r` in both places. `r` is refused
        // once the link is lost, and `run_link` has already returned, so
        // the frame must not name it anywhere.
        assert!(
            frozen.contains("shep muster, from another shell"),
            "the panel sends the operator somewhere that works"
        );
        assert!(
            !frozen.contains("dials again") && !frozen.contains("retry the link"),
            "and offers no key a freeze has already refused"
        );

        // Errored: selection parked on the errored sheep.
        let errored_buffer = scene(Scene::Errored).1;
        let errored = render_text(&errored_buffer);
        assert!(errored.contains("errored"));
        assert!(
            errored.contains("SHEEP 2  api"),
            "the selection is on the errored sheep"
        );
        assert_eq!(
            selected_row_count(&errored_buffer),
            1,
            "exactly one row's gutter is painted, on that row"
        );
        // Only the ANSI rendering carries colour to check STATUS against.
        //
        // Asserted per row, not on the whole frame: `errored.contains("1")`
        // would pass on any digit anywhere, blank column included.
        let row_of = |name: &str| {
            errored
                .lines()
                .find(|line| line.contains(name))
                .unwrap_or_else(|| panic!("no row for {name}:\n{errored}"))
                .to_string()
        };
        for (name, want) in [
            ("api", "1"),
            // NAME truncates at this width, landing one syllable earlier.
            ("billing-r", "1"),
            ("cron", "SIGTERM"),
        ] {
            let row = row_of(name);
            assert!(
                row.contains(want),
                "{name}'s EXIT cell must read {want}, not a dash: {row}"
            );
        }
        assert!(
            row_of("metrics").contains(" -   "),
            "a running sheep has no exit to report: {}",
            row_of("metrics")
        );

        let errored_ansi = render_ansi(&scene(Scene::Errored).1);
        assert!(
            errored_ansi.contains("\u{1b}[38;5;29monline"),
            "online's STATUS cell gets meadow"
        );
        assert!(
            errored_ansi.contains("\u{1b}[38;5;166merrored"),
            "errored's STATUS cell gets bark"
        );
        assert!(
            errored_ansi.contains("\u{1b}[38;5;221mwaiting-restart"),
            "waiting-restart's STATUS cell gets butter"
        );
        assert!(
            errored_ansi.contains("\u{1b}[38;5;245mID"),
            "the header row is muted grey, the same token stopped's STATUS uses"
        );
        assert!(
            errored_ansi.contains("\u{1b}[38;5;245mstopped"),
            "stopped's STATUS cell shares the chrome's muted grey rather than standing out"
        );

        // Refused: `x` with actions gated off.
        let refused = render_text(&scene(Scene::Refused).1);
        assert!(refused.contains("--read-only"), "{refused}");
        assert!(
            refused.contains("BLEATS api"),
            "a refusal does not blank the screen"
        );

        // FilterEditing: mid-type, table already narrowed.
        let editing = render_text(&scene(Scene::FilterEditing).1);
        assert_eq!(
            editing
                .lines()
                .filter(|line| line.contains("  web  "))
                .count(),
            2,
            "two rows survived the query"
        );
        assert!(!editing.contains("billing"), "and the rest did not");
        assert!(editing.contains("2 of 6 in the flock"), "got {editing:?}");
        assert!(
            editing.contains("filter  web\u{258f}"),
            "the query and the cursor"
        );
        for named in ["enter applies", "esc cancels", "ctrl-c quits"] {
            assert!(editing.contains(named), "the box names {named}");
        }

        // FilterActive: the same query, box closed.
        let active = render_text(&scene(Scene::FilterActive).1);
        assert!(active.contains("filter \"web\""), "the box is closed");
        assert!(!active.contains("enter applies"), "and its keys are gone");
        assert!(active.contains("2 of 6 in the flock"), "still narrowed");
        assert!(active.contains("/ edit") && active.contains("esc clear"));

        // FilterNoMatch: names the query rather than claiming empty.
        let none = render_text(&scene(Scene::FilterNoMatch).1);
        assert!(none.contains("no sheep's name contains \"zzz\""));
        assert!(!none.contains("the flock is empty"));
        assert!(none.contains("0 of 6 in the flock"));

        // HostUnknown: the strip keeps the flock's own totals.
        let unknown = render_text(&scene(Scene::HostUnknown).1);
        assert!(unknown.contains("host  usage is not available on this platform"));
        assert!(
            unknown.contains("flock cpu"),
            "the half lookout can compute survives"
        );

        // Lambs: the stamp sits before the list.
        let lambs = render_text(&scene(Scene::Lambs).1);
        assert!(lambs.contains("lambs  3 parent-pid descendants, read "));
        assert!(lambs.contains("48220 node"), "each lamb's pid and name");
        let line = lambs
            .lines()
            .find(|line| line.starts_with("lambs  "))
            .expect("the lamb line");
        assert!(
            line.find("read ").unwrap() < line.find("48220").unwrap(),
            "the stamp comes before the list"
        );

        // LambsUnknown: no pid to walk from, unset rather than empty.
        let unknown = render_text(&scene(Scene::LambsUnknown).1);
        assert!(unknown.contains("lambs  this sheep is not running, so there is no tree to walk"));
        assert!(
            !unknown.contains("none found"),
            "which is the other sentence"
        );
        assert!(unknown.contains("SHEEP 4  cron"), "on the stopped sheep");

        // Confirm: `R` pressed, nothing sent yet.
        let confirm = render_text(&scene(Scene::Confirm).1);
        assert!(confirm.contains("restart api (id 2)? enter confirms, any other key cancels"));
        assert!(confirm.contains("control enabled"), "the gate is open");
        assert!(
            row_for(&confirm, "api").is_some_and(|row| row.contains("online")),
            "nothing was sent, so api is still online: {confirm:?}"
        );

        // Acting: request out, table unchanged.
        let acting_buffer = scene(Scene::Acting).1;
        let acting = render_text(&acting_buffer);
        assert!(acting.contains("restart api (id 2): sent, waiting for the shepherd"));
        assert!(
            selected_line(&acting, &acting_buffer).is_some_and(|line| line.contains("api")),
            "the table is untouched: the selection is still on api"
        );
        assert!(
            row_for(&acting, "api").is_some_and(|row| row.contains("online")),
            "and the row still says what the shepherd last said"
        );

        // ActionAccepted: the reply's own row reaches the table at once.
        let accepted = render_text(&scene(Scene::ActionAccepted).1);
        assert!(accepted.contains("restart api (id 2): the shepherd restarted it"));
        assert!(
            row_for(&accepted, "api").is_some_and(|row| row.contains("48299")),
            "the reply's own row reached the table without waiting for a poll"
        );

        // ActionRefused: the shepherd's own sentence is forwarded as is.
        let action_refused_buffer = scene(Scene::ActionRefused).1;
        let refused = render_text(&action_refused_buffer);
        assert!(refused.contains("restart api (id 2): selector matched no registered sheep"));
        assert!(
            !refused.contains("NotFound"),
            "no Rust identifiers on the bar"
        );
        assert!(refused.contains("5 in the flock"), "one row shorter");
        assert!(
            row_for(&refused, "api").is_none(),
            "api is the row that went"
        );
        assert!(
            marked_row_name_starts_with(&refused, &action_refused_buffer, "billing"),
            "and the cursor has moved to the row below: {refused:?}"
        );

        // ActionRefusedOffline: names the same reconnect attempt as the
        // banner above it, not the exhausted-ladder sentence.
        let offline = render_text(&scene(Scene::ActionRefusedOffline).1);
        assert_eq!(
            offline.matches("reconnecting (attempt 3)").count(),
            2,
            "the banner and the refusal under it agree, rather than one \
             saying reconnecting and the other saying gone: {offline:?}"
        );
        assert!(
            !offline.contains("nothing left to ask"),
            "the ladder has not run out yet, so the refusal must not claim it has: {offline:?}"
        );

        // The left bar slot is empty here, same as on every ordinary
        // dashboard scene, so this bar carries the plain control hint.
        let lambs_bar = render_text(&scene(Scene::Lambs).1);
        for key in ["x stop", "R restart", "L reload"] {
            assert!(lambs_bar.contains(key), "the control hint names {key}");
        }

        // SettingsFresh: a bare `shep.toml`, every scalar reads the default.
        let fresh = render_text(&scene(Scene::SettingsFresh).1);
        assert_eq!(
            fresh.matches("the default").count(),
            6,
            "all six scalars read the default: {fresh:?}"
        );
        assert!(
            !fresh.contains("shep.toml  "),
            "a fresh home has declared nothing: {fresh:?}"
        );

        // SettingsSet: `shep.toml` and the default sit side by side.
        let set = render_text(&scene(Scene::SettingsSet).1);
        assert!(set.contains("shep.toml"), "some scalars are declared");
        assert!(set.contains("the default"), "and some are not: {set:?}");

        // SettingsConfirm: names the env var and flag it cannot see.
        let confirm = render_text(&scene(Scene::SettingsConfirm).1);
        assert!(confirm.contains("shep daemon reload"), "got: {confirm:?}");
        assert!(confirm.contains("SHEP_LOG_LEVEL"), "got: {confirm:?}");
        assert!(confirm.contains("--log-level"), "got: {confirm:?}");

        // SettingsTyping: names the field being typed, not the filter box.
        let typing = render_text(&scene(Scene::SettingsTyping).1);
        assert!(
            typing.contains("editing socket"),
            "names the field being typed: {typing:?}"
        );
        assert!(
            !typing.contains("filter "),
            "must not read as the dashboard's own filter box: {typing:?}"
        );

        // SettingsDogs: the drift the table exists to reveal.
        let dogs = render_text(&scene(Scene::SettingsDogs).1);
        assert!(
            dog_row_for(&dogs, "otel")
                .is_some_and(|row| row.contains("no") && row.contains("online")),
            "otel: disabled in the file, running: {dogs:?}"
        );
        assert!(
            dog_row_for(&dogs, "ledger")
                .is_some_and(|row| row.contains("yes") && row.contains("not running")),
            "ledger: enabled, absent from the flock: {dogs:?}"
        );
        assert!(
            dog_row_for(&dogs, "bark")
                .is_some_and(|row| row.contains("yes") && row.contains("silent")),
            "bark: enabled, running, never handshook: {dogs:?}"
        );

        // SettingsNarrow: both tables drop a column rather than clip.
        let narrow = render_text(&scene(Scene::SettingsNarrow).1);
        assert!(
            narrow.contains("shep.toml"),
            "the scalar rows keep SOURCE: {narrow:?}"
        );
        assert!(
            !narrow.contains("needs shep daemon reload"),
            "and lose the apply cost: {narrow:?}"
        );
        assert!(
            dog_row_for(&narrow, "otel").is_some_and(|row| row.contains("online")),
            "the dogs table keeps RUNNING: {narrow:?}"
        );
        assert!(!narrow.contains("built-in"), "and loses SOURCE: {narrow:?}");

        // "The same screen at 14 rows, which is fewer than it has to draw.
        //  The cursor is on the last dog, so the view has scrolled to reach
        //  it and `... 5 above` says how much is off the top. The scroll is
        //  counted in lines rather than in rows: a section header and the
        //  dogs caption cost the same height a row does."
        let short = render_text(&scene(Scene::SettingsShort).1);
        assert!(
            short.contains("... 5 above"),
            "the marker names how many rows are off the top: {short:?}"
        );
        assert!(
            short
                .lines()
                .any(|line| line.starts_with("> bark")
                    || line.starts_with('>') && line.contains("bark")),
            "the cursor's own row is drawn: {short:?}"
        );
        assert!(
            !short.contains("log_level"),
            "and the rows above it are the ones that went: {short:?}"
        );
        assert!(
            short.contains("[style]") && short.contains("[dogs]"),
            "what survives is whole sections, headers and all: {short:?}"
        );

        // Bleats: all three axes stacked, wrapping on.
        let bleats = render_text(&scene(Scene::Bleats).1);
        for chip in ["stream out", "level ≥ warn", "match /retry|jitter/ (regex)"] {
            assert!(
                bleats.contains(chip),
                "the filter row names {chip}: {bleats:?}"
            );
        }
        assert!(
            // The sentence itself is longer than this 100-column frame, so
            // it fits and truncates with an ellipsis: this is the prefix
            // that survives the cut.
            bleats.contains("1 of 16 lines in the window: all three m…"),
            "the survivor count and the start of the composition sentence: {bleats:?}"
        );
        assert!(
            bleats.contains("out  WARN retrying upstream payment gateway"),
            "the one surviving line, tagged by its stream: {bleats:?}"
        );
        assert!(
            bleats
                .lines()
                .any(|line| line.starts_with("     ith jitter")),
            "wrapping is on, so the line's tail lands on its own row rather than truncating: {bleats:?}"
        );
        assert!(
            bleats.contains("esc back") && bleats.contains("\u{2588} following"),
            "the full key line, and the pane is still following the tail: {bleats:?}"
        );

        // SheepPane: both charts, the config column, and the feed, all at
        // 160x48.
        let sheep_pane = render_text(&scene(Scene::SheepPane).1);
        assert!(
            sheep_pane.contains("\u{2588}\u{2588} CPU")
                && sheep_pane.contains("\u{2588}\u{2588} MEM"),
            "both charts draw: {sheep_pane:?}"
        );
        assert!(
            sheep_pane.contains("\u{2588}\u{2588} CONFIG & ENV") && sheep_pane.contains("script"),
            "the config column lists web's own fields: {sheep_pane:?}"
        );
        assert!(
            sheep_pane.contains("\u{2588}\u{2588} BLEATS"),
            "the embedded feed carries its own header: {sheep_pane:?}"
        );

        // SheepPaneCpuOnly: 139 columns, the CPU chart alone plus a
        // one-line memory summary.
        let cpu_only = render_text(&scene(Scene::SheepPaneCpuOnly).1);
        assert!(
            cpu_only.contains("\u{2588}\u{2588} CPU"),
            "the CPU chart still draws: {cpu_only:?}"
        );
        assert!(
            !cpu_only.contains("\u{2588}\u{2588} MEM"),
            "the memory chart is gone: {cpu_only:?}"
        );
        assert!(
            cpu_only.contains("rss "),
            "replaced by a one-line rss summary: {cpu_only:?}"
        );

        // SheepPaneSparklines: 99 columns, 1a's own pair on one row.
        let sparklines = render_text(&scene(Scene::SheepPaneSparklines).1);
        assert!(
            !sparklines.contains("\u{2588}\u{2588} CPU")
                && !sparklines.contains("\u{2588}\u{2588} MEM"),
            "both charts are gone: {sparklines:?}"
        );
        assert!(
            sparklines.contains("CPU 20s") && sparklines.contains("MEM/CEIL"),
            "1a's own pair draws instead: {sparklines:?}"
        );

        // SheepPaneShort: 160x25, the memory chart gone, the CPU chart and
        // the config column still up.
        let short_pane = render_text(&scene(Scene::SheepPaneShort).1);
        assert!(
            short_pane.contains("\u{2588}\u{2588} CPU"),
            "the CPU chart still draws: {short_pane:?}"
        );
        assert!(
            !short_pane.contains("\u{2588}\u{2588} MEM"),
            "the memory chart is gone under 26 rows: {short_pane:?}"
        );
        assert!(
            short_pane.contains("\u{2588}\u{2588} CONFIG & ENV"),
            "the config column, which gives ground last, is still up: {short_pane:?}"
        );

        // EditPane: fresh, no edits filed, 160x48. LANDS draws in the
        // header and the explanation panel is on screen, and the title
        // band carries no edit count.
        let edit_pane = render_text(&scene(Scene::EditPane).1);
        let title = edit_pane
            .lines()
            .find(|line| line.contains("(sheep config)"))
            .expect("the title band");
        assert!(
            !title.contains("edit"),
            "fresh, so the title names no edit count: {title:?}"
        );
        let header = edit_pane
            .lines()
            .find(|line| line.contains("FIELD") && line.contains("VALUE"))
            .expect("the field list header");
        assert!(
            header.contains("LANDS"),
            "wide enough for the cost column: {header:?}"
        );
        assert!(
            edit_pane.contains("FOCUSED"),
            "the explanation panel names the focused field: {edit_pane:?}"
        );

        // EditPaneEdited: the same pane with cwd and max_memory filed. The
        // title counts them and the pending section lists both.
        let edit_pane_edited = render_text(&scene(Scene::EditPaneEdited).1);
        let edited_title = edit_pane_edited
            .lines()
            .find(|line| line.contains("(sheep config)"))
            .expect("the title band");
        assert!(
            edited_title.contains("2 edits"),
            "two edits filed: {edited_title:?}"
        );
        let pending_section = edit_pane_edited
            .lines()
            .skip_while(|line| !line.trim_start().starts_with("pending edits"))
            .take(3)
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            pending_section.contains("cwd") && pending_section.contains("max_memory"),
            "both filed edits are named under the pending edits section: {pending_section:?}"
        );

        // EditPaneSqueezed: 120 columns. The panel still draws; LANDS
        // gives way to it, so the header carries FIELD and VALUE but not
        // LANDS.
        let squeezed = render_text(&scene(Scene::EditPaneSqueezed).1);
        let squeezed_header = squeezed
            .lines()
            .find(|line| line.contains("FIELD") && line.contains("VALUE"))
            .expect("the field list header");
        assert!(
            !squeezed_header.contains("LANDS"),
            "LANDS gives way to the panel at 120 columns: {squeezed_header:?}"
        );
        assert!(
            squeezed.contains("FOCUSED"),
            "the panel still draws at 120 columns: {squeezed:?}"
        );

        // EditPaneNarrow: 88 columns. The panel is gone, so LANDS returns.
        let narrow_edit = render_text(&scene(Scene::EditPaneNarrow).1);
        let narrow_edit_header = narrow_edit
            .lines()
            .find(|line| line.contains("FIELD") && line.contains("VALUE"))
            .expect("the field list header");
        assert!(
            narrow_edit_header.contains("LANDS"),
            "nothing else carries cost at 88 columns, so LANDS is back: {narrow_edit_header:?}"
        );
        assert!(
            !narrow_edit.contains("FOCUSED"),
            "the panel does not draw at 88 columns: {narrow_edit:?}"
        );

        // CloseDialog: 160x48, boxed. The heading, the first row inside
        // the border, names both halves: two edits needing a respawn and
        // one field already parked.
        let close_dialog = render_text(&scene(Scene::CloseDialog).1);
        let close_dialog_lines: Vec<&str> = close_dialog.lines().collect();
        let border_row = close_dialog_lines
            .iter()
            .position(|line| line.contains('▛')) // BOX_TOP_LEFT
            .expect("the box border draws at 160 columns");
        let heading = close_dialog_lines[border_row + 1];
        assert!(
            heading.contains("EDITS NEED A RESPAWN") && heading.contains("FIELD ALREADY"),
            "the heading names both the unsent and the parked half: {heading:?}"
        );

        // CloseDialogFloor: 90x48, exactly the width the border needs.
        // Read off the border's own row, the way both heading assertions
        // here do: a frame-wide `contains` passes on the glyph turning up
        // anywhere, and it is only this dialog that draws one today.
        let close_dialog_floor = render_text(&scene(Scene::CloseDialogFloor).1);
        let floor_lines: Vec<&str> = close_dialog_floor.lines().collect();
        let floor_border_row = floor_lines
            .iter()
            .position(|line| line.contains('▛')) // BOX_TOP_LEFT
            .expect("the box border draws at the floor");
        assert!(
            floor_lines[floor_border_row].contains('▜'), // BOX_TOP_RIGHT
            "the border's top row closes at the floor: {:?}",
            floor_lines[floor_border_row]
        );

        // CloseDialogNarrow: 89x48, one column under the floor. No box
        // glyph anywhere in the frame; this is the assertion a wrong
        // overlay::floor_for(BOX_WIDTH) would fail.
        let close_dialog_narrow = render_text(&scene(Scene::CloseDialogNarrow).1);
        for glyph in ['▛', '▜', '▙', '▟', '▐', '▀', '▄', '▌'] {
            assert!(
                !close_dialog_narrow.contains(glyph),
                "no border glyph {glyph:?} draws one column under the floor: {close_dialog_narrow:?}"
            );
        }

        // CloseDialogParked: 160x48, no edit of the operator's own. The
        // heading names only the parked half, with no unsent count.
        let close_dialog_parked = render_text(&scene(Scene::CloseDialogParked).1);
        let parked_lines: Vec<&str> = close_dialog_parked.lines().collect();
        let parked_border_row = parked_lines
            .iter()
            .position(|line| line.contains('▛'))
            .expect("the box border draws at 160 columns");
        let parked_heading = parked_lines[parked_border_row + 1];
        assert!(
            parked_heading.contains("FIELD ALREADY") && !parked_heading.contains("EDIT"),
            "the heading names the parked half alone, with no unsent count: {parked_heading:?}"
        );
    }

    /// Two grouped apps, four sheep, six visible rows: a `0..=flock_len()`
    /// budget only reaches index 4, short of the last row at index 5. One
    /// group would not show this, since its header lands the budget
    /// exactly on the last row.
    #[test]
    fn the_cursor_walk_budgets_by_visible_rows_not_by_sheep() {
        let t0 = Instant::now();
        let mut app = App::new(
            coloured_palette(),
            Control::ReadOnly,
            "/home/ada/.shep".to_string(),
            t0,
        );
        app.update(Msg::Snapshot {
            rows: vec![
                instance(0, "web", 0, 0, 3.4, 182 << 20, 4_512_000),
                instance(1, "web", 1, 0, 2.9, 178 << 20, 4_512_000),
                instance(2, "api", 0, 0, 7.1, 241 << 20, 4_512_000),
                instance(3, "api", 1, 0, 6.8, 239 << 20, 4_512_000),
            ],
            at: t0,
        });
        assert_eq!(
            app.visible_rows().len(),
            7,
            "the flock header, four sheep and two group headers"
        );

        // `web`'s second slot: the last visible row, and the one a
        // sheep-counted budget cannot reach.
        select_id(&mut app, 1);
        assert_eq!(app.selected(), Some(RowKey::Sheep(1)));
    }

    /// Only checks that every scene has a caption, since whether the
    /// caption is pinned by an assertion is not machine-checkable.
    #[test]
    fn every_scene_has_a_caption_and_a_distinct_label() {
        let mut labels = std::collections::BTreeSet::new();
        for which in Scene::ALL {
            assert!(
                labels.insert(which.label()),
                "two scenes share {}",
                which.label()
            );
            let caption = which.caption();
            assert!(caption.len() > 30, "{} has a stub caption", which.label());
            assert!(
                caption.ends_with('.'),
                "{}'s caption is not a sentence",
                which.label()
            );
        }
    }

    /// The scene that follows `scene` in gallery order, or `None` after the
    /// last one. Mirrors `Scene::ALL`'s own order.
    ///
    /// Exhaustive over [`Scene`], with no wildcard arm: a variant added to
    /// the enum without an arm here fails to compile. `scene_all_lists_every_variant_the_compiler_can_see`
    /// below walks this chain and checks it against `ALL`, which a
    /// hand-counted length could not: a forgotten scene just left the count
    /// honest at the old number.
    ///
    /// The `scenes!` macro that declares `Scene` keeps a variant from being
    /// left out of `ALL` outright — the two are generated from one list, so
    /// they cannot disagree on membership. What that macro cannot catch is
    /// this chain: a variant could still get an arm here that loops back on
    /// itself or points somewhere unreachable from `HealthyWide`, compiling
    /// fine while never being walked. That is exactly what this test's own
    /// walk-and-compare catches, so the two mechanisms are covering
    /// different halves of the same failure, not one covering the other.
    fn scene_after(scene: Scene) -> Option<Scene> {
        match scene {
            Scene::HealthyWide => Some(Scene::Errored),
            Scene::Errored => Some(Scene::Grouped),
            Scene::Grouped => Some(Scene::Folds),
            Scene::Folds => Some(Scene::WithDogs),
            Scene::WithDogs => Some(Scene::MemCeiling),
            Scene::MemCeiling => Some(Scene::CfgDrift),
            Scene::CfgDrift => Some(Scene::Empty),
            Scene::Empty => Some(Scene::Narrow),
            Scene::Narrow => Some(Scene::TooNarrow),
            Scene::TooNarrow => Some(Scene::Retrying),
            Scene::Retrying => Some(Scene::Frozen),
            Scene::Frozen => Some(Scene::Refused),
            Scene::Refused => Some(Scene::FilterEditing),
            Scene::FilterEditing => Some(Scene::FilterActive),
            Scene::FilterActive => Some(Scene::FilterNoMatch),
            Scene::FilterNoMatch => Some(Scene::NoDetail),
            Scene::NoDetail => Some(Scene::TableOnly),
            Scene::TableOnly => Some(Scene::FeedGap),
            Scene::FeedGap => Some(Scene::FeedMissing),
            Scene::FeedMissing => Some(Scene::Cramped),
            Scene::Cramped => Some(Scene::HostUnknown),
            Scene::HostUnknown => Some(Scene::Lambs),
            Scene::Lambs => Some(Scene::LambsUnknown),
            Scene::LambsUnknown => Some(Scene::Confirm),
            Scene::Confirm => Some(Scene::Acting),
            Scene::Acting => Some(Scene::ActionRefused),
            Scene::ActionRefused => Some(Scene::ActionAccepted),
            Scene::ActionAccepted => Some(Scene::ActionRefusedOffline),
            Scene::ActionRefusedOffline => Some(Scene::SettingsFresh),
            Scene::SettingsFresh => Some(Scene::SettingsSet),
            Scene::SettingsSet => Some(Scene::SettingsConfirm),
            Scene::SettingsConfirm => Some(Scene::SettingsTyping),
            Scene::SettingsTyping => Some(Scene::SettingsDogs),
            Scene::SettingsDogs => Some(Scene::SettingsNarrow),
            Scene::SettingsNarrow => Some(Scene::SettingsShort),
            Scene::SettingsShort => Some(Scene::Bleats),
            Scene::Bleats => Some(Scene::Secrets),
            Scene::Secrets => Some(Scene::SheepPane),
            Scene::SheepPane => Some(Scene::SheepPaneCpuOnly),
            Scene::SheepPaneCpuOnly => Some(Scene::SheepPaneSparklines),
            Scene::SheepPaneSparklines => Some(Scene::SheepPaneShort),
            Scene::SheepPaneShort => Some(Scene::EditPane),
            Scene::EditPane => Some(Scene::EditPaneEdited),
            Scene::EditPaneEdited => Some(Scene::EditPaneSqueezed),
            Scene::EditPaneSqueezed => Some(Scene::EditPaneNarrow),
            Scene::EditPaneNarrow => Some(Scene::CloseDialog),
            Scene::CloseDialog => Some(Scene::CloseDialogFloor),
            Scene::CloseDialogFloor => Some(Scene::CloseDialogNarrow),
            Scene::CloseDialogNarrow => Some(Scene::CloseDialogParked),
            Scene::CloseDialogParked => Some(Scene::Keymap),
            Scene::Keymap => Some(Scene::KeymapFloor),
            Scene::KeymapFloor => Some(Scene::KeymapBorderlessWide),
            Scene::KeymapBorderlessWide => Some(Scene::KeymapNarrow),
            Scene::KeymapNarrow => Some(Scene::KeymapTwoColumn),
            Scene::KeymapTwoColumn => Some(Scene::KeymapFrozen),
            Scene::KeymapFrozen => Some(Scene::KeymapReadOnly),
            Scene::KeymapReadOnly => Some(Scene::KeymapShort),
            Scene::KeymapShort => None,
        }
    }

    /// Walks [`scene_after`] from the first scene and checks the walk names
    /// exactly `Scene::ALL`, in the same order.
    ///
    /// The walk can only see variants `scene_after` was taught about, and
    /// that match cannot compile with one missing, so a scene left out of
    /// `ALL` shows up here as a length or order mismatch rather than as
    /// nothing at all.
    #[test]
    fn scene_all_lists_every_variant_the_compiler_can_see() {
        let mut walked = vec![Scene::HealthyWide];
        while let Some(next) = scene_after(*walked.last().unwrap()) {
            // Bounded, because `scene_after` is a hand-kept chain and a
            // variant wired back at an earlier one would otherwise spin here
            // forever. Nextest has no per-test timeout, so an unbounded walk
            // fails as a twenty-minute job timeout with no named test rather
            // than as an assertion.
            assert!(
                walked.len() < Scene::ALL.len(),
                "scene_after cycles: walked {} scenes without reaching the end of {}",
                walked.len(),
                Scene::ALL.len()
            );
            walked.push(next);
        }
        assert_eq!(walked.as_slice(), Scene::ALL);
    }

    /// `sgr` now draws a foreground, a background and `REVERSED`, so the
    /// title and section bands' reverse video and the selected row's
    /// painted ground both reach `frames.ansi`. This test still forbids
    /// any modifier beyond `REVERSED`: nothing in the dashboard uses one
    /// today, and a scene that started would render unstyled without this
    /// guard noticing.
    #[test]
    fn no_scene_uses_a_modifier_the_ansi_renderer_cannot_render() {
        for which in Scene::ALL {
            let buffer = scene(*which).1;
            for y in 0..buffer.area.height {
                for x in 0..buffer.area.width {
                    let cell = &buffer[(buffer.area.x + x, buffer.area.y + y)];
                    assert!(
                        cell.modifier.is_empty() || cell.modifier == Modifier::REVERSED,
                        "{} has an unrendered modifier at {x},{y}: {:?}",
                        which.label(),
                        cell.modifier
                    );
                }
            }
        }
    }

    /// A pinned width whose own arithmetic no longer holds drops a column
    /// in silence, and this is the scene whose whole point is what the
    /// columns look like once the shepherd is gone.
    ///
    /// The floor is `ALL`'s own tier threshold plus the gutter, not the
    /// design's 160: the frame is drawn twelve columns wider than it has
    /// to be, and pinning the wider number would fail for a scene that was
    /// still drawing everything.
    #[test]
    fn the_frozen_scene_draws_every_column() {
        use super::super::view::flock::{GUTTER, columns_for};

        let (width, _) = Scene::Frozen.size();
        assert_eq!(
            columns_for(width - GUTTER).len(),
            columns_for(u16::MAX).len(),
            "the frozen scene is {width} columns, which drops a column from the widest set"
        );
    }

    /// Rule 3 of the design system: strip every colour and the frame still
    /// reads. Its corollary on this one frame is stronger — no cell above
    /// the link panel may carry a colour at all, since a meadow `online`
    /// two seconds after the shepherd died is the one lie this screen can
    /// tell.
    #[test]
    fn no_cell_above_the_link_panel_is_painted_live() {
        let palette = coloured_palette();
        let buffer = scene(Scene::Frozen).1;
        let muted = palette.muted().fg;
        let line = palette.line().fg;
        // Row 0 is the band, which is bark and says so; the link panel
        // below carries the ladder's own bark blocks and a butter `r`.
        let panel_at = render_text(&buffer)
            .lines()
            .position(|row| row.contains("THE LINK"))
            .expect("the link panel is on a frozen frame");
        let panel_at = u16::try_from(panel_at).expect("a row index fits");
        for y in 1..panel_at {
            for x in 0..buffer.area.width {
                let cell = &buffer[(buffer.area.x + x, buffer.area.y + y)];
                assert!(
                    cell.fg == Color::Reset || Some(cell.fg) == muted || Some(cell.fg) == line,
                    "a live-looking cell at {x},{y}: {:?} in {:?}",
                    cell.symbol(),
                    cell.fg
                );
            }
        }
    }

    /// Rendered twice at two different ages and compared to each other,
    /// not to the healthy scene, since a live-versus-frozen diff would
    /// pass either way. The live pair at the bottom catches a renderer
    /// that drops the uptime column entirely.
    ///
    /// Split at the link panel's own chip rather than at a row index. Every
    /// value above it came from the shepherd and stopped when the shepherd
    /// did; the panel below it describes the link, and how long ago the
    /// link died is a fact about now. One half must not move and the other
    /// must, so the test asserts both rather than narrowing to the half
    /// that is easier to pin.
    #[test]
    fn a_frozen_frame_moves_only_in_the_link_panel() {
        let ten_minutes = render_text(&scene_with(
            Scene::Frozen,
            Duration::from_secs(600),
            coloured_palette(),
        ));
        let sixteen_hours = render_text(&scene_with(
            Scene::Frozen,
            Duration::from_secs(60_000),
            coloured_palette(),
        ));
        let above_the_panel = |frame: &str| {
            frame
                .split("THE LINK")
                .next()
                .expect("split yields at least one part")
                .to_string()
        };
        assert_eq!(
            above_the_panel(&ten_minutes),
            above_the_panel(&sixteen_hours),
            "the frozen frame's uptime column advanced after the link was lost"
        );
        assert_ne!(
            ten_minutes, sixteen_hours,
            "the link panel's age is the one number a frozen frame still counts"
        );
        // Seven seconds short of each age, and deliberately: `scene_with`
        // ticks the clock forward by that much before it freezes anything,
        // so the freeze happens at `t0 + 7s` and the panel counts from
        // there. `9m 53s`, not `593s` — the same two-unit shape every other
        // duration on the screen uses.
        assert!(
            ten_minutes.contains("2026-08-14 14:32:07, 9m 53s ago"),
            "and it counts in the same words every other duration uses"
        );
        assert!(
            sixteen_hours.contains("2026-08-14 14:32:07, 16h 39m ago"),
            "at both ends of the sweep"
        );
        assert!(
            above_the_panel(&ten_minutes).contains("1h 18m"),
            "the frozen frame has an uptime cell for the comparison above to cover"
        );

        let live_ten = render_text(&scene_with(
            Scene::HealthyWide,
            Duration::from_secs(600),
            coloured_palette(),
        ));
        let live_sixteen = render_text(&scene_with(
            Scene::HealthyWide,
            Duration::from_secs(60_000),
            coloured_palette(),
        ));
        assert_ne!(
            live_ten, live_sixteen,
            "a LIVE frame's uptime column must advance, or the assertion above passes for the wrong reason"
        );
    }

    /// Each width scene draws the column count it exists to show, counted
    /// off the heading row's own occupied starts rather than inferred from
    /// a word being present. A test that only looked for `MOVING` would
    /// pass at every width in the table, since `MOVING` draws at every
    /// width the overlay ever renders.
    #[test]
    fn each_keymap_width_scene_draws_its_own_column_count() {
        for (which, wanted) in [
            (Scene::Keymap, 4),
            (Scene::KeymapFloor, 4),
            (Scene::KeymapBorderlessWide, 4),
            (Scene::KeymapNarrow, 3),
            (Scene::KeymapTwoColumn, 2),
        ] {
            let rendered = render_text(&scene(which).1);
            let first_bank = rendered
                .lines()
                // `Group::Moving.heading()`, not the literal "MOVING": the
                // count below derives from `heading()`, so a rename would
                // leave this `find` hunting a word nothing draws and the
                // failure would read as a missing heading row rather than as
                // a rename.
                .find(|row| row.contains(Group::Moving.heading()))
                .expect("no heading row");
            let drawn = Group::DRAWN
                .iter()
                .filter(|group| first_bank.contains(group.heading()))
                .count();
            assert_eq!(drawn, wanted, "{}: {first_bank:?}", which.label());
        }
    }

    /// Every `Keymap*` scene actually raises the overlay.
    ///
    /// `scene`'s builder raises it from a `matches!` list of variants, and
    /// the comment over that list says "every `Keymap*` scene". Nothing held
    /// that claim. The per-scene checks in this module are a hand-written
    /// list, `each_keymap_width_scene_draws_its_own_column_count` names five
    /// of the eight, and a snapshot is accepted for whatever a scene
    /// rendered, so a ninth keymap scene left out of the `matches!` list
    /// would draw the dashboard and be pinned that way.
    ///
    /// Driven off the label rather than a list, so a new scene joins this
    /// test by being named. Dropping `KeymapNarrow` from the builder's list
    /// fails it, and so does adding a scene the list does not cover.
    ///
    /// The count is the other half: it catches a keymap scene whose label
    /// does not start with `keymap`, which this test would otherwise skip in
    /// silence, and it is the same eight the gallery preamble promises.
    #[test]
    fn every_keymap_scene_raises_the_overlay() {
        let mut checked = 0;
        for which in Scene::ALL {
            if !which.label().starts_with("keymap") {
                continue;
            }
            checked += 1;
            let rendered = render_text(&scene(*which).1);
            assert!(
                rendered.contains(Group::Moving.heading()),
                "{}: the overlay did not draw",
                which.label()
            );
        }
        assert_eq!(checked, 8, "the keymap scenes, counted by label");
    }

    /// Frame pins, not wire fixtures: re-accepting these after a layout
    /// change is expected, unlike the rule for shep-core's protocol
    /// snapshots.
    ///
    /// `cfg(unix)`: one fixture carries a synthetic signalled exit, and
    /// `signal_label` resolves it against the running platform's table.
    /// Windows never sets a signal on `ExitOutcome`, so this only runs
    /// against a synthetic fixture; the pinned artifacts under
    /// `docs/lookout/` are unix renderings for the same reason.
    #[cfg(unix)]
    #[test]
    fn frames_are_pinned() {
        for which in Scene::ALL {
            let (label, buffer) = scene(*which);
            insta::assert_snapshot!(label, render_text(&buffer));
        }
    }

    /// `Scene::Secrets` claims a revealed row in its own doc, caption and
    /// the hand-copied frame in `web/`. Assert the frame actually shows
    /// the plaintext and a countdown, not a mask: a snapshot alone would
    /// pass on an expired reveal, since nothing names what "revealed"
    /// means.
    #[test]
    fn the_secrets_scene_shows_a_revealed_row_not_a_mask() {
        let text = render_text(&scene(Scene::Secrets).1);
        let revealed = text
            .lines()
            .find(|line| line.contains("DB_PASSWORD"))
            .expect("the secrets scene draws a DB_PASSWORD row");

        assert!(
            revealed.contains("hunter2-not-really"),
            "DB_PASSWORD's row should show the revealed plaintext, not a mask: {revealed:?}"
        );
        assert!(
            !revealed.contains("bytes"),
            "the VALUE cell should show plaintext, not a masked byte count: {revealed:?}"
        );
        assert!(
            revealed.contains("visible"),
            "a revealed row should show a countdown, not the unrevealed dash: {revealed:?}"
        );
    }

    /// `secrets::model` reads `readers` and `roll_age` off the same muster
    /// roll, so a frame naming a reader and then saying no roll exists is a
    /// state the loader cannot produce. The snapshot pins the frame against
    /// its own committed copy, so the contradiction stays green there and
    /// reaches `docs/lookout/` and the published page.
    #[test]
    fn the_secrets_scene_does_not_deny_the_roll_its_readers_came_from() {
        let text = render_text(&scene(Scene::Secrets).1);
        let read_by = text
            .lines()
            .find(|line| line.contains("DB_PASSWORD"))
            .expect("the secrets scene draws a DB_PASSWORD row");

        assert!(
            read_by.contains("1 (1 online)"),
            "the scene's own row names a reader: {read_by:?}"
        );
        assert!(
            !text.contains("no muster roll yet"),
            "and so cannot also say the roll it came from was never written"
        );
        assert!(
            text.contains("READ BY as of the roll"),
            "it says how old the roll is instead"
        );
    }

    /// The two gallery files' text: plain, then ANSI.
    ///
    /// Separate from the writer so a non-ignored test can read it.
    fn gallery_text() -> (String, String) {
        let mut plain = String::from(GALLERY_PREAMBLE);
        let mut ansi = String::from(GALLERY_PREAMBLE);
        for which in Scene::ALL {
            let (width, height) = which.size();
            let heading = format!(
                "\n\n=== {}  ({width}x{height}) ===\n{}\n\n",
                which.label(),
                which.caption()
            );
            // Two separate renders, not one buffer read twice: `frames.txt`
            // is what a `NO_COLOR` operator sees, and that palette has no
            // painted ground for the gutter to fall back from, so the
            // buffer itself differs, not just how it prints.
            let plain_buffer = scene_with(*which, Duration::from_secs(600), no_color_palette());
            plain.push_str(&heading);
            plain.push_str(&render_text(&plain_buffer));
            let ansi_buffer = scene_with(*which, Duration::from_secs(600), coloured_palette());
            ansi.push_str(&heading);
            ansi.push_str(&render_ansi(&ansi_buffer));
        }
        (plain, ansi)
    }

    /// The committed gallery matches what the generator would write today.
    ///
    /// `write_the_gallery` is `#[ignore]`d, so nothing in the ordinary
    /// suite catches a scene that landed without also running it: its own
    /// doc names the exact failure, both files still saying fifty scenes
    /// and holding none of the eight keymap scenes that shipped alongside
    /// them. Diffing against fresh output, rather than only counting
    /// headings, catches a mismatch a count would miss too, a caption
    /// edited without a corresponding regeneration.
    ///
    /// `cfg(unix)`: same reason as `frames_are_pinned` above. `signal_label`
    /// resolves a fixture's signal against the running platform's own
    /// table, and the committed artifacts under `docs/lookout/` are unix
    /// renderings, so a Windows-built binary regenerates the `cron` row
    /// reading a bare `15` where the committed file reads `SIGTERM`.
    #[cfg(unix)]
    #[test]
    fn the_committed_gallery_matches_what_the_generator_would_write() {
        let dir = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/lookout"));
        let (plain, ansi) = gallery_text();
        for (name, want) in [("frames.txt", &plain), ("frames.ansi", &ansi)] {
            let have = std::fs::read_to_string(dir.join(name)).unwrap_or_else(|e| {
                panic!(
                    "{name} is missing or unreadable ({e}); run \
                     cargo test -p shep --lib --all-features -- --ignored write_the_gallery"
                )
            });
            assert_eq!(
                &have, want,
                "{name} is stale against the current scenes; run \
                 cargo test -p shep --lib --all-features -- --ignored write_the_gallery"
            );
        }
    }

    #[test]
    fn the_gallery_carries_no_dashes() {
        let (plain, ansi) = gallery_text();
        for (file, text) in [("frames.txt", &plain), ("frames.ansi", &ansi)] {
            assert!(!text.contains('\u{2014}'), "em dash in {file}");
            assert!(!text.contains('\u{2013}'), "en dash in {file}");
        }
    }

    /// Writes `docs/lookout/frames.txt` and `docs/lookout/frames.ansi`.
    ///
    /// `#[ignore]`: writes into the repository, so it only runs on request.
    ///
    /// ```text
    /// cargo test -p shep --lib --all-features -- --ignored write_the_gallery
    /// ```
    ///
    /// A layout change cannot rot these files unnoticed: they render the
    /// same `Scene::ALL` the pinned snapshots read, so the ordinary suite
    /// reddens first and whoever fixes it comes back here.
    ///
    /// **Adding a scene without running this one is caught too, now.**
    /// `the_committed_gallery_matches_what_the_generator_would_write`
    /// diffs the committed files against fresh output, catching a scene
    /// missing from both while their own preamble still carries the old
    /// count. Run this anyway, in the same commit that adds a scene: a
    /// missing regeneration failing there is a one-line fix, failing in
    /// the other test means reading a full-file diff to find it.
    #[test]
    #[ignore = "writes into docs/lookout; run it deliberately"]
    fn write_the_gallery() {
        // Absolute, derived from the manifest, so it lands in the same
        // place whatever directory the run started in.
        let dir = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/lookout"));
        std::fs::create_dir_all(dir).unwrap();

        let (plain, ansi) = gallery_text();
        std::fs::write(dir.join("frames.txt"), &plain).unwrap();
        std::fs::write(dir.join("frames.ansi"), &ansi).unwrap();

        // A live assertion, not a `timeout`: this function is synchronous,
        // so a `tokio::time::timeout` around it would complete on its first
        // poll and bound nothing at all. What can actually go wrong here is
        // a scene rendering empty, and that is what these two check.
        assert!(
            plain.lines().count() > 100,
            "every scene in the gallery is more than a hundred lines together"
        );
        assert_eq!(plain.matches("=== ").count(), Scene::ALL.len());
    }
}