shep-core 0.8.0

Types, Flockfile parsing, and the wire protocol shared by the shep process manager's daemon, client, and CLI
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
//! Per-app configuration schema: one sheep's Flockfile entry.

use core::fmt;

use std::collections::BTreeMap;

// use schemars::generate
use serde::{Deserialize, Deserializer, Serialize};

use crate::config::LevelRule;
use crate::values::{MemSize, UpDuration};

/// How a health probe checks a sheep
// wire format: changing these strings is a breaking change
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum ProbeKind {
    /// HTTP GET must return 2xx
    Http,
    /// TCP connect must succeed
    Tcp,
    /// Command must exit 0
    Exec,
}

/// Readiness/liveness probe configuration (spec §7)
// wire format: changing field names/defaults is a breaking change
// `deny_unknown_fields` used to live here. This type rides the wire inside
// `AppConfig` (itself carried by `Request::Start`, `Request::Add`, and
// `Response::SheepConfig`), where an unknown field means a newer peer, not
// a typo — denying it here would make a newer daemon's reply break an
// older client. The denial moved to `Flockfile::parse`, where the input
// really is a hand-written file. Do not restore the serde attribute here.
//
// The schema-only sibling attribute below is not the same thing and stays:
// `schemars(deny_unknown_fields)` only shapes the generated
// `additionalProperties: false`, which an editor uses to flag a Flockfile
// typo before a parse ever runs. It never reaches `#[derive(Deserialize)]`
// (schemars mirrors it into a synthesized attribute its own macro expansion
// reads, not the real one), so the wire still tolerates an unknown field.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(deny_unknown_fields))]
pub struct ProbeConfig {
    /// Probe mechanism
    pub kind: ProbeKind,
    /// URL (http), `host:port` (tcp), or command line (exec)
    pub target: String,
    /// Time between probes (default 10s)
    #[serde(default = "default_probe_interval")]
    pub interval: UpDuration,
    /// Per-probe timeout (default 5s)
    #[serde(default = "default_probe_timeout")]
    pub timeout: UpDuration,
    /// Consecutive failures before the probe reports unhealthy (default 3)
    #[serde(default = "default_failure_threshold")]
    pub failure_threshold: u32,
}

fn default_probe_interval() -> UpDuration {
    UpDuration::from_millis(10_000)
}
fn default_probe_timeout() -> UpDuration {
    UpDuration::from_millis(5_000)
}
fn default_failure_threshold() -> u32 {
    3
}

/// Per-app configuration — one sheep's entry in a Flockfile
///
/// Field names are the Flockfile contract (sheep-native; pm2 spellings are
/// rejected — the importer translates them). Deserializing this type
/// directly tolerates an unknown field, since it also rides the wire; a
/// Flockfile typo instead fails loudly at [`Flockfile::parse`](crate::config::Flockfile::parse),
/// the input that really is hand-written.
///
/// # Example
/// ```
/// use shep_core::config::AppConfig;
///
/// let app: AppConfig = toml::from_str("name = \"web\"\nscript = \"./srv\"").unwrap();
/// assert!(app.autorestart); // spec default
/// ```
// wire format: changing field names/defaults is a breaking change
//
// `deny_unknown_fields` used to sit beside `default` here. This type rides
// the wire inside `Request::Start`, `Request::Add`, and
// `Response::SheepConfig` — the last of which is a newer daemon handing an
// older client a config it does not fully understand, which is exactly the
// case an unknown field means "a newer peer", not a typo. The denial moved
// to `Flockfile::parse`, where the input really is a hand-written file. Do
// not restore the serde attribute here.
//
// The schema-only sibling attribute below is not the same thing and stays:
// `schemars(deny_unknown_fields)` only shapes the generated
// `additionalProperties: false`, which an editor uses to flag a Flockfile
// typo before a parse ever runs. It never reaches `#[derive(Deserialize)]`
// (schemars mirrors it into a synthesized attribute its own macro expansion
// reads, not the real one), so the wire still tolerates an unknown field.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schema", schemars(deny_unknown_fields))]
#[serde(default)]
pub struct AppConfig {
    /// Unique sheep name (required)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "my-first-sheep",
        "group": "process",
        "blurb": "A convenient and unique name for shep to display",
        "accepts": ["letters, digits, and most punctuation"],
        "refuses": ["a path separator or a colon", "a bare . or .."]
    })))]
    pub name: String,
    /// Executable or script path (required)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "./index.js",
        "group": "process",
        "blurb": "The script that shep should use to launch your app",
        "accepts": ["an absolute or relative path, expanded from cwd",
                    "~ expands, $VARS do not",
                    "a script shep cannot resolve yet: warned"],
        "neighbours": [{"field": "cwd",         "note": "resolved against this cwd"},
                       {"field": "interpreter", "note": "picks what runs this script"}]
    })))]
    pub script: String,
    /// Arguments passed to the script
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "inputs",
        "blurb": "Arguments passed to the script, as a list",
        "accepts": ["a list of strings, one argument each",
                    "{{instance}}, {{name}}, {{SHEP_HOME}} and {{secret:key}} expand"],
        "refuses": ["an unclosed {{ token", "a token shep does not define"]
    })))]
    pub args: Vec<String>,
    /// Working directory (default: daemon's cwd at spawn registration)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "/srv/app",
        "group": "process",
        "blurb": "Where the process runs. Without it, the daemon's own directory",
        "accepts": ["an absolute or relative path, expanded from cwd",
                    "~ expands, $VARS do not",
                    "a directory that does not exist yet: warned"],
        "neighbours": [{"field": "script",        "note": "resolved against this cwd"},
                       {"field": "out_file",      "note": "relative paths follow it too"},
                       {"field": "watch_options", "note": "globs are rooted here"}]
    })))]
    pub cwd: Option<String>,
    /// Interpreter override (`"none"` = run script directly)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "none",
        "group": "process",
        "blurb": "What runs the script. Set it to none to exec the file directly",
        "accepts": ["a command name found on PATH", "none, to exec the script directly"]
    })))]
    pub interpreter: Option<String>,
    /// Environment for the sheep (merged over the daemon's filtered env).
    ///
    /// A value may arrive as a string, a bare boolean, or a bare whole
    /// number (`SOME_BOOL = true`, `PORT = 8080`), and leaves as a string
    /// either way, so this field stays `BTreeMap<String, String>` and the
    /// wire always carries strings. A float is refused: `1.10` would reach
    /// the process as `1.1`. YAML resolves an unquoted `yes` to `"true"`
    /// and `0x1F` to `"31"`, so quote a value whose text must survive.
    #[serde(deserialize_with = "deserialize_env")]
    #[cfg_attr(feature = "schema", schemars(
        extend(
            "init" = {
                "example": "{ NODE_ENV = 'production' }",
                "group": "inputs",
                "blurb": "Environment variables for this app, layered over the daemon's own",
                "accepts": ["a table of KEY = value pairs",
                            "a bare true or 8080, which arrives as text",
                            "{{instance}}, {{name}}, {{SHEP_HOME}} and {{secret:key}} expand in a value"],
                "refuses": ["a float, since 1.10 would arrive as 1.1",
                            "SHEP_INSTANCE, SHEP_NAME, or SHEP_ENVIRONMENT, which shep sets itself",
                            "an unclosed {{ token",
                            "a token shep does not define"],
                "neighbours": [{"field": "environment", "note": "which environment {{secret:...}} reads from"}]
            },
            "additionalProperties" = {
                "anyOf": [{ "type": "string" }, { "type": "boolean" }, { "type": "integer" }]
            }
        )
    ))]
    pub env: BTreeMap<String, String>,
    /// Which environment this sheep resolves `{{secret:...}}` in.
    ///
    /// Absent falls back to `[daemon] environment` in `shep.toml`, which
    /// itself defaults to `production`. Never `all`: that is the store's
    /// every-environment slot, and a sheep claiming it would read that slot
    /// twice and never one of its own.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "staging",
        "group": "inputs",
        "blurb": "Which environment this app resolves secrets in",
        "accepts": ["a name from the secrets store"],
        "refuses": ["all, the store's every-environment slot",
                    "a name outside letters, digits, dot, underscore, or dash"],
        "neighbours": [{"field": "env", "note": "sets which environment its {{secret:...}} reads from"}]
    })))]
    pub environment: Option<String>,
    /// Instance count ("cluster" = N fork instances; spec §4)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "process",
        "blurb": "How many copies of this app to run"
    })))]
    pub instances: u32,
    /// Restart on unexpected exit
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "restart",
        "blurb": "Restarts the process automatically when it exits unexpectedly"
    })))]
    pub autorestart: bool,
    /// Start when the daemon starts / on `shep muster`
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "restart",
        "blurb": "Start this app when the daemon starts, and on shep muster"
    })))]
    pub autostart: bool,
    /// Exit codes treated as clean stop (no restart)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "restart",
        "blurb": "Exit codes that mean a clean stop, so shep will not restart",
        "accepts": ["a list of exit codes"]
    })))]
    pub stop_exit_codes: Vec<i32>,
    /// Uptime below this marks an exit as unstable
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "restart",
        "blurb": "An exit sooner than this counts as unstable"
    })))]
    pub min_uptime: UpDuration,
    /// Consecutive unstable exits before `errored`
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "restart",
        "blurb": "How many unstable exits in a row before shep gives up"
    })))]
    pub max_restarts: u32,
    /// Fixed delay before every restart (alternative to backoff)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "3s",
        "group": "restart",
        "blurb": "A fixed wait before every restart, instead of growing backoff"
    })))]
    pub restart_delay: Option<UpDuration>,
    /// Initial backoff delay; grows ×1.5 capped at 15s (spec §4)
    ///
    /// Defaults to 100ms, not unset. An unstable exit (sooner than
    /// `min_uptime`) with neither this nor `restart_delay` configured would
    /// otherwise restart with no delay at all, so an app that can never
    /// start (a missing dependency, a bad config) would burn its whole
    /// `max_restarts` budget inside a second, logging the same failure
    /// dozens of times.
    ///
    /// All of the above assumes `restart_delay` is unset. A fixed
    /// `restart_delay` takes precedence over this field on every exit,
    /// stable or not, so a stable exit restarts immediately only while
    /// `restart_delay` stays unset, and setting this field to `"0"`
    /// disables the backoff without producing an immediate restart if a
    /// nonzero `restart_delay` is also configured.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "5s",
        "group": "restart",
        "blurb": "Starting delay between restarts, growing each time it fails again"
    })))]
    pub exp_backoff_restart_delay: Option<UpDuration>,
    /// Stop signal, one of `SIGTERM`/`SIGINT`/`SIGQUIT`/`SIGUSR2` (the `SIG`
    /// prefix and the case are both optional). Unset means `SIGTERM`.
    ///
    /// A `String` rather than a [`KillSignal`](crate::config::KillSignal) so
    /// the Flockfile schema and this struct's wire form stay plain text;
    /// `normalize` is what refuses a name outside that set, the same split
    /// `cron_restart` and the watch globs already use.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "SIGTERM",
        "group": "shutdown",
        "blurb": "Which signal shep sends first when stopping this app",
        "suggest": ["SIGTERM", "SIGINT", "SIGQUIT", "SIGUSR2"],
        "accepts": ["SIGTERM, SIGINT, SIGQUIT, or SIGUSR2",
                    "the SIG prefix and case are both optional"],
        "refuses": ["a signal outside that list"]
    })))]
    pub kill_signal: Option<String>,
    /// Grace period between stop signal and SIGKILL
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "shutdown",
        "blurb": "How long shep waits after the stop signal before SIGKILL"
    })))]
    pub kill_timeout: UpDuration,
    /// Send `{"kind":"shutdown"}` on the shepherd channel instead of a signal
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "shutdown",
        "blurb": "Ask the app to stop over the channel instead of signalling it"
    })))]
    pub shutdown_with_message: bool,
    /// Readiness fallback window when no ready signal/probe configured
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "readiness",
        "blurb": "How long to wait for readiness when nothing else reports it"
    })))]
    pub listen_timeout: UpDuration,
    /// Drain window for the old instance during reload
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "shutdown",
        "blurb": "How long the old instance gets to drain during a reload"
    })))]
    pub graceful_timeout: UpDuration,
    /// How long a triggered action gets to answer on the shepherd channel
    /// before its row becomes `ActionOutcome::TimedOut`.
    ///
    /// Defaults to 3s — comfortably under the 5s an RPC caller gets when it
    /// sends no deadline of its own (`shep-client`'s `DEFAULT_DEADLINE`,
    /// mirrored daemon-side as `rpc`'s `DEFAULT_DEADLINE_MS`). The margin
    /// matters more than the number: push this past that budget and a caller
    /// using the plain default gives up with `DeadlineExceeded` before the
    /// daemon's own honest `TimedOut` row ever reaches it. A legitimately
    /// slow action (a cache flush, say) can still ask for longer, but its
    /// caller has to ask for a longer deadline in step —
    /// `Client::request_with_deadline`, the way `shep logs -f` already asks
    /// for `LOG_PLANE_DEADLINE` rather than the client's default. `normalize`
    /// refuses a value no caller could ever satisfy, however long a deadline
    /// it asks for; a value merely above the *default* budget is a caller's
    /// choice to widen its own deadline, not a config error this crate can
    /// see.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "shutdown",
        "blurb": "How long a triggered action has to answer before shep gives up"
    })))]
    pub action_timeout: UpDuration,
    /// Memory ceiling — polling enforcer restarts above this
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "512M",
        "group": "restart",
        "blurb": "Restart the app if it climbs above this much memory"
    })))]
    pub max_memory: Option<MemSize>,
    /// Watch files and restart on change
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "watch",
        "blurb": "Restart when a file changes"
    })))]
    pub watch: bool,
    /// Watch ignore globs (defaults added daemon-side: dot-entries, node_modules)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "watch",
        "blurb": "Paths watch should skip, on top of dotfiles and node_modules",
        "accepts": ["a list of glob patterns"],
        "refuses": ["a pattern globset cannot compile"],
        "neighbours": [{"field": "cwd",           "note": "globs are rooted here"},
                       {"field": "watch_options", "note": "removed from what this matches"}]
    })))]
    pub ignore_watch: Vec<String>,
    /// Watch debounce window (default 500ms, applied daemon-side)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "500",
        "group": "watch",
        "blurb": "How long to wait after a change before restarting"
    })))]
    pub watch_delay: Option<UpDuration>,
    /// Cron pattern for scheduled restarts (croner dialect)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "* * * * *",
        "group": "cron",
        "blurb": "Restart on a schedule, written as a cron pattern",
        "suggest": ["*/5 * * * *", "0 * * * *", "0 0 * * *", "0 0 * * 0"],
        "accepts": ["five fields: minute hour day month weekday",
                    "a nickname like @daily or @hourly"],
        "refuses": ["a field outside its valid range",
                    "a sixth seconds field, or L, W, # or ?",
                    "a pattern croner cannot parse"],
        "neighbours": [{"field": "cron_timezone", "note": "sets which zone this pattern reads in"}]
    })))]
    pub cron_restart: Option<String>,
    /// Fold (group) this sheep belongs to
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "backend",
        "group": "process",
        "blurb": "A fold to group this app with others, for commands that take one"
    })))]
    pub fold: Option<String>,
    /// Sheep or dogs that must be up before this one starts
    ///
    /// Names, never `name:slot`: a dependency on one instance of a
    /// load-balanced app is not a claim about availability. A dependency on
    /// a multi-instance app waits for every instance.
    ///
    /// Read once when a batch is ordered, at a boot, a muster, or a staged
    /// start, so an edit reaches the next such operation rather than the
    /// running child.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "[\"db\", \"cache\"]",
        "group": "process",
        "blurb": "Other sheep or dogs that must be up before this one starts",
        "accepts": ["a list of sheep or dog names"],
        "refuses": ["this sheep's own name", "a name:slot instance reference"]
    })))]
    pub depends_on: Vec<String>,
    /// Run as this user (unix)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "www-data",
        "group": "process",
        "blurb": "Run as this user, on unix",
        "accepts": ["a unix user name"],
        "refuses": ["a name with no passwd entry",
                    "another user, unless the shepherd runs as root"],
        "neighbours": [{"field": "group", "note": "resolved together at spawn"}]
    })))]
    pub user: Option<String>,
    /// Run as this group (unix)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "www-data",
        "group": "process",
        "blurb": "Run as this group, on unix",
        "accepts": ["a unix group name"],
        "refuses": ["a name with no group entry",
                    "another group, unless the shepherd runs as root"],
        "neighbours": [{"field": "user", "note": "resolved together at spawn"}]
    })))]
    pub group: Option<String>,
    /// Stdout log file (default: `{{SHEP_HOME}}/logs/{{name}}-{{instance}}-out.log`; `merge_logs` collapses to `{{name}}-out.log`)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "{{SHEP_HOME}}/logs/{{name}}-{{instance}}-out.log",
        "group": "logging",
        "blurb": "Where stdout goes. Written out, the default is {{SHEP_HOME}}/logs/{{name}}-{{instance}}-out.log",
        "accepts": ["a path, relative paths follow cwd",
                    "{{instance}}, {{name}} and {{SHEP_HOME}} expand",
                    "a parent that does not exist yet: warned"],
        "refuses": ["a {{secret:...}} token",
                    "one path for every instance, without merge_logs"],
        "neighbours": [{"field": "err_file",   "note": "shares the same collision rule"},
                       {"field": "merge_logs", "note": "shares one file, unless this path spells {{instance}} out"}]
    })))]
    pub out_file: Option<String>,
    /// Stderr log file (default: `{{SHEP_HOME}}/logs/{{name}}-{{instance}}-err.log`; `merge_logs` collapses to `{{name}}-err.log`)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "{{SHEP_HOME}}/logs/{{name}}-{{instance}}-err.log",
        "group": "logging",
        "blurb": "Where stderr goes. Written out, the default is {{SHEP_HOME}}/logs/{{name}}-{{instance}}-err.log",
        "accepts": ["a path, relative paths follow cwd",
                    "{{instance}}, {{name}} and {{SHEP_HOME}} expand",
                    "a parent that does not exist yet: warned"],
        "refuses": ["a {{secret:...}} token",
                    "one path for every instance, without merge_logs"],
        "neighbours": [{"field": "out_file",   "note": "shares the same collision rule"},
                       {"field": "merge_logs", "note": "shares one file, unless this path spells {{instance}} out"}]
    })))]
    pub err_file: Option<String>,
    /// Merge instance logs into one file pair
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "logging",
        "blurb": "Put every instance's output in one pair of files"
    })))]
    pub merge_logs: bool,
    /// How this app's own lines announce their level, for a client that
    /// filters by one.
    ///
    /// Ordered: rules are tried as written and the first match wins.
    /// Declaring any replaces the reader's built-in guess for this app
    /// rather than adding to it, so a line matching no rule announces no
    /// level. Nothing here hides a line: an unclassified line survives
    /// every level filter.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "[{ pattern = '\\[ERROR\\]', level = 'error' }]",
        "group": "logging",
        "blurb": "What this app's own log levels look like, for filtering",
        "accepts": ["a list of { pattern, level } rules, tried in order",
                    "a regex matched against the whole line, (?i) folds case",
                    "a level of trace, debug, info, warn, or error"],
        "refuses": ["an empty pattern, which would claim every line",
                    "a pattern regex cannot compile"],
        "neighbours": [{"field": "out_file", "note": "the lines these rules read"}]
    })))]
    pub level_rules: Vec<LevelRule>,
    /// Open the shepherd channel on fd 3 for this app on its own, without
    /// needing `wait_ready` or `shutdown_with_message` to imply it.
    ///
    /// Defaults to `false`: a socketpair plus two pump tasks per sheep is
    /// real cost weighed against spec §14.11's single-digit-MB idle-RSS
    /// goal, so a channel is opened only when something asks for one.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "inputs",
        "blurb": "Opens fd 3 so the app can talk to shep directly"
    })))]
    pub channel: bool,
    /// Open a pipe on this sheep's stdin, so `shep whisper` can write to it.
    ///
    /// Defaults to `false`, and the default is the decision rather than a
    /// convenience. Without it a sheep gets `/dev/null` on fd 0, which is what
    /// every sheep has had until now, and three things argue for keeping it
    /// that way unless an app asks otherwise:
    ///
    /// - Flipping it for the whole flock is a behaviour change to processes
    ///   nobody asked to change.
    /// - **Programs detect stdin.** A closed or null fd 0 is how a great many
    ///   programs decide they are non-interactive — no prompt, no pager, no
    ///   readline, no colour. Handing them a pipe silently moves them to the
    ///   other branch.
    /// - It costs a descriptor and a pump task per sheep for the whole life of
    ///   the process, against spec §14.11's single-digit-MB idle-RSS goal — the
    ///   same budget [`Self::channel`]'s own default is protecting.
    ///
    /// Unlike `channel`, nothing implies this: `wait_ready` and
    /// `shutdown_with_message` both need fd 3 and so turn `channel` on for you,
    /// while nothing in shep needs a sheep's stdin except an operator typing
    /// `shep whisper`. A sheep without it answers a `no_stdin` row and names
    /// this field.
    ///
    /// The pipe's write end lives as long as the sheep does, so the app sees
    /// EOF on stdin when the process is on its way out, never before.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "inputs",
        "blurb": "Keeps stdin open so shep whisper can write to the process"
    })))]
    pub stdin: bool,
    /// Expect `{"kind":"ready"}` on the shepherd channel
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "readiness",
        "blurb": "Wait for the app to say it is ready on the channel"
    })))]
    pub wait_ready: bool,
    /// Asserts that the app itself sets `SO_REUSEPORT` before it binds —
    /// shep binds nothing, so it cannot set the option on the app's behalf.
    /// The child process owns the mechanism (Node ≥22's `reusePort`, Go's
    /// `net.ListenConfig.Control`, nginx's `reuseport`); shep's contribution
    /// is permission for the old and new instance to overlap during reload,
    /// not the socket option itself.
    ///
    /// That permission is what the field buys, and it is read by exactly one
    /// thing: which reload the daemon runs for the app.
    ///
    /// - **Unset**, and the app has a `readiness_probe`: reload is SERIAL.
    ///   The instance being replaced is drained first and its replacement is
    ///   spawned into the empty slot, so the app is down for the length of
    ///   the drain. That is the cost of an honest answer — while both
    ///   instances are up, a probe against an address cannot say which of
    ///   them answered, and shep would take the outgoing instance's reply as
    ///   proof the incoming one is ready.
    /// - **Set**: reload OVERLAPS. The replacement is spawned alongside the
    ///   instance it replaces and takes over without a gap — if the app really does set
    ///   `SO_REUSEPORT`. If it does not, the replacement takes `EADDRINUSE`
    ///   and the reload fails, which is the failure this field exists to keep
    ///   opt-in.
    ///
    /// An app with no `readiness_probe` overlaps either way: with nothing
    /// probing an address, there is no answer for the wrong instance to give.
    /// So does one using `wait_ready`, because the shepherd channel a
    /// replacement reports on is its own — the instance being replaced has no
    /// way to answer it. Both of those need `SO_REUSEPORT` as much as a
    /// `reuse_port` app does if they bind an address, since they are overlapped
    /// too; what this field changes is which apps get overlapped, not what an
    /// overlap costs.
    ///
    /// Setting this on an app that does NOT set the socket option is the one
    /// way to get it wrong, and shep cannot check it: the option is set
    /// inside the child, after the fork, on a socket shep never sees.
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "process",
        "blurb": "The app sets SO_REUSEPORT itself, so reload may overlap the two instances"
    })))]
    pub reuse_port: bool,
    /// Readiness probe — gates reload's AwaitReady (spec §7)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": { "kind": "http", "target": "http://127.0.0.1:8080/ready" },
        "group": "readiness",
        "blurb": "A health check shep waits on before it treats a reload as finished",
        "accepts": ["kind: http, tcp, or exec",
                    "a target matching the kind: a url, host:port, or command"],
        "refuses": ["a failure_threshold of 0", "an interval below its own floor"],
        "neighbours": [{"field": "liveness_probe", "note": "uses a different interval floor"},
                       {"field": "reuse_port",     "note": "governs whether reload overlaps it"}]
    })))]
    pub readiness_probe: Option<ProbeConfig>,
    /// Liveness probe — failures feed the restart policy (spec §7)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": { "kind": "http", "target": "http://127.0.0.1:8080/healthz" },
        "group": "readiness",
        "blurb": "A health check that triggers a restart when it keeps failing",
        "accepts": ["kind: http, tcp, or exec",
                    "a target matching the kind: a url, host:port, or command"],
        "refuses": ["a failure_threshold of 0", "an interval below its own floor"],
        "neighbours": [{"field": "readiness_probe", "note": "uses a different interval floor"}]
    })))]
    pub liveness_probe: Option<ProbeConfig>,
    /// Watch include globs (empty = watch cwd)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "group": "watch",
        "blurb": "Which paths to watch. Empty means the working directory",
        "accepts": ["a list of glob patterns", "empty watches the whole cwd"],
        "refuses": ["a pattern globset cannot compile"],
        "neighbours": [{"field": "cwd",          "note": "globs are rooted here"},
                       {"field": "watch",        "note": "has no effect unless watch is on"},
                       {"field": "ignore_watch", "note": "skipped even when matched here"}]
    })))]
    pub watch_options: Vec<String>,
    /// Timezone for `cron_restart` (IANA name)
    #[cfg_attr(feature = "schema", schemars(extend("init" = {
        "example": "US/Eastern",
        "group": "cron",
        "blurb": "Which timezone cron_restart is read in, as an IANA name",
        "accepts": ["an IANA zone name, like US/Eastern"],
        "refuses": ["a name outside the IANA database"],
        "neighbours": [{"field": "cron_restart", "note": "the pattern this zone is read against"}]
    })))]
    pub cron_timezone: Option<String>,
}

/// One value an `env` table may carry: a string, or a bare boolean or whole
/// number an operator wrote without quoting.
///
/// Exists only to read a Flockfile, where the document is hand-written and a
/// bare value is a plausible shortcut. It never rides the wire: [`AppConfig`]
/// is serialized through its own impls, which see only `String`.
///
/// Debug does not leak an env value. A derived one would print the contents,
/// and a `{:?}` on a config mid-parse is how a secret reaches a log.
enum EnvValue {
    /// A quoted value, kept verbatim
    Str(String),
    /// A bare `true` or `false`
    Bool(bool),
    /// A whole number, signed or unsigned
    Int(i128),
}

impl fmt::Debug for EnvValue {
    /// Prints only the shape of the value, never its contents.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Str(_) => f.write_str("<str>"),
            Self::Bool(_) => f.write_str("<bool>"),
            Self::Int(_) => f.write_str("<int>"),
        }
    }
}

impl EnvValue {
    /// Renders the value as the string a process receives. Consuming: a borrow
    /// would force the `Str` arm to clone.
    #[must_use]
    fn into_string(self) -> String {
        match self {
            Self::Str(s) => s,
            Self::Bool(b) => b.to_string(),
            Self::Int(n) => n.to_string(),
        }
    }
}

impl<'de> serde::de::Deserialize<'de> for EnvValue {
    /// Reads one `env` value in whatever raw form it arrives.
    fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        struct EnvValueVisitor;

        impl serde::de::Visitor<'_> for EnvValueVisitor {
            type Value = EnvValue;

            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_str("a string, boolean, or whole number")
            }

            /// A quoted value, kept verbatim.
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<EnvValue, E> {
                Ok(EnvValue::Str(v.to_string()))
            }

            /// A quoted value from a non-borrowed source.
            fn visit_string<E: serde::de::Error>(self, v: String) -> Result<EnvValue, E> {
                Ok(EnvValue::Str(v))
            }

            /// A bare `true` or `false`.
            fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<EnvValue, E> {
                Ok(EnvValue::Bool(v))
            }

            /// A whole signed number.
            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<EnvValue, E> {
                // i128 holds the full i64 range losslessly.
                Ok(EnvValue::Int(i128::from(v)))
            }

            /// A whole unsigned number. Only JSON can produce one beyond
            /// `i64::MAX`; TOML's own spec bounds integers to signed 64-bit,
            /// so its `visit_u64` input is always within `i64::MAX` and the
            /// wider type is invisible from a TOML Flockfile. i128 holds
            /// whatever we receive losslessly, so no value is refused.
            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<EnvValue, E> {
                Ok(EnvValue::Int(i128::from(v)))
            }

            /// A float, refused. `f64` carries no trailing zero and no
            /// written precision, so `1.10` would reach the process as
            /// `1.1`. The value is left out of the message: an `env` value
            /// never reaches a log.
            fn visit_f64<E: serde::de::Error>(self, _v: f64) -> Result<EnvValue, E> {
                Err(E::custom(
                    "a float env value loses its written form, quote it",
                ))
            }
        }

        de.deserialize_any(EnvValueVisitor)
    }
}

/// Reads an `env` table, rendering each [`EnvValue`] as the string a process
/// receives. The `deserialize_with` on [`AppConfig::env`].
fn deserialize_env<'de, D: Deserializer<'de>>(de: D) -> Result<BTreeMap<String, String>, D::Error> {
    Ok(BTreeMap::<String, EnvValue>::deserialize(de)?
        .into_iter()
        .map(|(k, v)| (k, v.into_string()))
        .collect())
}

/// Redacts `env`: only its length is printed.
impl fmt::Debug for AppConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AppConfig")
            .field("name", &self.name)
            .field("script", &self.script)
            .field("env", &format_args!("<{} vars>", self.env.len()))
            .finish_non_exhaustive()
    }
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            name: String::new(),
            script: String::new(),
            args: Vec::new(),
            cwd: None,
            interpreter: None,
            env: BTreeMap::new(),
            environment: None,
            instances: 1,
            autorestart: true,
            autostart: true,
            stop_exit_codes: Vec::new(),
            min_uptime: UpDuration::from_millis(1000),
            max_restarts: 16,
            restart_delay: None,
            // Not None: see the field's doc comment. An unstable exit with
            // no restart policy configured must not restart instantly.
            exp_backoff_restart_delay: Some(UpDuration::from_millis(100)),
            kill_signal: None,
            kill_timeout: UpDuration::from_millis(1600),
            shutdown_with_message: false,
            listen_timeout: UpDuration::from_millis(3000),
            graceful_timeout: UpDuration::from_millis(8000),
            action_timeout: UpDuration::from_millis(3000),
            max_memory: None,
            watch: false,
            ignore_watch: Vec::new(),
            watch_delay: None,
            cron_restart: None,
            fold: None,
            depends_on: Vec::new(),
            user: None,
            group: None,
            out_file: None,
            err_file: None,
            merge_logs: false,
            level_rules: Vec::new(),
            channel: false,
            stdin: false,
            wait_ready: false,
            reuse_port: false,
            readiness_probe: None,
            liveness_probe: None,
            watch_options: Vec::new(),
            cron_timezone: None,
        }
    }
}

impl AppConfig {
    /// A minimal config with spec defaults, the programmatic entry point.
    #[must_use]
    pub fn minimal(name: &str, script: &str) -> Self {
        Self {
            name: name.to_string(),
            script: script.to_string(),
            ..Self::default()
        }
    }

    /// The names of the fields whose values differ between `self` and
    /// `other`, in field-name order.
    ///
    /// Names only, never values. The one caller sends this list across the
    /// wire to be printed at an operator, and [`AppConfig::env`] carries
    /// secrets, so a differing `env` reports `"env"` and stops there.
    ///
    /// Compare configs that have both been through
    /// [`normalize`](fn@crate::config::normalize). Two configs differing only
    /// in what normalization would have filled in are not a difference an
    /// operator can act on, and reporting them would make the caller noisy
    /// about nothing.
    ///
    /// # Example
    ///
    /// ```
    /// use shep_core::config::AppConfig;
    ///
    /// let stored = AppConfig::minimal("web", "./srv");
    /// let mut edited = stored.clone();
    /// edited.cwd = Some("/srv".to_string());
    ///
    /// assert_eq!(stored.drifted_fields(&edited), vec!["cwd".to_string()]);
    /// assert!(stored.drifted_fields(&stored).is_empty());
    /// ```
    #[must_use]
    pub fn drifted_fields(&self, other: &Self) -> Vec<String> {
        if self == other {
            return Vec::new();
        }
        // Serde-compared, not field by field: a new field needs no edit here.
        // Sorted since `serde_json::Map` is a `BTreeMap` only while
        // `preserve_order` is off crate-wide. An empty result means no
        // drift, or none could be computed.
        let (Ok(serde_json::Value::Object(mine)), Ok(serde_json::Value::Object(theirs))) =
            (serde_json::to_value(self), serde_json::to_value(other))
        else {
            return Vec::new();
        };
        let mut fields: Vec<String> = mine
            .iter()
            .filter(|(key, value)| theirs.get(key.as_str()) != Some(value))
            .map(|(key, _)| key.clone())
            .collect();
        fields.sort_unstable();
        fields
    }
}

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

    use crate::config::{LevelRule, LineLevel, NormalizeError};
    use crate::values::{MemSize, UpDuration};

    #[test]
    fn minimal_config_gets_spec_defaults() {
        let app = AppConfig::minimal("web", "./server");
        assert_eq!(app.name, "web");
        assert_eq!(app.script, "./server");
        assert!(app.autorestart);
        assert!(app.autostart);
        assert_eq!(app.instances, 1);
        assert_eq!(app.min_uptime, UpDuration::from_millis(1000));
        assert_eq!(app.max_restarts, 16);
        assert_eq!(app.kill_timeout, UpDuration::from_millis(1600));
        assert_eq!(app.listen_timeout, UpDuration::from_millis(3000));
        assert_eq!(app.graceful_timeout, UpDuration::from_millis(8000));
        assert_eq!(app.action_timeout, UpDuration::from_millis(3000));
        assert!(app.max_memory.is_none());
        assert!(app.fold.is_none());
        assert!(!app.channel);
    }

    #[test]
    fn unstable_restarts_are_throttled_by_default() {
        let app = AppConfig::minimal("web", "./srv");
        assert_eq!(
            app.exp_backoff_restart_delay,
            Some(UpDuration::from_millis(100))
        );
    }

    #[test]
    fn stdin_is_not_piped_unless_the_app_asks() {
        let app = AppConfig::minimal("web", "./srv");
        assert!(!app.stdin);
        let parsed: AppConfig = toml::from_str("name = \"web\"\nscript = \"./srv\"").unwrap();
        assert!(!parsed.stdin);
    }

    #[test]
    fn the_flockfile_key_is_stdin() {
        let parsed: AppConfig =
            toml::from_str("name = \"web\"\nscript = \"./srv\"\nstdin = true").unwrap();
        assert!(parsed.stdin);
    }

    #[test]
    fn environment_defaults_to_absent_and_parses_from_a_flockfile() {
        assert_eq!(AppConfig::default().environment, None);
        let app: AppConfig =
            toml::from_str("name = \"web\"\nscript = \"./srv\"\nenvironment = \"staging\"")
                .unwrap();
        assert_eq!(app.environment.as_deref(), Some("staging"));
    }

    #[test]
    fn toml_round_trip_with_newtypes() {
        let toml_src = r#"
name = "worker"
script = "python3"
args = ["job.py", "--fast"]
max_memory = "512M"
min_uptime = "5s"
fold = "backend"
env = { RUST_LOG = "info" }
"#;
        let app: AppConfig = toml::from_str(toml_src).unwrap();
        assert_eq!(app.max_memory, Some("512M".parse::<MemSize>().unwrap()));
        assert_eq!(app.min_uptime, UpDuration::from_millis(5000));
        assert_eq!(app.fold.as_deref(), Some("backend"));
        assert_eq!(app.env.get("RUST_LOG").map(String::as_str), Some("info"));
        assert_eq!(app.args, vec!["job.py", "--fast"]);
    }

    /// Raw TOML scalars in `env` read as their string form. `true` becomes
    /// `"true"`, `8080` becomes `"8080"`, and quoted strings pass through.
    /// A single test here covers the deserialization path; the
    /// `flockfile` test that reads the same document through all four
    /// formats covers the format dispatch.
    #[test]
    fn env_coerces_raw_scalars_to_their_string_form() {
        let src = r#"
name = "web"
script = "./srv"
env = { SOME_BOOL = true, PORT = 8080, NEG = -1, STR = "plain" }
"#;
        let app: AppConfig = toml::from_str(src).unwrap();
        assert_eq!(app.env["SOME_BOOL"], "true");
        assert_eq!(app.env["PORT"], "8080");
        assert_eq!(app.env["NEG"], "-1");
        assert_eq!(app.env["STR"], "plain");
    }

    /// A protocol-8 peer still serializes `increment_var`, which this build
    /// no longer has. It must deserialize and be dropped rather than error,
    /// since `MIN_SUPPORTED` is 8 and an error here would refuse every peer
    /// built before the field went.
    ///
    /// Fails if `deny_unknown_fields` comes back to this struct. It was
    /// moved to `Flockfile::parse` on purpose, so a newer daemon can hand an
    /// older client a config it does not fully understand. Why dropping the
    /// field is safe rather than merely tolerated is in `docs/decisions.md`.
    #[test]
    fn a_protocol_8_payload_carrying_increment_var_still_deserializes() {
        let src = r#"{ "name":"web","script":"./srv","increment_var":null }"#;
        let app = serde_json::from_str::<AppConfig>(src)
            .expect("a version-8 payload must not be refused for a field this build dropped");
        assert_eq!(app.name, "web");
        assert_eq!(app.script, "./srv");

        let populated = r#"{ "name":"web","script":"./srv","increment_var":"WORKER_ID" }"#;
        let app = serde_json::from_str::<AppConfig>(populated)
            .expect("a populated one is ignored too, not refused");
        assert_eq!(app.name, "web");
    }

    /// A float is refused rather than coerced. `f64` carries no trailing zero
    /// and no written precision, so accepting one hands the process a value
    /// the operator did not write. Quoting is the way to keep the text.
    ///
    /// Asserted through JSON: a TOML error echoes the offending source line,
    /// which would put the value in the message whatever serde said.
    #[test]
    fn env_refuses_a_float_because_its_written_form_would_not_survive() {
        let src = r#"{ "name":"web","script":"./srv","env":{ "RATIO": 1.10 } }"#;
        let err = serde_json::from_str::<AppConfig>(src)
            .expect_err("a float env value must be refused, not rounded")
            .to_string();
        assert!(
            err.contains("quote it"),
            "the error must name the fix, got: {err}"
        );
        assert!(!err.contains("1.1"), "the error leaked the value: {err}");

        let quoted = src.replace("1.10", r#""1.10""#);
        let app: AppConfig = serde_json::from_str(&quoted).unwrap();
        assert_eq!(app.env["RATIO"], "1.10");

        assert!(
            toml::from_str::<AppConfig>(
                "name = \"web\"\nscript = \"./srv\"\nenv = { RATIO = 1.10 }\n"
            )
            .is_err(),
            "TOML must refuse a float too"
        );
    }

    /// A whole number larger than `i64::MAX` is valid JSON and must load.
    /// TOML cannot reach this test: its spec bounds integers to signed 64-bit,
    /// so only JSON exercises this path. The value stringifies to its full
    /// positive form, not a negative wrap. Pinned to the exact string.
    #[test]
    fn env_reads_a_number_beyond_i64_max_without_wrapping() {
        let beyond_i64 = u64::MAX; // 18446744073709551615
        let src = format!(r#"{{ "name":"web","script":"./srv","env":{{ "BIG": {beyond_i64} }} }}"#);
        let app = serde_json::from_str::<AppConfig>(&src)
            .expect("a u64 beyond i64::MAX is valid JSON and must load");
        assert_eq!(app.env["BIG"], "18446744073709551615");
    }

    /// Serialization is the inverse of the coercion: whatever form a value
    /// arrived as, the wire form is a string. A `true` that deserialized
    /// into `"true"` must serialize to the JSON string `"true"`, not the
    /// boolean `true`.
    #[test]
    fn env_serialization_is_always_string_regardless_of_input_form() {
        let src = r#"
name = "web"
script = "./srv"
env = { SOME_BOOL = true, PORT = 8080, STR = "hello" }
"#;
        let app: AppConfig = toml::from_str(src).unwrap();
        let wire = serde_json::to_value(&app).unwrap();
        for (key, expected) in [("SOME_BOOL", "true"), ("PORT", "8080"), ("STR", "hello")] {
            assert_eq!(
                wire["env"].get(key).and_then(serde_json::Value::as_str),
                Some(expected),
                "wire form of {key} must be a string, not a scalar"
            );
        }
    }

    /// A value that is neither a string, boolean, nor number is refused, not
    /// guessed at. An array or object under `env` is a structural mistake —
    /// an operator meant a table or a list, and guessing a serialization is
    /// how a wrong value hides for months.
    #[test]
    fn env_refuses_structural_values() {
        for (label, inner) in [("array", r#"["a", "b"]"#), ("object", r#"{"k": "v"}"#)] {
            let src = format!(r#"{{ "name":"web","script":"./srv","env":{{"X":{inner}}}}}"#);
            assert!(
                serde_json::from_str::<AppConfig>(&src).is_err(),
                "a {label} env value must be refused"
            );
        }
    }

    /// The wire path is the opposite of a Flockfile's: an unknown field
    /// means a newer peer, and ignoring it is what stops a new Flockfile
    /// field breaking an older client that reads a config off the wire.
    /// `deny_unknown_fields` used to live here; the same typo is now
    /// refused only at `Flockfile::parse`, where the input really is a
    /// hand-written file.
    #[test]
    fn an_unknown_field_on_the_wire_is_ignored_rather_than_refused() {
        let config: AppConfig =
            serde_json::from_str(r#"{"name":"web","script":"./srv","invented_next_year":true}"#)
                .expect("the wire path tolerates what it does not know");
        assert_eq!(config.name, "web");
    }

    #[test]
    fn probe_config_parses_with_defaults() {
        let src = r#"
name = "api"
script = "./api"

[readiness_probe]
kind = "http"
target = "http://127.0.0.1:8080/healthz"
"#;
        let app: AppConfig = toml::from_str(src).unwrap();
        let probe = app.readiness_probe.unwrap();
        assert_eq!(probe.kind, ProbeKind::Http);
        assert_eq!(probe.target, "http://127.0.0.1:8080/healthz");
        assert_eq!(probe.interval, UpDuration::from_millis(10_000));
        assert_eq!(probe.timeout, UpDuration::from_millis(5_000));
        assert_eq!(probe.failure_threshold, 3);
        assert!(app.liveness_probe.is_none());
    }

    #[test]
    fn debug_redacts_env_values() {
        // Exact string pinned so a lazy derive(Debug) refactor fails here.
        let mut app = AppConfig::minimal("web", "./srv");
        app.env
            .insert("DATABASE_URL".to_string(), "postgres://secret".to_string());
        app.env.insert("RUST_LOG".to_string(), "info".to_string());
        assert_eq!(
            format!("{app:?}"),
            "AppConfig { name: \"web\", script: \"./srv\", env: <2 vars>, .. }"
        );
    }

    /// `EnvValue::Debug` prints only the kind, never the value — the exact
    /// string is pinned so a derived `Debug` (which prints the contents) fails
    /// here. This is the unit half of the redaction guarantee.
    #[test]
    fn env_value_debug_never_prints_the_value() {
        let cases = [
            (EnvValue::Str("postgres://secret".to_string()), "<str>"),
            (EnvValue::Bool(true), "<bool>"),
            (EnvValue::Int(9_223_372_036_854_775_807), "<int>"),
        ];
        for (value, expected) in cases {
            assert_eq!(format!("{value:?}"), expected);
        }
    }

    #[test]
    fn an_unedited_config_has_drifted_in_no_field() {
        let app = AppConfig::minimal("web", "./srv");

        assert!(app.drifted_fields(&app.clone()).is_empty());
    }

    #[test]
    fn drift_names_every_edited_field_and_no_other() {
        // Two fields, not one, so a comparator that stopped at the first
        // difference fails here.
        let stored = AppConfig::minimal("proto-api", "./proto-enum-api");
        let mut edited = stored.clone();
        edited.cwd = Some("/srv/pogo-proto-api".to_string());
        edited.args = vec!["-config".to_string(), "config.toml".to_string()];

        assert_eq!(
            stored.drifted_fields(&edited),
            vec!["args".to_string(), "cwd".to_string()]
        );
    }

    #[test]
    fn drift_reports_env_by_name_and_never_by_value() {
        let stored = AppConfig::minimal("web", "./srv");
        let mut edited = stored.clone();
        edited
            .env
            .insert("DATABASE_URL".to_string(), "postgres://hunter2".to_string());

        let fields = edited.drifted_fields(&stored);

        assert_eq!(fields, vec!["env".to_string()]);
        // Names go to an operator; a value never should.
        assert!(!fields.concat().contains("hunter2"));
    }

    #[test]
    fn drift_is_symmetric() {
        let stored = AppConfig::minimal("web", "./srv");
        let mut edited = stored.clone();
        edited.instances = 4;

        assert_eq!(
            stored.drifted_fields(&edited),
            edited.drifted_fields(&stored)
        );
        assert_eq!(
            stored.drifted_fields(&edited),
            vec!["instances".to_string()]
        );
    }

    /// The path fields are the ones an operator gets wrong, and the ones the
    /// type table cannot describe. Each states what it takes.
    #[test]
    fn the_path_fields_state_what_they_accept() {
        let schema = crate::config::flockfile_schema_json().to_value();
        let props = schema
            .pointer("/$defs/AppConfig/properties")
            .and_then(serde_json::Value::as_object)
            .expect("app config properties must exist");
        for name in ["cwd", "script", "out_file", "err_file"] {
            let accepts = props[name]["init"]["accepts"].as_array();
            assert!(
                accepts.is_some_and(|forms| !forms.is_empty()),
                "{name} carries no accepted forms"
            );
        }
    }

    /// Every entry carries both halves, so nothing renders half a line.
    #[test]
    fn every_neighbour_entry_carries_a_field_and_a_note() {
        let schema = crate::config::flockfile_schema_json().to_value();
        let props = schema
            .pointer("/$defs/AppConfig/properties")
            .and_then(serde_json::Value::as_object)
            .expect("app config properties must exist");
        for (name, prop) in props {
            let Some(entries) = prop["init"]["neighbours"].as_array() else {
                continue;
            };
            for entry in entries {
                assert!(
                    entry["field"].is_string(),
                    "{name} has a neighbour with no field"
                );
                assert!(
                    entry["note"].is_string(),
                    "{name} has a neighbour with no note"
                );
            }
        }
    }

    /// Where a per-field `refuses` clause is enforced.
    ///
    /// A panel naming a refusal nothing makes is the defect this table
    /// exists to stop, so a claim is either exercised against `normalize`
    /// or carries the reason it cannot be.
    enum Proof {
        /// `normalize` refuses this config, with an error this predicate
        /// accepts.
        Refused {
            /// A sheep whose only fault is the one the claim names.
            /// Boxed so this arm does not set the size of every row.
            value: Box<AppConfig>,
            /// The variant the refusal must arrive as.
            matches: fn(&NormalizeError) -> bool,
        },
        /// Enforced somewhere `normalize` cannot reach, named here so the
        /// gap stays a decision rather than an oversight.
        Elsewhere(&'static str),
    }

    /// One clause of one field's `refuses` list, with its proof.
    struct RefusalClaim {
        /// The Flockfile field carrying the clause.
        field: &'static str,
        /// The clause, character for character as the schema writes it.
        refusal: &'static str,
        /// What makes it true.
        proof: Proof,
    }

    /// A claim `normalize` proves.
    fn refused(
        field: &'static str,
        refusal: &'static str,
        value: AppConfig,
        matches: fn(&NormalizeError) -> bool,
    ) -> RefusalClaim {
        RefusalClaim {
            field,
            refusal,
            proof: Proof::Refused {
                value: Box::new(value),
                matches,
            },
        }
    }

    /// A claim enforced past `normalize`, with `where` naming the enforcer.
    fn elsewhere(field: &'static str, refusal: &'static str, place: &'static str) -> RefusalClaim {
        RefusalClaim {
            field,
            refusal,
            proof: Proof::Elsewhere(place),
        }
    }

    /// A minimal sheep with one thing changed, so a row carries only the
    /// value its own claim is about.
    fn sheep(edit: impl FnOnce(&mut AppConfig)) -> AppConfig {
        let mut app = AppConfig::minimal("web", "./srv");
        edit(&mut app);
        app
    }

    /// A probe of `kind` with everything else at its default, read from the
    /// same functions serde fills a missing field from.
    fn probe(kind: ProbeKind, target: &str) -> ProbeConfig {
        ProbeConfig {
            kind,
            target: target.to_owned(),
            interval: default_probe_interval(),
            timeout: default_probe_timeout(),
            failure_threshold: default_failure_threshold(),
        }
    }

    /// Every `refuses` clause in the schema, paired with what enforces it.
    ///
    /// Ordered by field, then as the field writes them. A clause naming
    /// several spellings gets a row for each, since one of them passing
    /// says nothing about the rest.
    ///
    /// Refusals only. Most fields have nothing validating them, so proving
    /// an `accepts` clause by handing `normalize` a value it never inspects
    /// would pass whatever the clause said.
    fn refusal_claims() -> Vec<RefusalClaim> {
        vec![
            refused(
                "args",
                "an unclosed {{ token",
                sheep(|a| a.args = vec!["{{name".to_owned()]),
                |e| matches!(e, NormalizeError::BadTemplate { .. }),
            ),
            refused(
                "args",
                "a token shep does not define",
                sheep(|a| a.args = vec!["{{slot}}".to_owned()]),
                |e| matches!(e, NormalizeError::BadTemplate { .. }),
            ),
            refused(
                "cron_restart",
                "a field outside its valid range",
                sheep(|a| a.cron_restart = Some("99 * * * *".to_owned())),
                |e| matches!(e, NormalizeError::InvalidCron { .. }),
            ),
            refused(
                "cron_restart",
                "a sixth seconds field, or L, W, # or ?",
                sheep(|a| a.cron_restart = Some("0 0 * * * *".to_owned())),
                |e| matches!(e, NormalizeError::InvalidCron { .. }),
            ),
            refused(
                "cron_restart",
                "a sixth seconds field, or L, W, # or ?",
                sheep(|a| a.cron_restart = Some("0 0 L * *".to_owned())),
                |e| matches!(e, NormalizeError::InvalidCron { .. }),
            ),
            refused(
                "cron_restart",
                "a sixth seconds field, or L, W, # or ?",
                sheep(|a| a.cron_restart = Some("0 0 15W * *".to_owned())),
                |e| matches!(e, NormalizeError::InvalidCron { .. }),
            ),
            refused(
                "cron_restart",
                "a sixth seconds field, or L, W, # or ?",
                sheep(|a| a.cron_restart = Some("0 0 * * 1#2".to_owned())),
                |e| matches!(e, NormalizeError::InvalidCron { .. }),
            ),
            refused(
                "cron_restart",
                "a sixth seconds field, or L, W, # or ?",
                sheep(|a| a.cron_restart = Some("0 0 ? * *".to_owned())),
                |e| matches!(e, NormalizeError::InvalidCron { .. }),
            ),
            refused(
                "cron_restart",
                "a pattern croner cannot parse",
                sheep(|a| a.cron_restart = Some("every tuesday".to_owned())),
                |e| matches!(e, NormalizeError::InvalidCron { .. }),
            ),
            refused(
                "cron_timezone",
                "a name outside the IANA database",
                sheep(|a| a.cron_timezone = Some("Mars/Olympus".to_owned())),
                |e| matches!(e, NormalizeError::InvalidTimezone { .. }),
            ),
            refused(
                "depends_on",
                "this sheep's own name",
                sheep(|a| a.depends_on = vec!["web".to_owned()]),
                |e| matches!(e, NormalizeError::SelfDependency(_)),
            ),
            refused(
                "depends_on",
                "a name:slot instance reference",
                sheep(|a| a.depends_on = vec!["api:0".to_owned()]),
                |e| matches!(e, NormalizeError::InstanceDependency { .. }),
            ),
            elsewhere(
                "env",
                "a float, since 1.10 would arrive as 1.1",
                "EnvValue's Deserialize, before normalize sees the table",
            ),
            refused(
                "env",
                "a token shep does not define",
                sheep(|a| {
                    a.env.insert("WORKER".to_owned(), "{{slot}}".to_owned());
                }),
                |e| matches!(e, NormalizeError::BadTemplate { .. }),
            ),
            refused(
                "env",
                "SHEP_INSTANCE, SHEP_NAME, or SHEP_ENVIRONMENT, which shep sets itself",
                sheep(|a| {
                    a.env.insert("SHEP_INSTANCE".to_owned(), "0".to_owned());
                }),
                |e| matches!(e, NormalizeError::ReservedEnvVar { .. }),
            ),
            refused(
                "env",
                "SHEP_INSTANCE, SHEP_NAME, or SHEP_ENVIRONMENT, which shep sets itself",
                sheep(|a| {
                    a.env.insert("SHEP_NAME".to_owned(), "web".to_owned());
                }),
                |e| matches!(e, NormalizeError::ReservedEnvVar { .. }),
            ),
            refused(
                "env",
                "SHEP_INSTANCE, SHEP_NAME, or SHEP_ENVIRONMENT, which shep sets itself",
                sheep(|a| {
                    a.env
                        .insert("SHEP_ENVIRONMENT".to_owned(), "staging".to_owned());
                }),
                |e| matches!(e, NormalizeError::ReservedEnvVar { .. }),
            ),
            refused(
                "env",
                "an unclosed {{ token",
                sheep(|a| {
                    a.env.insert("GREETING".to_owned(), "{{name".to_owned());
                }),
                |e| matches!(e, NormalizeError::BadTemplate { .. }),
            ),
            refused(
                "environment",
                "all, the store's every-environment slot",
                sheep(|a| a.environment = Some(crate::secrets::ALL_ENVIRONMENTS.to_owned())),
                |e| matches!(e, NormalizeError::InvalidEnvironment { .. }),
            ),
            refused(
                "environment",
                "a name outside letters, digits, dot, underscore, or dash",
                sheep(|a| a.environment = Some("staging!".to_owned())),
                |e| matches!(e, NormalizeError::InvalidEnvironment { .. }),
            ),
            refused(
                "err_file",
                "a {{secret:...}} token",
                sheep(|a| a.err_file = Some("/var/log/{{secret:tenant}}.log".to_owned())),
                |e| matches!(e, NormalizeError::SecretInLogPath { .. }),
            ),
            refused(
                "err_file",
                "one path for every instance, without merge_logs",
                sheep(|a| {
                    a.instances = 2;
                    a.err_file = Some("/var/log/web-err.log".to_owned());
                }),
                |e| matches!(e, NormalizeError::SharedLogPath { .. }),
            ),
            elsewhere(
                "group",
                "a name with no group entry",
                "shep-daemon's privilege::resolve, at spawn",
            ),
            elsewhere(
                "group",
                "another group, unless the shepherd runs as root",
                "shep-daemon's privilege::resolve, at spawn",
            ),
            refused(
                "ignore_watch",
                "a pattern globset cannot compile",
                sheep(|a| a.ignore_watch = vec!["[".to_owned()]),
                |e| matches!(e, NormalizeError::InvalidWatchGlob { .. }),
            ),
            refused(
                "kill_signal",
                "a signal outside that list",
                sheep(|a| a.kill_signal = Some("SIGKILL".to_owned())),
                |e| matches!(e, NormalizeError::InvalidKillSignal { .. }),
            ),
            refused(
                "level_rules",
                "an empty pattern, which would claim every line",
                sheep(|a| {
                    a.level_rules = vec![LevelRule {
                        pattern: String::new(),
                        level: LineLevel::Error,
                    }];
                }),
                |e| matches!(e, NormalizeError::InvalidLevelRule { .. }),
            ),
            refused(
                "level_rules",
                "a pattern regex cannot compile",
                sheep(|a| {
                    a.level_rules = vec![LevelRule {
                        pattern: "[unterminated".to_owned(),
                        level: LineLevel::Error,
                    }];
                }),
                |e| matches!(e, NormalizeError::InvalidLevelRule { .. }),
            ),
            refused(
                "liveness_probe",
                "a failure_threshold of 0",
                sheep(|a| {
                    let mut p = probe(ProbeKind::Tcp, "127.0.0.1:8080");
                    p.failure_threshold = 0;
                    a.liveness_probe = Some(p);
                }),
                |e| matches!(e, NormalizeError::ZeroFailureThreshold { .. }),
            ),
            refused(
                "liveness_probe",
                "an interval below its own floor",
                sheep(|a| {
                    let mut p = probe(ProbeKind::Tcp, "127.0.0.1:8080");
                    p.interval = UpDuration::from_millis(500);
                    a.liveness_probe = Some(p);
                }),
                |e| matches!(e, NormalizeError::IntervalBelowMinimum { .. }),
            ),
            refused(
                "name",
                "a path separator or a colon",
                sheep(|a| a.name = "web/api".to_owned()),
                |e| matches!(e, NormalizeError::InvalidName(_)),
            ),
            refused(
                "name",
                "a path separator or a colon",
                sheep(|a| a.name = r"web\api".to_owned()),
                |e| matches!(e, NormalizeError::InvalidName(_)),
            ),
            refused(
                "name",
                "a path separator or a colon",
                sheep(|a| a.name = "web:0".to_owned()),
                |e| matches!(e, NormalizeError::InvalidName(_)),
            ),
            refused(
                "name",
                "a bare . or ..",
                sheep(|a| a.name = ".".to_owned()),
                |e| matches!(e, NormalizeError::InvalidName(_)),
            ),
            refused(
                "name",
                "a bare . or ..",
                sheep(|a| a.name = "..".to_owned()),
                |e| matches!(e, NormalizeError::InvalidName(_)),
            ),
            refused(
                "out_file",
                "a {{secret:...}} token",
                sheep(|a| a.out_file = Some("/var/log/{{secret:tenant}}.log".to_owned())),
                |e| matches!(e, NormalizeError::SecretInLogPath { .. }),
            ),
            refused(
                "out_file",
                "one path for every instance, without merge_logs",
                sheep(|a| {
                    a.instances = 2;
                    a.out_file = Some("/var/log/web-out.log".to_owned());
                }),
                |e| matches!(e, NormalizeError::SharedLogPath { .. }),
            ),
            refused(
                "readiness_probe",
                "a failure_threshold of 0",
                sheep(|a| {
                    let mut p = probe(ProbeKind::Tcp, "127.0.0.1:8080");
                    p.failure_threshold = 0;
                    a.readiness_probe = Some(p);
                }),
                |e| matches!(e, NormalizeError::ZeroFailureThreshold { .. }),
            ),
            refused(
                "readiness_probe",
                "an interval below its own floor",
                sheep(|a| {
                    let mut p = probe(ProbeKind::Tcp, "127.0.0.1:8080");
                    p.interval = UpDuration::from_millis(0);
                    a.readiness_probe = Some(p);
                }),
                |e| matches!(e, NormalizeError::IntervalBelowMinimum { .. }),
            ),
            elsewhere(
                "user",
                "a name with no passwd entry",
                "shep-daemon's privilege::resolve, at spawn",
            ),
            elsewhere(
                "user",
                "another user, unless the shepherd runs as root",
                "shep-daemon's privilege::resolve, at spawn",
            ),
            refused(
                "watch_options",
                "a pattern globset cannot compile",
                sheep(|a| a.watch_options = vec!["[".to_owned()]),
                |e| matches!(e, NormalizeError::InvalidWatchGlob { .. }),
            ),
        ]
    }

    /// fails if a field claims a refusal `normalize` does not make. The
    /// static tables behind the same panel are parser-backed in
    /// `shep-cli`'s `lookout::validation`; a per-field clause is only
    /// backed here.
    #[test]
    fn every_per_field_refusal_is_one_normalize_really_makes() {
        for claim in refusal_claims() {
            let Proof::Refused { value, matches } = claim.proof else {
                continue;
            };
            let field = claim.field;
            let refusal = claim.refusal;
            match crate::config::normalize(*value) {
                Ok(_) => panic!("{field} says it refuses {refusal}, and normalize accepted it"),
                Err(err) => assert!(
                    matches(&err),
                    "{field}'s \"{refusal}\" was refused as {err:?}, which is not the variant \
                     the table names"
                ),
            }
        }
    }

    /// fails if a clause starts or stops leaning on an enforcer outside
    /// this crate. The list is written twice on purpose: without a second
    /// copy, `Proof::Elsewhere` is a free pass past the test above.
    #[test]
    fn the_clauses_enforced_outside_normalize_are_the_ones_named() {
        let claims = refusal_claims();
        let outside: Vec<(&str, &str, &str)> = claims
            .iter()
            .filter_map(|claim| match claim.proof {
                Proof::Elsewhere(place) => Some((claim.field, claim.refusal, place)),
                Proof::Refused { .. } => None,
            })
            .collect();
        assert_eq!(
            outside,
            vec![
                (
                    "env",
                    "a float, since 1.10 would arrive as 1.1",
                    "EnvValue's Deserialize, before normalize sees the table",
                ),
                (
                    "group",
                    "a name with no group entry",
                    "shep-daemon's privilege::resolve, at spawn",
                ),
                (
                    "group",
                    "another group, unless the shepherd runs as root",
                    "shep-daemon's privilege::resolve, at spawn",
                ),
                (
                    "user",
                    "a name with no passwd entry",
                    "shep-daemon's privilege::resolve, at spawn",
                ),
                (
                    "user",
                    "another user, unless the shepherd runs as root",
                    "shep-daemon's privilege::resolve, at spawn",
                ),
            ]
        );
    }

    /// fails if a value the panel offers with one keypress is one
    /// `normalize` turns around. A suggestion is a literal fill, so it is
    /// the one claim a config can be checked against directly.
    #[test]
    fn every_suggested_value_is_one_normalize_accepts() {
        let schema = crate::config::flockfile_schema_json().to_value();
        let props = schema
            .pointer("/$defs/AppConfig/properties")
            .and_then(serde_json::Value::as_object)
            .expect("app config properties must exist");
        for (field, prop) in props {
            let Some(values) = prop["init"]["suggest"].as_array() else {
                continue;
            };
            for value in values {
                let value = value.as_str().expect("a suggestion is a string");
                let app = sheep(|a| match field.as_str() {
                    "cron_restart" => a.cron_restart = Some(value.to_owned()),
                    "kill_signal" => a.kill_signal = Some(value.to_owned()),
                    other => panic!("{other} suggests values that this test cannot place"),
                });
                assert!(
                    crate::config::normalize(app).is_ok(),
                    "{field} suggests `{value}`, which normalize refuses"
                );
            }
        }
    }

    /// fails if the schema and the table have drifted apart in either
    /// direction: a new clause with no proof, or a proof for a clause no
    /// field writes any more.
    #[test]
    fn the_refusal_table_and_the_schema_name_the_same_clauses() {
        let schema = crate::config::flockfile_schema_json().to_value();
        let props = schema
            .pointer("/$defs/AppConfig/properties")
            .and_then(serde_json::Value::as_object)
            .expect("app config properties must exist");
        let in_schema: Vec<(&str, &str)> = props
            .iter()
            .filter_map(|(field, prop)| Some((field.as_str(), prop["init"]["refuses"].as_array()?)))
            .flat_map(|(field, clauses)| {
                clauses.iter().map(move |clause| {
                    (
                        field,
                        clause.as_str().expect("a refusal clause is a string"),
                    )
                })
            })
            .collect();

        let claims = refusal_claims();
        let proved: Vec<(&str, &str)> = claims.iter().map(|c| (c.field, c.refusal)).collect();

        let unproved: Vec<_> = in_schema
            .iter()
            .filter(|clause| !proved.contains(clause))
            .collect();
        let stale: Vec<_> = proved
            .iter()
            .filter(|clause| !in_schema.contains(clause))
            .collect();
        assert!(
            unproved.is_empty() && stale.is_empty(),
            "a refusal and its proof live together, in refusal_claims in this file.\n  \
             claimed by a field, proved nowhere: {unproved:?}\n  \
             proved here, claimed by no field: {stale:?}"
        );
    }
}