shep 0.7.4

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

use std::path::PathBuf;
use std::time::Instant;

use serde_json::{Map, Value};
use shep_core::config::{ApplyGroup, GROUP_ORDER, apply_group, flockfile_schema_json};
use shep_core::protocol::{EnvValue, SheepConfigView};
use shep_core::values::{MemSize, UpDuration};

use super::field::{FieldKind, FieldSet, ListItem, ValueKind};
use super::viewport::Viewport;

/// Which thing the pane is editing.
///
/// Two things, and they are not the same shape of edit. A sheep's config is
/// shep's own document, so shep knows what every field costs; a dog's
/// section belongs to the dog, so shep publishes the change and the dog
/// decides what to reload, which is what [`ConfigPane::cost`]'s [`Option`]
/// is for.
///
/// `Debug` is derived (IR-41): a name and a binary's path, neither of which
/// is a value the pane withholds. A dog's section can carry a credential and
/// is held on [`ConfigPane`] instead, behind that type's own redacted
/// `Debug`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaneTarget {
    /// One sheep, by name.
    Sheep {
        /// The sheep.
        name: String,
    },
    /// One dog, by name, with the binary its schema was probed from.
    Dog {
        /// The dog.
        name: String,
        /// The adopted binary, or [`None`] for a built-in, whose schema
        /// comes from `crate::dog::builtin_schema`, since a built-in dog is
        /// this same binary. Kept so a re-probe asks the same path the pane
        /// opened on.
        adopted_path: Option<PathBuf>,
    },
}

impl PaneTarget {
    /// The target's name.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Sheep { name } | Self::Dog { name, .. } => name,
        }
    }
}

/// Why a row cannot be edited from the pane.
///
/// Two different facts, and an operator has to be able to tell them apart:
/// one says the field is beyond editing anywhere, the other says only that
/// this screen has no widget for its shape and a Flockfile still can.
/// Collapsing them into `Field::editable` alone is what made six rows claim
/// the wrong one.
///
/// `Debug` is derived (IR-41): a bare variant name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Lock {
    /// shep itself refuses a config write. Identity or flock shape rather
    /// than a runtime knob, so no surface changes it: `name` and
    /// `instances`, whose count moves through `shep stock` instead.
    Refused,
    /// The pane has no widget for this shape, and nothing more than that.
    /// `shep start <Flockfile>` writes these perfectly well, and
    /// [`ConfigPane::cost`] still reports what doing so would cost.
    NoWidget,
}

/// One row of the pane.
///
/// One variant, and it stays one: the env sub-screen went a different way
/// and got [`EnvRow`] of its own, because its `+ new` row is not an index
/// into anything and would have made this enum answer for two screens.
/// Named rather than left as a bare index anyway, a `usize` travelling
/// between [`ConfigPane::rows`], the viewport and the renderer says nothing
/// about what it indexes, and this one says.
///
/// `Debug` is derived (IR-41): an index.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaneRow {
    /// Index into [`ConfigPane::fields`].
    Field(usize),
}

/// One config field's new value, on its way out of the pane.
///
/// A newtype for the reason [`EnvValue`] is one: `cwd` and `script`
/// routinely hold a home directory and `args` holds a token, so
/// [`ConfigPane`]'s own `Debug` already withholds the map these come out
/// of. A bare [`Value`] travels on into `Sent::ApplyField`, which derives
/// `Debug`, so the newtype rides with the value wherever it goes rather
/// than depending on every type along the way to redact it separately.
///
/// The wire field itself (`Request::SetSheepField`) stays a bare
/// [`Value`] deliberately: `env` is the one field `AppConfig`'s own
/// `Debug` redacts, and `cwd` prints in the clear on every request that
/// carries a whole config, so a newtype there would protect one copy of
/// a value the protocol prints three other ways. This one guards
/// lookout, where a live value must never print.
///
/// `Debug` is manual and redacted (IR-41), exact-string-tested below. It
/// names the JSON type and nothing else, which is what a diagnostic
/// needs and is not a value.
#[derive(Clone, PartialEq, Eq)]
pub struct FieldValue(Value);

impl FieldValue {
    /// The value, for the request that carries it.
    #[must_use]
    pub fn as_value(&self) -> &Value {
        &self.0
    }
}

impl From<Value> for FieldValue {
    fn from(value: Value) -> Self {
        Self(value)
    }
}

/// Prints the JSON type and never the value. See the type doc for why.
/// Exact-string-tested below (`a_field_values_debug_names_no_value`) so a
/// future `#[derive(Debug)]` fails that test instead of silently reopening
/// the leak.
impl core::fmt::Debug for FieldValue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let kind = match &self.0 {
            Value::Null => "null",
            Value::Bool(_) => "bool",
            Value::Number(_) => "number",
            Value::String(_) => "string",
            Value::Array(_) => "array",
            Value::Object(_) => "object",
        };
        write!(f, "FieldValue(<{kind}>)")
    }
}

/// One edit, ready to send.
///
/// Two variants, and they leave by their own doors: a [`Self::Set`] as a
/// `Request::SetSheepField` and a [`Self::SetEnv`] as a
/// `Request::SetSheepEnv`. Both record an operator override for one key,
/// never a template merge: a one-app `Request::ApplyConfig` at
/// `ResetDepth::File` would treat the edit as a template load, so it would
/// vanish from `overridden` the moment it landed and the pane's `*` marker
/// would never appear for it.
///
/// `Debug` is derived, safe because both value types redact themselves:
/// [`FieldValue`] names a JSON type and [`EnvValue`] names a byte count.
/// One mechanism on the value beats two on the types that carry it; see
/// [`FieldValue`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaneEdit {
    /// Set the config field `key` to `value`.
    Set {
        /// The field.
        key: String,
        /// The new value, already typed to the field's kind.
        value: FieldValue,
    },
    /// Set the env key `key`, or with [`None`] remove it.
    SetEnv {
        /// The env key.
        key: String,
        /// The value, or [`None`] to remove the key.
        value: Option<EnvValue>,
    },
}

impl PaneEdit {
    /// Which field or env key this edit moves.
    #[must_use]
    pub fn key(&self) -> &str {
        match self {
            Self::Set { key, .. } | Self::SetEnv { key, .. } => key,
        }
    }
}

/// The pane's one in-flight edit.
///
/// One field on [`ConfigPane`] rather than several [`Option`]s, for the
/// reason the settings screen's own `Pending` gives: typing, armed and sent
/// cannot overlap, and saying so in the type beats saying so in a guard.
///
/// Shared by the field list and the env sub-screen. Both arm, and neither
/// needed a mechanism of its own: `view::status` renders whatever is here,
/// `Msg::Tick` expires whatever is armed, and the only thing that differs
/// is the [`PaneEdit`] variant inside.
///
/// `Debug` is manual and redacted (IR-41), exact-string-tested below. Two
/// of the three variants would otherwise print a value: `Typing`'s buffer
/// is what the operator is halfway through typing, which on the env screen
/// is a secret, and `Armed`/`Sent`'s `text` is a rendered sentence that
/// quotes a config value verbatim. The env sentence deliberately does not
/// quote its own value ([`ConfigPane::confirm_text`]), but the field
/// sentence does, so the whole field is withheld rather than one arm of it.
#[derive(Clone, PartialEq, Eq)]
pub enum PanePending {
    /// A text edit under construction. Owns [`super::app::InputMode::Text`]
    /// for as long as it exists.
    Typing {
        /// Which field.
        key: String,
        /// What has been typed so far.
        buffer: String,
    },
    /// Waiting for `Enter`. Nothing has gone out.
    Armed {
        /// The candidate.
        edit: PaneEdit,
        /// The question it reads as, rendered once at arm time.
        text: String,
        /// When it was armed. Only an armed edit expires.
        at: Instant,
    },
    /// Gone out, awaiting the shepherd's reply.
    ///
    /// `ticket` is what a landing reply is matched against
    /// ([`ConfigPane::settle`]). A key would still confuse two writes to
    /// the same field in flight at once; a ticket, minted fresh per send,
    /// cannot.
    Sent {
        /// The write this is waiting on. Minted by `App` per send, so no
        /// two are ever equal.
        ticket: u64,
        /// Which field or env key is in flight. Not what a reply is
        /// matched against (see `ticket`), but what a `{:?}` names.
        key: String,
        /// The rendered question, so the prompt line does not change
        /// wording between the question and its own answer.
        text: String,
    },
}

/// Prints the key and never a buffer or a rendered sentence. See the type
/// doc for why. Exact-string-tested below
/// (`debug_names_no_value_on_a_pane_pending`).
impl core::fmt::Debug for PanePending {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Typing { key, buffer } => write!(
                f,
                "PanePending::Typing {{ key: {key:?}, buffer: <{} chars> }}",
                buffer.chars().count()
            ),
            Self::Armed { edit, .. } => write!(f, "PanePending::Armed {{ edit: {edit:?} }}"),
            Self::Sent { ticket, key, .. } => {
                write!(f, "PanePending::Sent {{ ticket: {ticket}, key: {key:?} }}")
            }
        }
    }
}

/// One row of the env sub-screen.
///
/// `Debug` is derived (IR-41): an index, or a marker for the row that adds
/// a key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnvRow {
    /// Index into [`EnvPane::keys`].
    Key(usize),
    /// The `+ new` row.
    New,
}

/// The env sub-screen: key names, and a write-only editor over them.
///
/// Write-only, not a shortcut: `Request::SheepConfig` answers with the
/// env keys and no values, so this screen has nothing to seed an editor
/// with and never asks for one. A value goes out through
/// `Request::SetSheepEnv`, one key at a time.
///
/// `Debug` is manual and redacted (IR-41), exact-string-tested below. Key
/// names are withheld for the reason [`ConfigPane`]'s own `Debug`
/// withholds `env_keys`; the buffer is withheld because on this screen it
/// is the secret itself, the whole of `DB_PASSWORD=hunter2` in one
/// string.
#[derive(Clone, PartialEq, Eq)]
pub struct EnvPane {
    keys: Vec<String>,
    view: Viewport,
    /// `Some((None, buffer))` on the `+ new` row, where the buffer is
    /// `KEY=value`; `Some((Some(key), buffer))` on an existing key, where
    /// it is the value alone.
    typing: Option<(Option<String>, String)>,
}

/// Prints counts and never a key or a buffer. See the type doc for why.
/// Exact-string-tested below (`an_env_panes_debug_names_no_key_and_no_value`).
impl core::fmt::Debug for EnvPane {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "EnvPane {{ keys: {}, cursor: {}, typing: {} }}",
            self.keys.len(),
            self.view.cursor(),
            self.typing.is_some()
        )
    }
}

impl EnvPane {
    /// A sub-screen over `keys`, cursor at the top and nothing being typed.
    #[must_use]
    pub fn new(keys: Vec<String>) -> Self {
        Self {
            keys,
            view: Viewport::new(),
            typing: None,
        }
    }

    /// One row per key, then the `+ new` row.
    #[must_use]
    pub fn rows(&self) -> Vec<EnvRow> {
        let mut rows: Vec<EnvRow> = (0..self.keys.len()).map(EnvRow::Key).collect();
        rows.push(EnvRow::New);
        rows
    }

    /// The row under the cursor. Never [`None`]: [`Self::rows`] always ends
    /// with [`EnvRow::New`], so there is always at least one row.
    #[must_use]
    pub fn cursor(&self) -> Option<EnvRow> {
        let rows = self.rows();
        rows.get(self.view.cursor()).copied()
    }

    /// The key names, in display order.
    #[must_use]
    pub fn keys(&self) -> &[String] {
        &self.keys
    }

    /// The key the cursor is on, or [`None`] on the `+ new` row.
    ///
    /// What a refresh carries across instead of the cursor's index. A
    /// removal shortens the list, so an index that survived would name a
    /// different key afterwards and a reflexive second `Enter` would arm a
    /// write against the neighbour.
    #[must_use]
    pub fn cursor_key(&self) -> Option<&str> {
        match self.cursor()? {
            EnvRow::Key(index) => self.keys.get(index).map(String::as_str),
            EnvRow::New => None,
        }
    }

    /// The cursor and offset.
    #[must_use]
    pub fn view(&self) -> &Viewport {
        &self.view
    }

    /// What is being typed: which key it is for (`None` on the `+ new`
    /// row, where the buffer is the whole `KEY=value`) and the buffer.
    /// [`None`] while no editor is open.
    #[must_use]
    pub fn typing(&self) -> Option<(Option<&str>, &str)> {
        self.typing
            .as_ref()
            .map(|(key, buffer)| (key.as_deref(), buffer.as_str()))
    }

    /// Records the terminal's height, in rows of data.
    pub fn set_rows(&mut self, rows: usize) {
        let len = self.rows().len();
        self.view.set_rows(rows, len);
    }

    pub(super) fn move_by(&mut self, delta: isize) {
        let len = self.rows().len();
        self.view.move_by(delta, len);
    }

    pub(super) fn move_to_first(&mut self) {
        let len = self.rows().len();
        self.view.move_to(0, len);
    }

    pub(super) fn move_to_last(&mut self) {
        let len = self.rows().len();
        self.view.move_to(len.saturating_sub(1), len);
    }

    /// Adopts a previous sub-screen's offset, and puts the cursor back on
    /// `cursor_key` by name.
    ///
    /// A set re-reads the whole config, so without this the operator
    /// would be thrown back to the first key by their own keystroke.
    /// Carrying the cursor's index instead is worse: a removal shortens
    /// the list, so the same index names the next key down and a
    /// reflexive second `Enter` arms a write against a neighbour nobody
    /// chose.
    ///
    /// A key that is gone puts the cursor on the `+ new` row instead of
    /// whatever took its place, since that is the one row where `Enter`
    /// destroys nothing.
    pub(super) fn adopt_view(&mut self, view: Viewport, cursor_key: Option<&str>) {
        self.view = view;
        let len = self.rows().len();
        let index = match cursor_key {
            Some(key) => self
                .keys
                .iter()
                .position(|name| name == key)
                .unwrap_or(len - 1),
            None => len - 1,
        };
        self.view.move_to(index, len);
    }

    /// Opens the editor on the row under the cursor.
    ///
    /// On a key: an empty buffer, because the value is never read back and
    /// seeding one would mean this screen had been told a secret it is
    /// built not to hear. On `+ new`: also empty, and the operator types
    /// `KEY=value`.
    pub fn begin_typing(&mut self) {
        self.typing = match self.cursor() {
            Some(EnvRow::Key(index)) => Some((Some(self.keys[index].clone()), String::new())),
            Some(EnvRow::New) => Some((None, String::new())),
            None => None,
        };
    }

    /// Appends one typed character.
    pub fn type_char(&mut self, typed: char) {
        if let Some((_, buffer)) = self.typing.as_mut() {
            buffer.push(typed);
        }
    }

    /// Removes the last typed character.
    pub fn type_backspace(&mut self) {
        if let Some((_, buffer)) = self.typing.as_mut() {
            buffer.pop();
        }
    }

    /// Drops the editor, leaving the sub-screen open.
    pub fn abandon_typing(&mut self) {
        self.typing = None;
    }

    /// Closes the editor and reads what it holds.
    ///
    /// `(key, Some(value))` sets, `(key, None)` removes. [`None`] when
    /// nothing was being typed, and for a `+ new` buffer with no `=` or an
    /// empty key: neither names a key, and a screen that guessed one would
    /// be inventing the operator's intent.
    pub fn apply_typing(&mut self) -> Option<(String, Option<String>)> {
        let (key, buffer) = self.typing.take()?;
        match key {
            // An existing key with an empty buffer is a removal. There is
            // no separate unset key on this screen, and no widget for one
            // either: an empty value and no value are the same keystroke
            // here, and removing is the one of the two shep can express.
            Some(key) => Some((key, (!buffer.is_empty()).then_some(buffer))),
            None => {
                let (key, value) = buffer.split_once('=')?;
                if key.is_empty() {
                    return None;
                }
                Some((key.to_owned(), Some(value.to_owned())))
            }
        }
    }
}

/// One row of the list sub-screen.
///
/// `Debug` is derived (IR-41): an index, or a marker for the row that adds
/// an element.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListRow {
    /// Index into [`ListPane::elements`].
    Item(usize),
    /// The `+ new` row.
    New,
}

/// The list sub-screen: one array field's elements, and an editor over
/// them.
///
/// Values are drawn, unlike [`EnvPane`]: an array arrives with the
/// config, so hiding an element would leave the cursor unable to say
/// which one it holds. `Debug` is manual and redacted (IR-41),
/// exact-string-tested below, for the same reason as [`ConfigPane`]'s:
/// `args` can carry a token an operator typed. Elements are held as
/// text; [`ListItem`] turns the array back to JSON on write.
#[derive(Clone, PartialEq, Eq)]
pub struct ListPane {
    key: String,
    item: ListItem,
    elements: Vec<String>,
    view: Viewport,
    /// `Some((Some(index), buffer))` on an element, `Some((None, buffer))`
    /// on the `+ new` row.
    typing: Option<(Option<usize>, String)>,
}

impl ListPane {
    /// A sub-screen over one array field, cursor at the top and nothing
    /// being typed.
    #[must_use]
    pub fn new(key: String, item: ListItem, elements: Vec<String>) -> Self {
        Self {
            key,
            item,
            elements,
            view: Viewport::new(),
            typing: None,
        }
    }

    /// The field this array belongs to, which is also the key a write
    /// carries.
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// What the elements are, for the editor that parses one back.
    #[must_use]
    pub fn item(&self) -> ListItem {
        self.item
    }

    /// The elements, in the order the array holds them.
    #[must_use]
    pub fn elements(&self) -> &[String] {
        &self.elements
    }

    /// One row per element, then the `+ new` row.
    #[must_use]
    pub fn rows(&self) -> Vec<ListRow> {
        let mut rows: Vec<ListRow> = (0..self.elements.len()).map(ListRow::Item).collect();
        rows.push(ListRow::New);
        rows
    }

    /// The row under the cursor. Never [`None`]: [`Self::rows`] always ends
    /// with [`ListRow::New`], so there is always at least one row.
    #[must_use]
    pub fn cursor(&self) -> Option<ListRow> {
        self.rows().get(self.view.cursor()).copied()
    }

    /// The cursor and offset.
    #[must_use]
    pub fn view(&self) -> &Viewport {
        &self.view
    }

    /// What is being typed: which element it is for ([`None`] on the `+
    /// new` row) and the buffer. [`None`] while no editor is open.
    #[must_use]
    pub fn typing(&self) -> Option<(Option<usize>, &str)> {
        self.typing
            .as_ref()
            .map(|(index, buffer)| (*index, buffer.as_str()))
    }

    /// Records the terminal's height, in rows of data.
    pub fn set_rows(&mut self, rows: usize) {
        let len = self.rows().len();
        self.view.set_rows(rows, len);
    }

    pub(super) fn move_by(&mut self, delta: isize) {
        let len = self.rows().len();
        self.view.move_by(delta, len);
    }

    pub(super) fn move_to(&mut self, index: usize) {
        let len = self.rows().len();
        self.view.move_to(index, len);
    }

    pub(super) fn move_to_first(&mut self) {
        self.move_to(0);
    }

    pub(super) fn move_to_last(&mut self) {
        let len = self.rows().len();
        self.move_to(len.saturating_sub(1));
    }

    /// Adopts a previous sub-screen's cursor and offset, clamped to this
    /// one's own row count.
    ///
    /// By index rather than by name, unlike [`EnvPane::adopt_view`]: an
    /// element has no name, and its position is the only thing that
    /// identifies it. A cursor past the end lands on the `+ new` row,
    /// which is the one row where `Enter` destroys nothing.
    pub(super) fn adopt_view(&mut self, view: Viewport) {
        self.view = view;
        let len = self.rows().len();
        self.view.clamp(len);
    }

    /// Opens the editor on the row under the cursor, seeded with the
    /// element it is on and empty on `+ new`.
    pub fn begin_typing(&mut self) {
        self.typing = match self.cursor() {
            Some(ListRow::Item(index)) => self
                .elements
                .get(index)
                .map(|element| (Some(index), element.clone())),
            Some(ListRow::New) => Some((None, String::new())),
            None => None,
        };
    }

    /// Appends one typed character.
    pub fn type_char(&mut self, typed: char) {
        if let Some((_, buffer)) = self.typing.as_mut() {
            buffer.push(typed);
        }
    }

    /// Removes the last typed character.
    pub fn type_backspace(&mut self) {
        if let Some((_, buffer)) = self.typing.as_mut() {
            buffer.pop();
        }
    }

    /// Drops the editor, leaving the sub-screen open.
    pub fn abandon_typing(&mut self) {
        self.typing = None;
    }

    /// Closes the editor and reads what it holds.
    ///
    /// [`None`] three ways, and only one of them closes the editor: an
    /// empty buffer is nothing to write and leaves the array alone, since
    /// `d` is the key that removes an element. An integer element whose
    /// buffer does not parse keeps the editor open, the same rule
    /// [`ConfigPane::apply_typing`] follows, because the operator is
    /// mid-word rather than wrong.
    pub fn apply_typing(&mut self) -> Option<String> {
        let (_, buffer) = self.typing.as_ref()?;
        if self.item == ListItem::Integer && buffer.parse::<i64>().is_err() && !buffer.is_empty() {
            return None;
        }
        let (_, buffer) = self.typing.take()?;
        (!buffer.is_empty()).then_some(buffer)
    }

    /// The elements with `text` written at the cursor, appended on the `+
    /// new` row. [`None`] when the cursor names no element.
    pub(super) fn with_element(&self, text: String) -> Option<Vec<String>> {
        let mut elements = self.elements.clone();
        match self.cursor()? {
            ListRow::Item(index) => *elements.get_mut(index)? = text,
            ListRow::New => elements.push(text),
        }
        Some(elements)
    }

    /// The elements without the one under the cursor. [`None`] on the `+
    /// new` row, which holds no element to remove.
    pub(super) fn without_element(&self) -> Option<Vec<String>> {
        let ListRow::Item(index) = self.cursor()? else {
            return None;
        };
        let mut elements = self.elements.clone();
        (index < elements.len()).then(|| {
            elements.remove(index);
            elements
        })
    }

    /// The elements with the one under the cursor moved `delta` places.
    /// [`None`] on the `+ new` row and at either end.
    pub(super) fn reordered(&self, delta: isize) -> Option<Vec<String>> {
        let ListRow::Item(index) = self.cursor()? else {
            return None;
        };
        let target = usize::try_from(isize::try_from(index).ok()? + delta).ok()?;
        if target >= self.elements.len() {
            return None;
        }
        let mut elements = self.elements.clone();
        elements.swap(index, target);
        Some(elements)
    }
}

/// The whole array as JSON, ready for `Request::SetSheepField`.
///
/// An integer element that does not parse travels as the string it is, so
/// the daemon refuses it by name instead of this guessing a number. Only
/// reachable for an element the config itself carried, since
/// [`ListPane::apply_typing`] refuses to arm one an operator typed.
fn list_value(item: ListItem, elements: &[String]) -> Value {
    let element = |text: &String| match item {
        ListItem::Text => Value::String(text.clone()),
        ListItem::Integer => text
            .parse::<i64>()
            .map_or_else(|_| Value::String(text.clone()), Value::from),
    };
    Value::Array(elements.iter().map(element).collect())
}

/// The state of an open pane.
///
/// `Debug` is manual and redacted (IR-41): `values` is a sheep's config with
/// `env` already stripped by [`SheepConfigView::new`], but `args` and `cwd`
/// are still in it and routinely carry a token or a home directory.
/// `env_keys` is a key set, which is itself worth keeping out of a log, and
/// the same reasoning [`SheepConfigView`]'s own `Debug` gives applies here
/// unchanged: this type is a copy of that one's payload.
#[derive(Clone)]
pub struct ConfigPane {
    target: PaneTarget,
    fields: FieldSet,
    values: Map<String, Value>,
    env_keys: Vec<String>,
    overridden: Vec<String>,
    /// Field names parked until the next respawn, as the shepherd reported
    /// them. Nothing to do with [`Self::pending_edit`], which is this
    /// pane's own one in-flight edit; the two words come from opposite
    /// ends and the collision is the shepherd's.
    pending: Vec<String>,
    view: Viewport,
    pending_edit: Option<PanePending>,
    env: Option<EnvPane>,
    /// The open list sub-screen. Never open at the same time as
    /// [`Self::env`]: each opens on a field of its own kind, and `Escape`
    /// closes whichever is up before the pane.
    list: Option<ListPane>,
    /// Whether `h` is showing the selected field's own help text.
    help_open: bool,
    /// The dog's `[<name>]` table as TOML text, and [`None`] for a sheep.
    ///
    /// Kept beside the parsed `values` rather than instead of them, because
    /// the two answer different questions: `values` is what the rows render,
    /// and this is what a write edits. `Request::SetDogConfig` replaces the
    /// whole section, so an edit that re-rendered it from `values` would
    /// throw away every comment the operator wrote. See
    /// [`Self::edited_section`].
    section: Option<String>,
}

impl core::fmt::Debug for ListPane {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "ListPane {{ key: {:?}, item: {:?}, elements: {}, typing: {} }}",
            self.key,
            self.item,
            self.elements.len(),
            if self.typing.is_some() {
                "some"
            } else {
                "none"
            }
        )
    }
}

impl core::fmt::Debug for ConfigPane {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "ConfigPane {{ target: {:?}, fields: {}, env_keys: {}, cursor: {} }}",
            self.target,
            self.fields.len(),
            self.env_keys.len(),
            self.view.cursor()
        )
    }
}

impl ConfigPane {
    /// A pane over one sheep's config, read off the Flockfile schema.
    ///
    /// The schema is the field list: it already carries every property's
    /// type, default and group, so the pane reads the same document `shep
    /// init` scaffolds from rather than keeping a second list of 40 names
    /// in step with it.
    #[must_use]
    pub fn sheep(view: SheepConfigView) -> Self {
        let schema = flockfile_schema_json().to_value();
        let defs = schema
            .get("$defs")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        let properties = defs
            .get("AppConfig")
            .and_then(|app| app.get("properties"))
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        let set = FieldSet::from_properties(&properties, &defs, GROUP_ORDER);
        // A Structural field is identity or flock shape, not a runtime knob:
        // `name` cannot drift without becoming a different sheep, and
        // `instances` is routed through `handle_scale` rather than through a
        // config write at all. Read-only here, so the pane never offers an
        // edit the daemon would refuse.
        let fields = FieldSet::from_fields(
            set.fields()
                .iter()
                .cloned()
                .map(|mut field| {
                    if apply_group(&field.key) == ApplyGroup::Structural {
                        field.editable = false;
                    }
                    field
                })
                .collect(),
            GROUP_ORDER,
        );
        let values = serde_json::to_value(&view.config)
            .ok()
            .and_then(|value| value.as_object().cloned())
            .unwrap_or_default();
        Self {
            target: PaneTarget::Sheep { name: view.name },
            fields,
            values,
            env_keys: view.env_keys,
            overridden: view.overridden,
            pending: view.pending,
            view: Viewport::new(),
            pending_edit: None,
            env: None,
            list: None,
            help_open: false,
            section: None,
        }
    }

    /// A pane over one dog's `[<name>]` section.
    ///
    /// `schema` is the dog's own answer to the schema flag, probed at
    /// open rather than read from anywhere; `section` is the table as
    /// `Request::DogConfig` rendered it, empty when `dogs.toml` has none.
    ///
    /// Flat, in schema order, with no group headers: a dog's schema
    /// carries no `init.group`. A [`FieldKind::Map`] or
    /// [`FieldKind::List`] row is marked not editable and draws
    /// [`Lock::NoWidget`].
    #[must_use]
    pub fn dog(
        name: String,
        adopted_path: Option<PathBuf>,
        schema: Value,
        section: String,
    ) -> Self {
        let defs = schema
            .get("$defs")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        let properties = schema
            .get("properties")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        let set = FieldSet::from_properties(&properties, &defs, &[]);
        let fields = FieldSet::from_fields(
            set.fields()
                .iter()
                .cloned()
                .map(|mut field| {
                    if matches!(field.kind, FieldKind::Map | FieldKind::List(_)) {
                        field.editable = false;
                    }
                    field
                })
                .collect(),
            &[],
        );
        let values: Map<String, Value> = section
            .parse::<toml::Table>()
            .ok()
            .and_then(|table| serde_json::to_value(table).ok())
            .and_then(|value| value.as_object().cloned())
            .unwrap_or_default();
        Self {
            target: PaneTarget::Dog { name, adopted_path },
            fields,
            values,
            env_keys: Vec::new(),
            overridden: Vec::new(),
            pending: Vec::new(),
            view: Viewport::new(),
            pending_edit: None,
            env: None,
            list: None,
            help_open: false,
            section: Some(section),
        }
    }

    /// The section with `edit` applied, comments and key order intact, ready
    /// for `Request::SetDogConfig`. [`None`] for a sheep pane, for an env
    /// edit, and for a section that does not parse.
    ///
    /// `toml_edit` rather than a re-render of [`Self::values`], and that is
    /// the whole reason this method exists: the request replaces the section
    /// wholesale, so a re-render would delete every comment in it on the
    /// operator's own keystroke.
    ///
    /// A `null` value removes the key, which is how the pane's empty buffer
    /// unsets one, and is what puts the dog back on its own default.
    #[must_use]
    pub fn edited_section(&self, edit: &PaneEdit) -> Option<String> {
        let section = self.section.as_deref()?;
        let PaneEdit::Set { key, value } = edit else {
            return None;
        };
        let mut doc: toml_edit::DocumentMut = section.parse().ok()?;
        match value.as_value() {
            Value::Null => {
                doc.remove(key);
            }
            Value::Bool(flag) => doc[key] = toml_edit::value(*flag),
            // A number that is neither an i64 nor an f64 is not something
            // TOML can hold, so the edit is refused rather than rounded.
            Value::Number(number) => match (number.as_i64(), number.as_f64()) {
                (Some(int), _) => doc[key] = toml_edit::value(int),
                (None, Some(float)) => doc[key] = toml_edit::value(float),
                (None, None) => return None,
            },
            Value::String(text) => doc[key] = toml_edit::value(text.as_str()),
            other => doc[key] = toml_edit::value(other.to_string()),
        }
        Some(doc.to_string())
    }

    /// The one in-flight edit, or [`None`].
    #[must_use]
    pub fn pending_edit(&self) -> Option<&PanePending> {
        self.pending_edit.as_ref()
    }

    /// The open env sub-screen, or [`None`] when the field list is what is
    /// on screen.
    #[must_use]
    pub fn env(&self) -> Option<&EnvPane> {
        self.env.as_ref()
    }

    pub(super) fn env_mut(&mut self) -> Option<&mut EnvPane> {
        self.env.as_mut()
    }

    /// Opens the env sub-screen over this sheep's key names.
    pub(super) fn open_env(&mut self) {
        self.env = Some(EnvPane::new(self.env_keys.clone()));
    }

    /// Closes it, leaving the field list up.
    pub(super) fn close_env(&mut self) {
        self.env = None;
    }

    /// The open list sub-screen, or [`None`] when the field list is what is
    /// on screen.
    #[must_use]
    pub fn list(&self) -> Option<&ListPane> {
        self.list.as_ref()
    }

    pub(super) fn list_mut(&mut self) -> Option<&mut ListPane> {
        self.list.as_mut()
    }

    /// Opens the list sub-screen over the array field under the cursor.
    /// Does nothing on any other row.
    pub(super) fn open_list(&mut self) {
        let Some(PaneRow::Field(index)) = self.cursor() else {
            return;
        };
        let Some(field) = self.fields.fields().get(index) else {
            return;
        };
        let FieldKind::List(item) = field.kind else {
            return;
        };
        let key = field.key.clone();
        let elements = self.elements_of(&key);
        self.list = Some(ListPane::new(key, item, elements));
    }

    /// Closes it, leaving the field list up.
    pub(super) fn close_list(&mut self) {
        self.list = None;
    }

    /// `key`'s array as one string per element, empty when the field holds
    /// no array. A non-scalar element renders as compact JSON, which is
    /// what an editor would have to type back.
    fn elements_of(&self, key: &str) -> Vec<String> {
        let Some(Value::Array(values)) = self.values.get(key) else {
            return Vec::new();
        };
        values
            .iter()
            .map(|value| match value {
                Value::String(text) => text.clone(),
                other => other.to_string(),
            })
            .collect()
    }

    /// Arms the whole array with `text` written at the sub-screen's cursor,
    /// appended when the cursor is on `+ new`.
    ///
    /// The whole array travels as one value: `Request::SetSheepField`
    /// carries one field, so an element is not a thing the wire can name.
    pub(super) fn arm_list_element(&mut self, text: String, now: Instant) {
        let Some(elements) = self.list.as_ref().and_then(|list| list.with_element(text)) else {
            return;
        };
        self.arm_list(elements, now);
    }

    /// Arms the whole array without the element under the cursor.
    pub(super) fn arm_list_removal(&mut self, now: Instant) {
        let Some(elements) = self.list.as_ref().and_then(ListPane::without_element) else {
            return;
        };
        self.arm_list(elements, now);
    }

    /// Arms the whole array with the element under the cursor moved `delta`
    /// places. Does nothing at either end, where there is nowhere to move.
    pub(super) fn arm_list_reorder(&mut self, delta: isize, now: Instant) {
        let Some(elements) = self.list.as_ref().and_then(|list| list.reordered(delta)) else {
            return;
        };
        self.arm_list(elements, now);
    }

    fn arm_list(&mut self, elements: Vec<String>, now: Instant) {
        let Some(list) = self.list.as_ref() else {
            return;
        };
        let edit = PaneEdit::Set {
            key: list.key().to_owned(),
            value: list_value(list.item(), &elements).into(),
        };
        let text = self.confirm_text(&edit);
        self.pending_edit = Some(PanePending::Armed {
            edit,
            text,
            at: now,
        });
    }

    /// Whether `h` is showing the selected field's own help text.
    #[must_use]
    pub fn help_open(&self) -> bool {
        self.help_open
    }

    /// Flips it.
    pub(super) fn toggle_help(&mut self) {
        self.help_open = !self.help_open;
    }

    /// Dismisses it. A no-op when it is already closed, so `Escape` can
    /// call this unconditionally.
    pub(super) fn close_help(&mut self) {
        self.help_open = false;
    }

    /// Carries a previous pane's help visibility across a rebuild, the
    /// same reason [`Self::adopt_view`] carries the cursor: a re-read must
    /// not dismiss a note the operator has not dismissed.
    pub(super) fn set_help_open(&mut self, open: bool) {
        self.help_open = open;
    }

    /// The key under the cursor, and why the pane will not edit it, when it
    /// will not. [`None`] both for a row that edits and for no row at all.
    ///
    /// The one place a caller asks "may I edit what is selected", so a
    /// refusal is raised for the right one of [`Lock`]'s two reasons rather
    /// than for a generic third.
    #[must_use]
    pub fn cursor_lock(&self) -> Option<(&str, Lock)> {
        let PaneRow::Field(index) = self.cursor()?;
        let field = self.fields.fields().get(index)?;
        self.lock(&field.key).map(|lock| (field.key.as_str(), lock))
    }

    /// The kind of widget the row under the cursor wants, or [`None`] for
    /// no row at all.
    #[must_use]
    pub fn cursor_kind(&self) -> Option<&FieldKind> {
        let PaneRow::Field(index) = self.cursor()?;
        self.fields.fields().get(index).map(|field| &field.kind)
    }

    /// Arms the opposite of what a bool holds, or the next name in a
    /// choice. Does nothing for a locked field, or for one no keystroke
    /// cycles ([`FieldKind::Text`], [`FieldKind::Integer`],
    /// [`FieldKind::Map`], [`FieldKind::Opaque`]).
    pub fn cycle(&mut self, now: Instant) {
        let Some(PaneRow::Field(index)) = self.cursor() else {
            return;
        };
        let Some(field) = self.fields.fields().get(index) else {
            return;
        };
        if self.lock(&field.key).is_some() {
            return;
        }
        // The base is whatever is already armed for this field, so a
        // second `space` walks the cycle instead of re-deriving the
        // stored value. An arm for a different field is not a base: the
        // cursor moved, so this starts fresh from the stored value.
        let armed_here = match &self.pending_edit {
            Some(PanePending::Armed {
                edit: PaneEdit::Set { key, value },
                ..
            }) if *key == field.key => Some(value.as_value()),
            _ => None,
        };
        let current = armed_here.or_else(|| self.values.get(&field.key));
        let next = match &field.kind {
            FieldKind::Bool => Value::Bool(!current.and_then(Value::as_bool).unwrap_or(false)),
            FieldKind::Choice(names) | FieldKind::Suggested(names) if !names.is_empty() => {
                let current = current.and_then(Value::as_str);
                let next = current
                    .and_then(|value| names.iter().position(|name| name == value))
                    .map_or(0, |i| (i + 1) % names.len());
                Value::String(names[next].clone())
            }
            FieldKind::Choice(_)
            | FieldKind::Suggested(_)
            | FieldKind::Text
            | FieldKind::Integer
            | FieldKind::Map
            | FieldKind::List(_)
            | FieldKind::Opaque => return,
        };
        let edit = PaneEdit::Set {
            key: field.key.clone(),
            value: next.into(),
        };
        let text = self.confirm_text(&edit);
        self.pending_edit = Some(PanePending::Armed {
            edit,
            text,
            at: now,
        });
    }

    /// Opens the text editor on the row under the cursor. Does nothing for
    /// a locked field, or for one that is not typed.
    ///
    /// Seeded with what is on screen, except for a secret, which is seeded
    /// empty: the pane renders `<set>` for one and never holds the value,
    /// so a seed would have to invent it.
    pub fn begin_typing(&mut self) {
        let Some(PaneRow::Field(index)) = self.cursor() else {
            return;
        };
        let Some(field) = self.fields.fields().get(index) else {
            return;
        };
        if self.lock(&field.key).is_some()
            || !matches!(
                field.kind,
                FieldKind::Text | FieldKind::Integer | FieldKind::Suggested(_)
            )
        {
            return;
        }
        let seed = if field.secret {
            String::new()
        } else {
            match self.value(&field.key) {
                unset if unset == "(unset)" => String::new(),
                value => value,
            }
        };
        self.pending_edit = Some(PanePending::Typing {
            key: field.key.clone(),
            buffer: seed,
        });
    }

    /// Appends one typed character.
    pub fn type_char(&mut self, typed: char) {
        if let Some(PanePending::Typing { buffer, .. }) = self.pending_edit.as_mut() {
            buffer.push(typed);
        }
    }

    /// Removes the last typed character.
    pub fn type_backspace(&mut self) {
        if let Some(PanePending::Typing { buffer, .. }) = self.pending_edit.as_mut() {
            buffer.pop();
        }
    }

    /// Turns the buffer into an armed edit, typed to the field's kind.
    ///
    /// An empty buffer is `null`, which is how a nullable field is unset.
    /// An integer field whose buffer does not parse keeps the editor open
    /// rather than arming a string the daemon would refuse: the operator is
    /// mid-word, not wrong.
    pub fn apply_typing(&mut self, now: Instant) {
        let Some(PanePending::Typing { key, buffer }) = self.pending_edit.take() else {
            return;
        };
        let kind = self.fields.by_key(&key).map(|field| field.kind.clone());
        let value = match (kind, buffer.as_str()) {
            (_, "") => Value::Null,
            (Some(FieldKind::Integer), text) => match text.parse::<i64>() {
                Ok(number) => Value::from(number),
                Err(_) => {
                    self.pending_edit = Some(PanePending::Typing { key, buffer });
                    return;
                }
            },
            (_, text) => Value::String(text.to_owned()),
        };
        let edit = PaneEdit::Set {
            key,
            value: value.into(),
        };
        let text = self.confirm_text(&edit);
        self.pending_edit = Some(PanePending::Armed {
            edit,
            text,
            at: now,
        });
    }

    /// Drops an editor under construction, leaving the pane open.
    pub fn abandon_typing(&mut self) {
        if matches!(self.pending_edit, Some(PanePending::Typing { .. })) {
            self.pending_edit = None;
        }
    }

    /// Drops an armed edit. A request already sent is not cancellable by a
    /// keypress, the same rule every other confirm in lookout follows.
    pub fn cancel(&mut self) {
        if matches!(self.pending_edit, Some(PanePending::Armed { .. })) {
            self.pending_edit = None;
        }
    }

    /// Whether an edit is armed, the one state a stray key has to eat
    /// rather than also doing its ordinary job.
    #[must_use]
    pub fn is_armed(&self) -> bool {
        matches!(self.pending_edit, Some(PanePending::Armed { .. }))
    }

    /// When the armed edit was armed, for the expiry the tick runs.
    #[must_use]
    pub fn armed_at(&self) -> Option<Instant> {
        match self.pending_edit {
            Some(PanePending::Armed { at, .. }) => Some(at),
            _ => None,
        }
    }

    /// Takes the armed edit out and marks it sent under `ticket`. [`None`]
    /// when nothing is armed, and the pane is left exactly as it was.
    ///
    /// The ticket is the caller's, because the caller is what mints one per
    /// send and puts the same value on the request. See
    /// [`PanePending::Sent`].
    pub fn take_armed(&mut self, ticket: u64) -> Option<PaneEdit> {
        match self.pending_edit.take() {
            Some(PanePending::Armed { edit, text, .. }) => {
                self.pending_edit = Some(PanePending::Sent {
                    ticket,
                    key: edit.key().to_owned(),
                    text,
                });
                Some(edit)
            }
            other => {
                self.pending_edit = other;
                None
            }
        }
    }

    /// Clears the in-flight line for `ticket`, once the shepherd has
    /// answered that write and not another.
    ///
    /// Only clears [`PanePending::Sent`], the way [`Self::cancel`] only
    /// clears `Armed`: a reply landing while an editor is open must not
    /// throw the buffer away, since on the env screen that buffer is a
    /// secret the operator cannot read back.
    ///
    /// Only clears a `Sent` whose own ticket matches, since two writes
    /// can be in flight on the same field at once. Each request names
    /// its own key, so the values can never cross, but without a ticket
    /// match the wrong one's "sent, waiting" line would clear early.
    pub fn settle(&mut self, ticket: u64) {
        if matches!(&self.pending_edit, Some(PanePending::Sent { ticket: sent, .. }) if *sent == ticket)
        {
            self.pending_edit = None;
        }
    }

    /// Arms an env write from the sub-screen's own editor.
    ///
    /// Env arms like everything else: the daemon writes the override
    /// store on the same call, so the old value is gone the moment the
    /// reply lands, whether it takes effect at the next spawn or not.
    /// Under a write-only screen an overwrite is exactly as unrecoverable
    /// as a deletion, so a set arms too, not only a removal.
    pub(super) fn arm_env(&mut self, key: String, value: Option<EnvValue>, now: Instant) {
        let edit = PaneEdit::SetEnv { key, value };
        let text = self.confirm_text(&edit);
        self.pending_edit = Some(PanePending::Armed {
            edit,
            text,
            at: now,
        });
    }

    /// The question an armed edit reads as.
    ///
    /// It names the field's class, not what this write will do: only the
    /// shepherd knows whether a given write reaches the running child, so
    /// a class-based promise can be wrong. `NeedsRespawn` gets the same
    /// treatment, naming the reload it waits for rather than a restart it
    /// may not perform.
    ///
    /// Three things speak, and only this one is a prediction: the status
    /// bar after the reply reports what the shepherd actually did, and
    /// the row's `!` flag is the durable answer, read off the shepherd's
    /// parked-field list on every refresh.
    ///
    /// An env sentence names its key and never its value, unlike a field
    /// sentence, which quotes what it is setting: echoing a value just
    /// typed tells the operator nothing new, and would put a secret into
    /// a string that outlives the editor. A field marked
    /// `x-shep-secret` gets the same protection, rendered as `<set>`
    /// rather than a quoted credential.
    fn confirm_text(&self, edit: &PaneEdit) -> String {
        let name = self.target.name();
        let (key, value) = match edit {
            PaneEdit::SetEnv {
                key,
                value: Some(_),
            } => {
                return format!("set env {key}? {key} waits for `shep reload {name}`");
            }
            PaneEdit::SetEnv { key, value: None } => {
                return format!(
                    "remove env {key}? it waits for `shep reload {name}`, and lookout cannot \
                     read the value back to put it there again"
                );
            }
            PaneEdit::Set { key, value } => (key, value),
        };
        let secret = self.fields.by_key(key).is_some_and(|field| field.secret);
        let shown = match value.as_value() {
            Value::Null => "(unset)".to_owned(),
            _ if secret => "<set>".to_owned(),
            Value::String(text) => self.resolved_display(key, text),
            other => other.to_string(),
        };
        // `ApplyGroup` is `#[non_exhaustive]`, so the wildcard is required
        // rather than chosen; it answers the way `view::pane::cost_label`
        // does, a conservative promise of a restart rather than a silent
        // claim that the change applied. `Structural` cannot reach here.
        match self.cost(key) {
            Some(ApplyGroup::Live) => format!("set {key} = {shown}? {key} is a live setting"),
            Some(ApplyGroup::NextSpawn) => {
                format!("set {key} = {shown}? {key} is read when {name} spawns")
            }
            Some(_) => format!("set {key} = {shown}? {key} waits for `shep reload {name}`"),
            None => format!("set {key} = {shown}? {name} is told, and decides what to reload"),
        }
    }

    /// What is being edited.
    #[must_use]
    pub fn target(&self) -> &PaneTarget {
        &self.target
    }

    /// The form.
    #[must_use]
    pub fn fields(&self) -> &FieldSet {
        &self.fields
    }

    /// The current value of `key`, rendered for a cell.
    ///
    /// A scalar shows bare, an absent or `null` value shows `(unset)`, and
    /// anything else shows compact JSON. A sheep's `env` is the one field
    /// whose value this pane never holds, since the shepherd strips it on
    /// the way out, so it shows its key count instead, and the sub-screen
    /// shows the names.
    ///
    /// That special case is gated on the target, not on the key alone: a
    /// dog's schema is somebody else's, and one declaring a field named
    /// `env` reads its own section, not [`Self::env_keys`], which
    /// [`Self::dog`] always leaves empty.
    ///
    /// This is the parseable form: what [`Self::begin_typing`] seeds an
    /// editor with. [`Self::display_value`] is the one a row draws, and the
    /// two disagree exactly for a [`ValueKind`] field, where a seed has to
    /// stay something the daemon's own grammar still accepts.
    #[must_use]
    pub fn value(&self, key: &str) -> String {
        if key == "env" && matches!(self.target, PaneTarget::Sheep { .. }) {
            return match self.env_keys.len() {
                1 => "1 key".to_owned(),
                count => format!("{count} keys"),
            };
        }
        match self.values.get(key) {
            None | Some(Value::Null) => "(unset)".to_owned(),
            Some(Value::String(text)) => text.clone(),
            Some(Value::Bool(flag)) => flag.to_string(),
            Some(Value::Number(number)) => number.to_string(),
            Some(other) => other.to_string(),
        }
    }

    /// [`Self::value`], resolved through its own grammar for a
    /// [`MemSize`]/[`UpDuration`] field: what a row draws instead of the
    /// digits an operator would otherwise have to already know the
    /// convention for.
    #[must_use]
    pub fn display_value(&self, key: &str) -> String {
        self.resolved_display(key, &self.value(key))
    }

    /// `raw` resolved through `key`'s own grammar, when `key` is one of
    /// shep-core's unit types. Display only: [`Self::value`] is what an
    /// editor still seeds and sends, so a suffix minted here never travels
    /// back out as part of a value.
    ///
    /// A `raw` that fails to parse, including whatever is mid-edit, comes
    /// back unchanged: this has no business guessing at a string shep is
    /// about to refuse on its own.
    ///
    /// Only a bare number is annotated. A value naming its own unit is the
    /// operator's spelling and survives as written, so a `60s` on disk is
    /// never redrawn as the `1m` its own `Display` would canonicalize it to.
    fn resolved_display(&self, key: &str, raw: &str) -> String {
        if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
            return raw.to_owned();
        }
        match self.fields.by_key(key).and_then(|field| field.value_kind) {
            Some(ValueKind::MemSize) => raw
                .parse::<MemSize>()
                .map_or_else(|_| raw.to_owned(), |_| format!("{raw} B")),
            Some(ValueKind::UpDuration) => raw
                .parse::<UpDuration>()
                .map_or_else(|_| raw.to_owned(), |_| format!("{raw}ms")),
            None => raw.to_owned(),
        }
    }

    /// What changing `key` costs.
    ///
    /// [`None`] is not reachable for a sheep and is not dead weight either:
    /// a dog decides for itself what a published change reloads, so the
    /// answer for one is "the pane does not know", and every caller already
    /// renders that as an empty cost cell rather than as a guess.
    #[must_use]
    pub fn cost(&self, key: &str) -> Option<ApplyGroup> {
        match self.target {
            PaneTarget::Sheep { .. } => Some(apply_group(key)),
            // The dog decides, not shep. Said once at the foot of the pane
            // rather than guessed per row.
            PaneTarget::Dog { .. } => None,
        }
    }

    /// Why the pane will not edit `key`, or [`None`] when it will.
    ///
    /// [`Lock::Refused`] outranks [`Lock::NoWidget`]: a Structural field
    /// that also happened to have no widget is still refused by shep, which
    /// is the fact that survives the pane gaining every widget it lacks.
    #[must_use]
    pub fn lock(&self, key: &str) -> Option<Lock> {
        if self.cost(key) == Some(ApplyGroup::Structural) {
            return Some(Lock::Refused);
        }
        match self.fields.by_key(key) {
            Some(field) if !field.editable => Some(Lock::NoWidget),
            _ => None,
        }
    }

    /// Whether an operator has overridden `key`.
    #[must_use]
    pub fn is_overridden(&self, key: &str) -> bool {
        self.overridden.iter().any(|name| name == key)
    }

    /// Whether `key` is parked until the next respawn.
    #[must_use]
    pub fn is_pending(&self, key: &str) -> bool {
        self.pending.iter().any(|name| name == key)
    }

    /// How many fields wait for a reload or a restart.
    ///
    /// Every one of them is already written to the override store, so this
    /// counts what the running process has not taken yet, never what an
    /// operator could lose.
    #[must_use]
    pub fn parked_count(&self) -> usize {
        self.pending.len()
    }

    /// Whether a reload of this sheep overlaps its replacement or runs
    /// serially. Always [`ReloadKind::Overlap`] for a dog, which has no
    /// such fields to read.
    #[must_use]
    pub fn reload_kind(&self) -> ReloadKind {
        let flag = |key: &str| {
            self.values
                .get(key)
                .and_then(Value::as_bool)
                .unwrap_or(false)
        };
        let has_probe = self
            .values
            .get("readiness_probe")
            .is_some_and(|probe| !probe.is_null());
        reload_mode(flag("wait_ready"), has_probe, flag("reuse_port"))
    }

    /// The cursor and offset.
    #[must_use]
    pub fn view(&self) -> &Viewport {
        &self.view
    }

    /// Records the terminal's height, in rows of data.
    pub fn set_rows(&mut self, rows: usize) {
        let len = self.rows().len();
        self.view.set_rows(rows, len);
    }

    /// One row per field, in display order.
    #[must_use]
    pub fn rows(&self) -> Vec<PaneRow> {
        (0..self.fields.len()).map(PaneRow::Field).collect()
    }

    /// The row under the cursor, or `None` for an empty form.
    #[must_use]
    pub fn cursor(&self) -> Option<PaneRow> {
        let rows = self.rows();
        rows.get(self.view.cursor()).copied()
    }

    pub(super) fn move_by(&mut self, delta: isize) {
        let len = self.rows().len();
        self.view.move_by(delta, len);
    }

    pub(super) fn move_to_first(&mut self) {
        let len = self.rows().len();
        self.view.move_to(0, len);
    }

    pub(super) fn move_to_last(&mut self) {
        let len = self.rows().len();
        self.view.move_to(len.saturating_sub(1), len);
    }

    /// Adopts a previous pane's in-flight edit, so a refresh does not
    /// silently drop a question the operator has not answered or a write
    /// they are still waiting on.
    ///
    /// [`PanePending::Typing`] is deliberately not carried: its buffer was
    /// seeded from a value this refresh may have just changed, so keeping
    /// it would put the operator halfway through editing something that is
    /// no longer there. `App::release_text_mode_if_unowned` is what puts
    /// the keyboard back when that happens.
    pub(super) fn adopt_pending_edit(&mut self, previous: Option<PanePending>) {
        self.pending_edit = match previous {
            Some(carried @ (PanePending::Armed { .. } | PanePending::Sent { .. })) => Some(carried),
            Some(PanePending::Typing { .. }) | None => None,
        };
    }

    /// Adopts a previous pane's cursor and offset, clamped to this one's
    /// own row count. What a refresh of an already-open pane rides on, so
    /// `r` does not throw the operator back to the first field.
    pub(super) fn adopt_view(&mut self, view: Viewport) {
        self.view = view;
        let len = self.rows().len();
        self.view.clamp(len);
    }

    /// Re-opens the env sub-screen on the refreshed key list, at the cursor
    /// and offset it had. Setting a key re-reads the whole config, and
    /// without this the sub-screen would slam shut on the operator's own
    /// keystroke, on the one screen where the keystroke adds a row.
    pub(super) fn adopt_env_view(&mut self, view: Viewport, cursor_key: Option<&str>) {
        let mut env = EnvPane::new(self.env_keys.clone());
        env.adopt_view(view, cursor_key);
        self.env = Some(env);
    }

    /// Re-opens the list sub-screen on the refreshed array, at the cursor
    /// and offset it had. Setting an element re-reads the whole config,
    /// and without this the sub-screen would slam shut on the operator's
    /// own keystroke.
    pub(super) fn adopt_list_view(&mut self, key: &str, view: Viewport) {
        let Some(item) = self.fields.by_key(key).and_then(|field| match field.kind {
            FieldKind::List(item) => Some(item),
            _ => None,
        }) else {
            return;
        };
        let mut list = ListPane::new(key.to_owned(), item, self.elements_of(key));
        list.adopt_view(view);
        self.list = Some(list);
    }

    #[cfg(test)]
    pub(crate) fn move_to_key(&mut self, key: &str) {
        if let Some(index) = self
            .fields
            .fields()
            .iter()
            .position(|field| field.key == key)
        {
            let len = self.rows().len();
            self.view.move_to(index, len);
        }
    }
}

/// Which of the daemon's two reloads an app takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReloadKind {
    /// The replacement is spawned alongside the instance it replaces.
    Overlap,
    /// The instance being replaced is drained first, so the app is down for
    /// the length of the drain.
    Serial,
}

impl ReloadKind {
    /// The word the pane's own menu prints for it.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Overlap => "overlapping",
            Self::Serial => "serial",
        }
    }
}

/// Whether a reload of this app overlaps or runs serially.
///
/// The daemon decides through `ReadinessSource::of`, which answers for
/// `wait_ready` before it reads `readiness_probe`, so an app with both
/// overlaps.
const fn reload_mode(wait_ready: bool, has_probe: bool, reuse_port: bool) -> ReloadKind {
    if !wait_ready && has_probe && !reuse_port {
        ReloadKind::Serial
    } else {
        ReloadKind::Overlap
    }
}

#[cfg(test)]
mod tests {
    use shep_core::config::{AppConfig, ProbeConfig, ProbeKind};

    use super::*;

    fn web() -> SheepConfigView {
        let mut config = AppConfig {
            name: "web".into(),
            max_restarts: 32,
            ..AppConfig::default()
        };
        config
            .env
            .insert("DB_HOST".into(), "{{shared:DB_HOST}}".into());
        SheepConfigView::new(config, vec!["max_restarts".into()], vec!["env".into()])
    }

    fn web_with_args(args: &[&str]) -> SheepConfigView {
        let config = AppConfig {
            name: "web".into(),
            args: args.iter().map(|arg| (*arg).to_string()).collect(),
            stop_exit_codes: vec![0, 143],
            ..AppConfig::default()
        };
        SheepConfigView::new(config, Vec::new(), Vec::new())
    }

    #[test]
    fn a_sheep_pane_has_forty_one_fields_in_eight_groups() {
        let pane = ConfigPane::sheep(web());
        assert_eq!(pane.fields().len(), 41);
        assert!(!pane.fields().is_empty());
        let mut groups: Vec<&str> = Vec::new();
        for field in pane.fields().fields() {
            let group = field.group.as_deref().expect("every field carries a group");
            if groups.last() != Some(&group) {
                groups.push(group);
            }
        }
        assert_eq!(
            groups,
            [
                "process",
                "logging",
                "inputs",
                "restart",
                "readiness",
                "shutdown",
                "watch",
                "cron"
            ]
        );
    }

    #[test]
    fn a_value_renders_bare_for_a_scalar_and_as_a_count_for_env() {
        let pane = ConfigPane::sheep(web());
        assert_eq!(pane.value("max_restarts"), "32");
        assert_eq!(pane.value("autorestart"), "true");
        assert_eq!(pane.value("cwd"), "(unset)");
        assert_eq!(pane.value("env"), "1 key");
    }

    #[test]
    fn cost_comes_from_apply_group_for_a_sheep() {
        let pane = ConfigPane::sheep(web());
        assert_eq!(pane.cost("max_restarts"), Some(ApplyGroup::Live));
        assert_eq!(pane.cost("kill_signal"), Some(ApplyGroup::NextSpawn));
        assert_eq!(pane.cost("script"), Some(ApplyGroup::NeedsRespawn));
        assert_eq!(pane.cost("instances"), Some(ApplyGroup::Structural));
    }

    #[test]
    fn structural_fields_are_not_editable_and_the_rest_are() {
        let pane = ConfigPane::sheep(web());
        for key in ["name", "instances"] {
            assert!(!pane.fields().by_key(key).unwrap().editable, "{key}");
        }
        assert!(pane.fields().by_key("max_restarts").unwrap().editable);
    }

    #[test]
    fn the_menu_counts_the_parked_fields_once() {
        let mut config = AppConfig {
            name: "web".into(),
            ..AppConfig::default()
        };
        config.env.insert("DB_HOST".into(), "db.internal".into());
        let view =
            SheepConfigView::new(config, Vec::new(), vec!["env".into(), "kill_signal".into()]);
        assert_eq!(ConfigPane::sheep(view).parked_count(), 2);
        assert_eq!(ConfigPane::sheep(web_with_args(&[])).parked_count(), 0);
    }

    #[test]
    fn a_probe_without_reuse_port_is_the_only_serial_reload() {
        assert_eq!(reload_mode(false, true, false), ReloadKind::Serial);
        assert_eq!(reload_mode(true, true, false), ReloadKind::Overlap);
        assert_eq!(reload_mode(false, true, true), ReloadKind::Overlap);
        assert_eq!(reload_mode(false, false, false), ReloadKind::Overlap);
    }

    #[test]
    fn a_pane_reads_its_reload_kind_off_the_three_fields_it_turns_on() {
        let probed = |wait_ready, reuse_port| {
            let config = AppConfig {
                name: "web".into(),
                wait_ready,
                reuse_port,
                readiness_probe: Some(ProbeConfig {
                    kind: ProbeKind::Tcp,
                    target: "127.0.0.1:8080".into(),
                    interval: UpDuration::from_millis(10_000),
                    timeout: UpDuration::from_millis(5_000),
                    failure_threshold: 3,
                }),
                ..AppConfig::default()
            };
            ConfigPane::sheep(SheepConfigView::new(config, Vec::new(), Vec::new())).reload_kind()
        };
        assert_eq!(probed(false, false), ReloadKind::Serial);
        assert_eq!(probed(true, false), ReloadKind::Overlap);
        assert_eq!(probed(false, true), ReloadKind::Overlap);
        assert_eq!(
            ConfigPane::sheep(web()).reload_kind(),
            ReloadKind::Overlap,
            "no probe, so nothing an outgoing instance could answer"
        );
    }

    #[test]
    fn overridden_and_pending_are_read_off_the_view() {
        let pane = ConfigPane::sheep(web());
        assert!(pane.is_overridden("max_restarts"));
        assert!(!pane.is_overridden("autorestart"));
        assert!(pane.is_pending("env"));
        assert!(!pane.is_pending("max_restarts"));
    }

    #[test]
    fn the_cursor_walks_the_rows_and_clamps_at_both_ends() {
        let mut pane = ConfigPane::sheep(web());
        assert_eq!(pane.cursor(), Some(PaneRow::Field(0)));
        pane.move_by(1);
        assert_eq!(pane.cursor(), Some(PaneRow::Field(1)));
        pane.move_by(-5);
        assert_eq!(pane.cursor(), Some(PaneRow::Field(0)));
        pane.move_to_last();
        assert_eq!(pane.cursor(), Some(PaneRow::Field(40)));
        assert_eq!(
            pane.fields().fields()[40].key,
            "cron_timezone",
            "the last row is the last field"
        );
        pane.move_to_first();
        assert_eq!(pane.cursor(), Some(PaneRow::Field(0)));
    }

    #[test]
    fn a_refreshed_pane_keeps_the_cursor_it_had() {
        let mut pane = ConfigPane::sheep(web());
        pane.set_rows(10);
        pane.move_to_last();
        let carried = pane.view().clone();
        let mut fresh = ConfigPane::sheep(web());
        fresh.adopt_view(carried);
        assert_eq!(fresh.cursor(), Some(PaneRow::Field(40)));
    }

    #[test]
    fn cycling_a_bool_arms_a_set_with_the_flipped_value() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("autorestart");
        pane.cycle(Instant::now());
        let Some(PanePending::Armed {
            edit: PaneEdit::Set { key, value },
            text,
            ..
        }) = pane.pending_edit()
        else {
            panic!("{:?}", pane.pending_edit());
        };
        assert_eq!(key, "autorestart");
        assert_eq!(value.as_value(), &serde_json::json!(false));
        assert!(text.contains("autorestart"), "{text}");
    }

    #[test]
    fn space_cycles_a_suggested_field_and_e_still_opens_the_editor() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("kill_signal");
        pane.cycle(Instant::now());
        assert!(pane.pending_edit().is_some(), "space arms a suggestion");
        pane.cancel();
        pane.begin_typing();
        assert!(
            matches!(pane.pending_edit(), Some(PanePending::Typing { .. })),
            "e still opens a free-text editor"
        );
    }

    /// `apply_group` is a fact about the field; a write's fate is a fact
    /// about the flock, which only the shepherd knows. `watch` is `Live`
    /// but parks whenever its config subset cannot normalize alone, so a
    /// blanket promise can be wrong. The sentence names the class instead.
    #[test]
    fn a_live_confirm_names_the_class_and_promises_no_outcome() {
        for key in ["autorestart", "watch"] {
            let mut pane = ConfigPane::sheep(web());
            pane.move_to_key(key);
            pane.cycle(Instant::now());
            let Some(PanePending::Armed { text, .. }) = pane.pending_edit() else {
                panic!("{:?}", pane.pending_edit());
            };
            assert_eq!(
                pane.cost(key),
                Some(ApplyGroup::Live),
                "the fixture must keep {key} Live or the test means nothing"
            );
            assert!(text.contains("is a live setting"), "{text}");
            assert!(!text.contains("takes it now"), "{text}");
            assert!(!text.contains("respawn"), "{text}");
            assert!(!text.contains("next start"), "{text}");
        }
    }

    /// `autostart` is in force the moment it lands, because the daemon
    /// reads it at muster.
    #[test]
    fn a_next_spawn_confirm_names_when_the_field_is_read() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("autostart");
        pane.cycle(Instant::now());
        let Some(PanePending::Armed { text, .. }) = pane.pending_edit() else {
            panic!("{:?}", pane.pending_edit());
        };
        assert_eq!(pane.cost("autostart"), Some(ApplyGroup::NextSpawn));
        assert!(text.contains("is read when web spawns"), "{text}");
        assert!(!text.contains("respawn"), "{text}");
    }

    /// The daemon parks such a field and waits, the same fact the status
    /// line states one keystroke later.
    #[test]
    fn a_respawn_field_arms_a_confirm_that_names_the_reload_it_waits_for() {
        for key in ["merge_logs", "shutdown_with_message"] {
            let mut pane = ConfigPane::sheep(web());
            pane.move_to_key(key);
            pane.cycle(Instant::now());
            let Some(PanePending::Armed { text, .. }) = pane.pending_edit() else {
                panic!("{:?}", pane.pending_edit());
            };
            assert_eq!(
                pane.cost(key),
                Some(ApplyGroup::NeedsRespawn),
                "the fixture must keep {key} NeedsRespawn or the test means nothing"
            );
            assert!(text.contains("waits for `shep reload web`"), "{text}");
            assert!(!text.contains("is respawned"), "{text}");
        }
    }

    /// Env is `NeedsRespawn` in every case, against the same status line
    /// the field arm answers to.
    #[test]
    fn an_env_confirm_names_the_reload_it_waits_for_and_never_the_value() {
        for value in [Some("hunter2".to_owned().into()), None] {
            let pane = ConfigPane::sheep(web());
            let text = pane.confirm_text(&PaneEdit::SetEnv {
                key: "DB_PASSWORD".into(),
                value,
            });
            assert!(text.contains("waits for `shep reload web`"), "{text}");
            assert!(!text.contains("respawn"), "{text}");
            assert!(!text.contains("hunter2"), "{text}");
        }
    }

    #[test]
    fn a_read_only_field_does_not_arm() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("instances");
        pane.cycle(Instant::now());
        assert!(pane.pending_edit().is_none());
        pane.begin_typing();
        assert!(pane.pending_edit().is_none());
    }

    /// A string here would be refused by `AppConfig`'s own deserializer.
    #[test]
    fn typing_into_an_integer_and_applying_arms_a_number_not_a_string() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("max_restarts");
        pane.begin_typing();
        let Some(PanePending::Typing { buffer, .. }) = pane.pending_edit() else {
            panic!("{:?}", pane.pending_edit());
        };
        assert_eq!(buffer, "32", "the editor opens on what is on screen");
        pane.type_backspace();
        pane.type_backspace();
        for c in "40".chars() {
            pane.type_char(c);
        }
        pane.apply_typing(Instant::now());
        let Some(PanePending::Armed {
            edit: PaneEdit::Set { value, .. },
            ..
        }) = pane.pending_edit()
        else {
            panic!("{:?}", pane.pending_edit());
        };
        assert_eq!(value.as_value(), &serde_json::json!(40));
    }

    /// The request names one key and one JSON value; the daemon
    /// deserializes that value into the field it names, so an integer
    /// field handed `"40"` is refused rather than set.
    #[test]
    fn an_edit_carries_the_key_and_the_typed_value_and_nothing_else() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("max_restarts");
        pane.begin_typing();
        pane.type_backspace();
        pane.type_backspace();
        for c in "40".chars() {
            pane.type_char(c);
        }
        pane.apply_typing(Instant::now());
        let Some(PaneEdit::Set { key, value }) = pane.take_armed(7) else {
            panic!("{:?}", pane.pending_edit());
        };
        assert_eq!(key, "max_restarts");
        assert_eq!(value.as_value(), &serde_json::json!(40));
        assert!(
            !matches!(value.as_value(), serde_json::Value::String(_)),
            "an integer field must not travel as a string"
        );
    }

    /// `kill_timeout` defaults to 1600ms, which `UpDuration::Display`
    /// prints as the bare digits `"1600"`; `listen_timeout` defaults to
    /// 3s, which it already prints with a unit. `value` stays the raw,
    /// parseable form an editor would seed from.
    #[test]
    fn a_bare_up_duration_shows_its_resolved_unit_and_a_suffixed_one_is_unchanged() {
        let pane = ConfigPane::sheep(web());
        assert_eq!(pane.display_value("kill_timeout"), "1600ms");
        assert_eq!(pane.value("kill_timeout"), "1600");
        assert_eq!(pane.display_value("listen_timeout"), "3s");
    }

    /// A dog's values come from the section its operator wrote, so a
    /// spelling that `UpDuration::Display` would canonicalize to `1m`
    /// stays as `60s`. A sheep's arrive already canonicalized, `UpDuration`
    /// serializing through its own `Display`, so this is the pane that can
    /// tell the difference.
    #[test]
    fn a_dogs_own_spelling_of_a_duration_survives_the_pane() {
        let schema = serde_json::json!({
            "properties": {
                "poll": { "type": "string", "$ref": "#/$defs/UpDuration" }
            },
            "$defs": { "UpDuration": { "type": "string" } }
        });
        let pane = ConfigPane::dog("bark".into(), None, schema, "poll = \"60s\"\n".into());
        assert_eq!(pane.display_value("poll"), "60s");
    }

    /// 64 bytes is not a whole `K`/`M`/`G`, so `MemSize::Display` prints
    /// the bare digits `"64"`; 512 mebibytes already prints with a unit.
    #[test]
    fn a_bare_mem_size_shows_its_resolved_unit_and_a_suffixed_one_is_unchanged() {
        for (bytes, want) in [(64, "64 B"), (512 << 20, "512M")] {
            let config = AppConfig {
                name: "web".into(),
                max_memory: Some(MemSize::from_bytes(bytes)),
                ..AppConfig::default()
            };
            let pane = ConfigPane::sheep(SheepConfigView::new(config, Vec::new(), Vec::new()));
            assert_eq!(pane.display_value("max_memory"), want, "{bytes} bytes");
        }
    }

    /// A field with no `MemSize`/`UpDuration` grammar is untouched by
    /// `display_value`, the same as `value`.
    #[test]
    fn a_field_with_no_unit_grammar_displays_the_same_either_way() {
        let pane = ConfigPane::sheep(web());
        assert_eq!(pane.display_value("cwd"), pane.value("cwd"));
        assert_eq!(
            pane.display_value("max_restarts"),
            pane.value("max_restarts")
        );
    }

    /// The confirm sentence quotes what a write would actually mean, not
    /// the digits the operator typed: this is the moment the maintainer's
    /// own report says nothing warned them.
    #[test]
    fn arming_a_bare_number_on_a_mem_size_field_confirms_the_resolved_value() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("max_memory");
        pane.begin_typing();
        for c in "64".chars() {
            pane.type_char(c);
        }
        pane.apply_typing(Instant::now());
        let Some(PanePending::Armed { text, .. }) = pane.pending_edit() else {
            panic!("{:?}", pane.pending_edit());
        };
        assert!(text.contains("set max_memory = 64 B?"), "{text}");
    }

    /// A buffer that does not parse renders as typed rather than guessed
    /// at or hidden: shep is the one that gets to refuse it.
    #[test]
    fn an_unparseable_buffer_on_a_unit_field_confirms_as_typed() {
        let mut pane = ConfigPane::sheep(web());
        pane.move_to_key("max_memory");
        pane.begin_typing();
        for c in "banana".chars() {
            pane.type_char(c);
        }
        pane.apply_typing(Instant::now());
        let Some(PanePending::Armed { text, .. }) = pane.pending_edit() else {
            panic!("{:?}", pane.pending_edit());
        };
        assert!(text.contains("set max_memory = banana?"), "{text}");
    }

    #[test]
    fn toggling_help_flips_it_and_closing_it_is_idempotent() {
        let mut pane = ConfigPane::sheep(web());
        assert!(!pane.help_open());
        pane.toggle_help();
        assert!(pane.help_open());
        pane.toggle_help();
        assert!(!pane.help_open());
        pane.toggle_help();
        pane.close_help();
        assert!(!pane.help_open());
        pane.close_help();
        assert!(
            !pane.help_open(),
            "closing an already-closed help is a no-op"
        );
    }

    #[test]
    fn the_env_pane_lists_keys_and_a_new_row_and_an_empty_apply_means_unset() {
        let mut env = EnvPane::new(vec!["A".into(), "B".into()]);
        assert_eq!(env.rows().len(), 3, "two keys and a + new row");
        env.move_to_last();
        env.begin_typing();
        for c in "C=3".chars() {
            env.type_char(c);
        }
        assert_eq!(
            env.apply_typing(),
            Some(("C".to_owned(), Some("3".to_owned())))
        );
        env.move_to_first();
        env.begin_typing();
        assert_eq!(env.apply_typing(), Some(("A".to_owned(), None)));
    }

    /// The bark section every dog test below reads: a comment, a scalar,
    /// and a sink carrying a credential.
    fn bark_section() -> String {
        "# how often\npoll = \"60s\"\nhistory_bytes = 4096\n\n[sinks.ops]\nkind = \"slack\"\nurl = \"https://hooks.example/x\"\n".to_owned()
    }

    fn bark_pane() -> ConfigPane {
        let schema = crate::dog::builtin_schema("bark").expect("bark is a built-in");
        ConfigPane::dog("bark".into(), None, schema, bark_section())
    }

    /// A dog's schema carries no group, so the pane draws no headers, and
    /// shep does not classify a dog's field cost: `cost` answers `None`
    /// for one.
    #[test]
    fn a_dog_pane_is_flat_in_schema_order_and_marks_the_secret() {
        let pane = bark_pane();
        assert!(
            pane.fields()
                .fields()
                .iter()
                .all(|field| field.group.is_none()),
            "a dog's schema carries no group, so the pane draws no headers"
        );
        let keys: Vec<&str> = pane
            .fields()
            .fields()
            .iter()
            .map(|f| f.key.as_str())
            .collect();
        assert_eq!(
            keys,
            ["history_bytes", "poll", "rules", "sink_timeout", "sinks"],
            "schema order, which for a serde_json map is alphabetical"
        );
        assert!(
            pane.fields()
                .by_key("sinks")
                .expect("sinks is a field")
                .secret
        );
        assert_eq!(pane.value("poll"), "60s");
        assert_eq!(pane.cost("poll"), None);
    }

    /// Shep writes a `sinks` table happily; this screen simply has no
    /// widget for a table of tables.
    #[test]
    fn a_dogs_map_field_is_locked_for_want_of_a_widget_and_not_refused() {
        let pane = bark_pane();
        assert_eq!(pane.lock("sinks"), Some(Lock::NoWidget));
        assert_eq!(pane.lock("rules"), Some(Lock::NoWidget));
        assert_eq!(pane.lock("poll"), None);
    }

    /// A dog whose schema declares one secret string. No built-in has one:
    /// bark's only secret is a map, and a map has no editor to type a
    /// secret into, so the leak the confirm sentence could carry was not
    /// reachable from any fixture the pane already had.
    fn secret_dog_pane() -> ConfigPane {
        let schema = serde_json::json!({
            "properties": {
                "webhook": { "type": "string", "x-shep-secret": true },
            }
        });
        ConfigPane::dog(
            "pydog".into(),
            None,
            schema,
            "webhook = \"https://hook/OLD\"\n".to_owned(),
        )
    }

    /// `ConfigPane::dog` always leaves `env_keys` empty, so an `env` field
    /// on a dog reads its own section, not the sheep key count. No
    /// built-in declares such a field; the dog pane exists for schemas
    /// shep did not write.
    #[test]
    fn a_dogs_own_env_field_reads_its_section_and_not_the_sheep_key_count() {
        let schema = serde_json::json!({
            "properties": {
                "env": { "type": "string" },
            }
        });
        let mut pane = ConfigPane::dog(
            "pydog".into(),
            None,
            schema,
            "env = \"staging\"\n".to_owned(),
        );
        assert_eq!(pane.value("env"), "staging");
        pane.move_to_key("env");
        pane.begin_typing();
        let Some(PanePending::Typing { buffer, .. }) = pane.pending_edit() else {
            panic!("{:?}", pane.pending_edit());
        };
        assert_eq!(buffer, "staging");
    }

    /// The pane renders `<set>` for a secret and seeds its editor empty.
    /// The sentence outlives both: it sits in `PanePending`, prints on
    /// the status bar, and survives `take_armed` for the whole round
    /// trip.
    #[test]
    fn a_secret_fields_confirm_never_quotes_what_was_typed() {
        let mut pane = secret_dog_pane();
        pane.move_to_key("webhook");
        pane.begin_typing();
        for typed in "https://hook/T0PS3CRET".chars() {
            pane.type_char(typed);
        }
        pane.apply_typing(Instant::now());
        let Some(PanePending::Armed { text, .. }) = pane.pending_edit() else {
            panic!("{:?}", pane.pending_edit());
        };
        assert!(!text.contains("T0PS3CRET"), "{text}");
        assert!(text.contains("set webhook = <set>?"), "{text}");
    }

    /// Re-rendering from parsed values would delete every comment in a
    /// file shep does not author.
    #[test]
    fn an_edited_section_keeps_its_comments_and_changes_one_key() {
        let pane = bark_pane();
        let out = pane
            .edited_section(&PaneEdit::Set {
                key: "poll".into(),
                value: serde_json::json!("30s").into(),
            })
            .expect("the fixture section parses");
        assert!(out.contains("# how often"), "{out}");
        assert!(out.contains("poll = \"30s\""), "{out}");
        assert!(out.contains("history_bytes = 4096"), "{out}");
        assert!(out.contains("url = \"https://hooks.example/x\""), "{out}");
    }

    /// An empty buffer unsets the key, putting it back on the dog's own
    /// default.
    #[test]
    fn a_null_edit_removes_the_key_from_the_section() {
        let pane = bark_pane();
        let out = pane
            .edited_section(&PaneEdit::Set {
                key: "history_bytes".into(),
                value: serde_json::Value::Null.into(),
            })
            .expect("the fixture section parses");
        assert!(!out.contains("history_bytes"), "{out}");
        assert!(out.contains("# how often"), "{out}");
    }

    /// A section here would send a sheep's config out through a dog's
    /// door.
    #[test]
    fn a_sheep_pane_has_no_section_to_edit() {
        let pane = ConfigPane::sheep(web());
        assert_eq!(
            pane.edited_section(&PaneEdit::Set {
                key: "cwd".into(),
                value: serde_json::json!("/srv").into(),
            }),
            None
        );
    }

    /// `cwd` and `script` routinely hold a home directory and `args`
    /// holds a token, which is why `ConfigPane`'s own `Debug` withholds
    /// the map these come out of. Asserted on `FieldValue` itself, not
    /// on a type that carries it, since a wrapper could redact while the
    /// value underneath still prints.
    #[test]
    fn a_field_values_debug_names_no_value() {
        for (value, want) in [
            (serde_json::json!("/home/ada/secret-project"), "<string>"),
            (serde_json::json!(40), "<number>"),
            (serde_json::json!(false), "<bool>"),
            (serde_json::json!(null), "<null>"),
            (serde_json::json!(["--token", "hunter2"]), "<array>"),
            (serde_json::json!({ "a": 1 }), "<object>"),
        ] {
            let wrapped: FieldValue = value.into();
            assert_eq!(format!("{wrapped:?}"), format!("FieldValue({want})"));
        }
    }

    /// `Debug` is derived, safe only because both value types redact
    /// themselves; this test pins that fact.
    #[test]
    fn a_pane_edits_debug_names_no_value() {
        let set = PaneEdit::Set {
            key: "cwd".into(),
            value: serde_json::json!("/home/ada/secret-project").into(),
        };
        assert_eq!(
            format!("{set:?}"),
            r#"Set { key: "cwd", value: FieldValue(<string>) }"#
        );
        let env = PaneEdit::SetEnv {
            key: "DB_PASSWORD".into(),
            value: Some("hunter2".to_owned().into()),
        };
        assert_eq!(
            format!("{env:?}"),
            r#"SetEnv { key: "DB_PASSWORD", value: Some(EnvValue(<7 bytes>)) }"#
        );
    }

    /// The buffer is what the operator is halfway through typing, and on
    /// the env screen that is the secret itself; the question quotes the
    /// value a field edit is setting (IR-41).
    #[test]
    fn debug_names_no_value_on_a_pane_pending() {
        let typing = PanePending::Typing {
            key: "cwd".into(),
            buffer: "/home/ada/secret-project".into(),
        };
        assert_eq!(
            format!("{typing:?}"),
            r#"PanePending::Typing { key: "cwd", buffer: <24 chars> }"#
        );
        let armed = PanePending::Armed {
            edit: PaneEdit::Set {
                key: "cwd".into(),
                value: serde_json::json!("/home/ada/secret-project").into(),
            },
            text: "set cwd = /home/ada/secret-project? web takes it now".into(),
            at: Instant::now(),
        };
        assert_eq!(
            format!("{armed:?}"),
            r#"PanePending::Armed { edit: Set { key: "cwd", value: FieldValue(<string>) } }"#
        );
        let sent = PanePending::Sent {
            ticket: 7,
            key: "cwd".into(),
            text: "set cwd = /home/ada/secret-project? web takes it now".into(),
        };
        assert_eq!(
            format!("{sent:?}"),
            r#"PanePending::Sent { ticket: 7, key: "cwd" }"#
        );
    }

    /// The buffer on the `+ new` row is the whole `KEY=value`, secret
    /// included (IR-41).
    #[test]
    fn an_env_panes_debug_names_no_key_and_no_value() {
        let mut env = EnvPane::new(vec!["DB_PASSWORD".into(), "API_TOKEN".into()]);
        env.move_to_last();
        env.begin_typing();
        for typed in "STRIPE_KEY=sk_live_1".chars() {
            env.type_char(typed);
        }
        assert_eq!(
            format!("{env:?}"),
            "EnvPane { keys: 2, cursor: 2, typing: true }"
        );
    }

    /// A dog's section is the single most credential-dense thing this
    /// screen loads: bark's own `sinks` table is a webhook URL with a
    /// bearer token in it. The redaction is on the pane, not on each
    /// type that carries the text.
    #[test]
    fn a_dog_panes_debug_names_no_section() {
        let pane = bark_pane();
        assert_eq!(
            format!("{pane:?}"),
            r#"ConfigPane { target: Dog { name: "bark", adopted_path: None }, fields: 5, env_keys: 0, cursor: 0 }"#
        );
    }

    /// `args` and `cwd` live in `values` and routinely carry a token or a
    /// home directory (IR-41).
    #[test]
    fn the_panes_debug_names_no_value_it_holds() {
        let mut config = AppConfig {
            name: "web".into(),
            cwd: Some("/home/ada/secret-project".into()),
            args: vec!["--token".into(), "hunter2".into()],
            ..AppConfig::default()
        };
        config.env.insert("DB_PASSWORD".into(), "hunter2".into());
        let pane = ConfigPane::sheep(SheepConfigView::new(config, Vec::new(), Vec::new()));
        assert_eq!(
            format!("{pane:?}"),
            r#"ConfigPane { target: Sheep { name: "web" }, fields: 41, env_keys: 1, cursor: 0 }"#
        );
    }

    /// The array is one value, so an element is not a thing the wire can
    /// name.
    #[test]
    fn editing_one_element_sends_the_whole_array() {
        let mut pane = ConfigPane::sheep(web_with_args(&["--port", "8080"]));
        pane.move_to_key("args");
        pane.open_list();
        pane.list_mut().expect("open").move_to(1);
        pane.arm_list_element("9090".into(), Instant::now());
        let Some(PaneEdit::Set { key, value }) = pane.take_armed(1) else {
            panic!("expected a set");
        };
        assert_eq!(key, "args");
        assert_eq!(value.as_value(), &serde_json::json!(["--port", "9090"]));
    }

    /// Derived, unlike every other type in this file that touches a value.
    /// The screen renders its elements, so a `{:?}` that hid them would
    /// withhold what the operator is already reading. `ConfigPane`'s own
    /// `Debug` still names no element (`the_panes_debug_names_no_value_it_holds`).
    #[test]
    fn a_list_panes_debug_names_no_element() {
        let list = ListPane::new(
            "args".into(),
            ListItem::Text,
            vec!["--token".into(), "hunter2".into()],
        );
        assert_eq!(
            format!("{list:?}"),
            r#"ListPane { key: "args", item: Text, elements: 2, typing: none }"#
        );
    }

    /// The operator is mid-word, not wrong, so the editor stays open and
    /// nothing arms. The same rule `ConfigPane::apply_typing` follows for
    /// an integer field.
    #[test]
    fn an_integer_element_that_does_not_parse_keeps_the_editor_open() {
        let mut pane = ConfigPane::sheep(web_with_args(&[]));
        pane.move_to_key("stop_exit_codes");
        pane.open_list();
        let list = pane.list_mut().expect("open");
        list.move_to_last();
        list.begin_typing();
        list.type_char('-');
        assert_eq!(list.apply_typing(), None);
        assert!(list.typing().is_some(), "the editor is still open");
        list.type_char('1');
        assert_eq!(list.apply_typing().as_deref(), Some("-1"));
    }

    /// The whole array goes out, so a removal and a reorder are the same
    /// kind of write an element edit is.
    #[test]
    fn removing_and_reordering_arm_the_whole_array_too() {
        let mut pane = ConfigPane::sheep(web_with_args(&["a", "b", "c"]));
        pane.move_to_key("args");
        pane.open_list();
        pane.list_mut().expect("open").move_to(1);
        pane.arm_list_removal(Instant::now());
        let Some(PaneEdit::Set { value, .. }) = pane.take_armed(1) else {
            panic!("expected a set");
        };
        assert_eq!(value.as_value(), &serde_json::json!(["a", "c"]));

        pane.arm_list_reorder(-1, Instant::now());
        let Some(PaneEdit::Set { value, .. }) = pane.take_armed(2) else {
            panic!("expected a set");
        };
        assert_eq!(value.as_value(), &serde_json::json!(["b", "a", "c"]));
    }

    /// `J`'s direction. Only `-1` is exercised above, and the two share
    /// one arm in `arm_list_reorder`.
    #[test]
    fn moving_an_element_down_arms_the_whole_array() {
        let mut pane = ConfigPane::sheep(web_with_args(&["a", "b", "c"]));
        pane.move_to_key("args");
        pane.open_list();
        pane.list_mut().expect("open").move_to(0);
        pane.arm_list_reorder(1, Instant::now());
        let Some(PaneEdit::Set { value, .. }) = pane.take_armed(1) else {
            panic!("expected a set");
        };
        assert_eq!(value.as_value(), &serde_json::json!(["b", "a", "c"]));
    }

    /// The `+ new` row holds no element, and neither end has anywhere to
    /// move to, so neither keystroke arms anything at all.
    #[test]
    fn a_removal_or_a_move_with_nothing_to_act_on_arms_nothing() {
        let mut pane = ConfigPane::sheep(web_with_args(&["a", "b"]));
        pane.move_to_key("args");
        pane.open_list();
        pane.list_mut().expect("open").move_to_last();
        pane.arm_list_removal(Instant::now());
        assert!(!pane.is_armed(), "the `+ new` row holds no element");
        pane.list_mut().expect("open").move_to_first();
        pane.arm_list_reorder(-1, Instant::now());
        assert!(!pane.is_armed(), "the first element cannot move up");
    }

    /// An integer array's elements render as digits and travel back as
    /// numbers, which is what tells `stop_exit_codes` apart from `args`.
    #[test]
    fn an_integer_array_travels_as_numbers() {
        let mut pane = ConfigPane::sheep(web_with_args(&[]));
        pane.move_to_key("stop_exit_codes");
        pane.open_list();
        assert_eq!(pane.list().expect("open").elements(), ["0", "143"]);
        pane.list_mut().expect("open").move_to(0);
        pane.arm_list_element("2".into(), Instant::now());
        let Some(PaneEdit::Set { key, value }) = pane.take_armed(1) else {
            panic!("expected a set");
        };
        assert_eq!(key, "stop_exit_codes");
        assert_eq!(value.as_value(), &serde_json::json!([2, 143]));
    }

    /// A dog's write replaces its whole section, and `edited_section` has
    /// no rendering for an array, so the pane offers no editor for one.
    #[test]
    fn a_dogs_array_field_has_no_widget_here() {
        let schema = serde_json::json!({
            "properties": { "sinks": { "type": "array", "items": { "type": "string" } } }
        });
        let pane = ConfigPane::dog("bark".into(), None, schema, String::new());
        assert!(!pane.fields().by_key("sinks").expect("declared").editable);
        assert_eq!(pane.lock("sinks"), Some(Lock::NoWidget));
    }
}