shep-core 0.5.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
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
//! Validation and normalization: `AppConfig` -> `ResolvedApp`
//!
//! `ResolvedApp` is a proof token: constructing one is only possible through
//! [`normalize`], so daemon code can require it and skip re-validation.

use core::fmt;

use std::path::Path;

use std::collections::BTreeSet;

use globset::Glob;

use crate::config::{
    AppConfig, CronParseError, CronSchedule, KillSignal, ProbeConfig, ProbeTarget,
};
use crate::values::UpDuration;

/// Shortest `interval` a `liveness_probe` may name.
///
/// The daemon's liveness loop floors whatever it is handed at this same
/// value, so a smaller number would be silently honoured as this one with
/// no warning.
///
/// One second is a floor no legitimate configuration wants to be under: for
/// [`ProbeKind::Exec`](crate::config::ProbeKind::Exec) a shorter interval is
/// that many process spawns per second, per sheep, for as long as it runs.
const MIN_LIVENESS_INTERVAL: UpDuration = UpDuration::from_millis(1_000);

/// Shortest `interval` a `readiness_probe` may name.
///
/// A whole second lower than [`MIN_LIVENESS_INTERVAL`]: the readiness wait
/// honours its `interval` exactly as written, bounded by `listen_timeout`,
/// so only zero needs rejecting. A fast app polling every 20ms to leave
/// `starting` sooner must not lose that.
const MIN_READINESS_INTERVAL: UpDuration = UpDuration::from_millis(1);

/// Longest `action_timeout` an app may name.
///
/// The daemon clamps every RPC deadline to `MAX_DEADLINE_MS` (60s, in
/// shep-daemon's `rpc` module), so a value at or above that line could
/// never be honoured by any caller. Set 2s under the clamp so the daemon
/// still has room to build the `TimedOut` row and send it back after the
/// wait gives up.
const MAX_ACTION_TIMEOUT: UpDuration = UpDuration::from_millis(58_000);

/// A validated app config: only obtainable via [`normalize`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedApp {
    config: AppConfig,
}

impl ResolvedApp {
    /// Borrow the validated configuration
    #[must_use]
    pub fn config(&self) -> &AppConfig {
        &self.config
    }

    /// Unwrap the validated configuration (consumes the proof token)
    #[must_use]
    pub fn into_config(self) -> AppConfig {
        self.config
    }
}

/// Expands a leading `~/` against `home`, and refuses `~user/`.
///
/// `~/` only: `~user/...` needs a passwd lookup whose answer depends on who
/// the daemon runs as, and `$VAR` is never expanded here or anywhere. A
/// value with no leading `~` is returned unchanged. Thin wrapper over
/// [`expand_home_tilde`], attaching the sheep name and field
/// [`NormalizeError`] carries; `shep-cli`'s `shep adopt` calls
/// [`expand_home_tilde`] directly instead.
///
/// # Errors
/// - [`NormalizeError::TildeUser`] if the path names another user's home.
/// - [`NormalizeError::NoHomeForTilde`] if `~/` is used and `home` is `None`.
fn expand_tilde(
    value: &str,
    home: Option<&Path>,
    name: &str,
    field: &'static str,
) -> Result<String, NormalizeError> {
    expand_home_tilde(value, home).map_err(|err| match err {
        TildeError::OtherUser => NormalizeError::TildeUser {
            name: name.to_string(),
            field,
            value: value.to_string(),
        },
        TildeError::NoHome => NormalizeError::NoHomeForTilde {
            name: name.to_string(),
            field,
        },
    })
}

/// Why [`expand_home_tilde`] refused a value, with no per-field context
/// attached, for a caller that has none to give.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TildeError {
    /// The value names another user's home (`~user/...`). Refused rather
    /// than resolved: answering it means a passwd lookup, and under a
    /// systemd unit the answer depends on who the process runs as rather
    /// than on who wrote the value.
    OtherUser,
    /// The value begins `~/` and no home directory could be determined.
    NoHome,
}

impl fmt::Display for TildeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OtherUser => write!(
                f,
                "shep expands only `~/` (your own home); another user's home needs a \
                 passwd lookup whose answer depends on who the process runs as"
            ),
            Self::NoHome => write!(f, "begins with `~/` but no home directory could be found"),
        }
    }
}

impl core::error::Error for TildeError {}

/// Expands a leading `~/` in `value` against `home`
///
/// Accepts `~` alone or `~/...`. `~user/` is refused, since resolving it
/// takes a passwd lookup whose answer depends on who the process runs as.
/// `$VAR` is never expanded. A value with no leading `~` comes back
/// unchanged.
///
/// # Errors
/// - [`TildeError::OtherUser`] if the value names another user's home.
/// - [`TildeError::NoHome`] if `~/` is used and `home` is `None`.
pub fn expand_home_tilde(value: &str, home: Option<&Path>) -> Result<String, TildeError> {
    let Some(rest) = value.strip_prefix('~') else {
        return Ok(value.to_string());
    };
    // `~` alone, or `~/...`. Anything else after the tilde names a user.
    if !(rest.is_empty() || rest.starts_with('/')) {
        return Err(TildeError::OtherUser);
    }
    let Some(home) = home else {
        return Err(TildeError::NoHome);
    };
    // `join` would discard `home` for a rest that still looks absolute, so
    // the separator is trimmed and the two halves are concatenated instead.
    let joined = home.join(rest.trim_start_matches('/'));
    Ok(joined.to_string_lossy().into_owned())
}

/// Every field of an [`AppConfig`] that carries a filesystem path.
///
/// Named once, and walked by [`expand_paths`] and by its own test, so a
/// fifth path field added later fails that test until it is handled.
/// Expanding `~/` in some path fields and not others would be worse than
/// expanding in none: it teaches that tildes work and then fails somewhere
/// the operator has no reason to suspect.
#[cfg(test)]
const PATH_FIELDS: &[&str] = &["script", "cwd", "out_file", "err_file"];

/// Expands `~/` in every path field of `app`, in place.
///
/// # Errors
/// Whatever [`expand_tilde`] refuses, named with the field that carried it.
fn expand_paths(app: &mut AppConfig, home: Option<&Path>) -> Result<(), NormalizeError> {
    let name = app.name.clone();
    app.script = expand_tilde(&app.script, home, &name, "script")?;
    for (field, slot) in [
        ("cwd", &mut app.cwd),
        ("out_file", &mut app.out_file),
        ("err_file", &mut app.err_file),
    ] {
        if let Some(value) = slot {
            *slot = Some(expand_tilde(value, home, &name, field)?);
        }
    }
    Ok(())
}

/// Validates one app config
///
/// # Errors
///
/// - [`NormalizeError::MissingName`]: `name` is empty.
/// - [`NormalizeError::InvalidName`]: `name` contains a path separator or a colon, or is `.`/`..`.
/// - [`NormalizeError::ReservedEnvVar`]: `env` sets `SHEP_INSTANCE` or `SHEP_NAME`, which shep injects itself.
/// - [`NormalizeError::IncrementVarRemoved`]: `increment_var` is set; removed in favour of `{{instance}}` templating.
/// - [`NormalizeError::MissingScript`]: `script` is empty.
/// - [`NormalizeError::ZeroInstances`]: `instances == 0`.
/// - [`NormalizeError::InvalidCron`]: `cron_restart` is not valid in croner's dialect.
/// - [`NormalizeError::InvalidTimezone`]: `cron_timezone` is not a name in the IANA time-zone database.
/// - [`NormalizeError::InvalidProbe`]: a `readiness_probe`/`liveness_probe` target [`ProbeTarget::parse`] rejects.
/// - [`NormalizeError::ZeroFailureThreshold`]: a probe's `failure_threshold` is explicitly `0`.
/// - [`NormalizeError::IntervalBelowMinimum`]: a probe's `interval` is under the floor its own loop honours.
/// - [`NormalizeError::ZeroMaxMemory`]: `max_memory` is `0`.
/// - [`NormalizeError::ActionTimeoutTooLong`]: `action_timeout` is at or above the ceiling no RPC caller could wait past.
/// - [`NormalizeError::InvalidKillSignal`]: `kill_signal` names a signal the daemon's stop ladder cannot send.
/// - [`NormalizeError::WatchWithoutCwd`]: `watch` is `true` with no `cwd` set.
/// - [`NormalizeError::ZeroWatchDelay`]: `watch_delay` is `0`.
/// - [`NormalizeError::InvalidWatchGlob`]: a `watch_options` or `ignore_watch` pattern globset will not compile.
/// - [`NormalizeError::BadTemplate`]: an `env`/`args`/log-path value carries an undefined or unclosed `{{...}}` token.
/// - [`NormalizeError::SharedLogPath`]: `out_file` or `err_file` renders to the same path for two instances.
/// - [`NormalizeError::TildeUser`]: a path field names another user's `~user` home.
/// - [`NormalizeError::NoHomeForTilde`]: a path field expands `~/` but no home directory could be found.
/// - [`NormalizeError::SelfDependency`]: an app names itself in `depends_on`.
/// - [`NormalizeError::InstanceDependency`]: a `depends_on` entry is written `name:slot`.
pub fn normalize(app: AppConfig) -> Result<ResolvedApp, NormalizeError> {
    normalize_with_home(app, std::env::home_dir().as_deref())
}

/// [`normalize`], with the home directory supplied rather than read.
///
/// A parameter so the `~/` expansion above is testable without mutating the
/// process environment, which is racy under a parallel `cargo test`. This is
/// also the seam that matters for correctness rather than only for tests:
/// the daemon may run as a different user than the CLI, so `~` has to be
/// resolved where the config is normalised, not where it is executed.
///
/// # Errors
/// The same set [`normalize`] documents.
pub fn normalize_with_home(
    mut app: AppConfig,
    home: Option<&Path>,
) -> Result<ResolvedApp, NormalizeError> {
    if app.name.is_empty() {
        return Err(NormalizeError::MissingName);
    }
    if app.name.contains(['/', '\\', ':']) || app.name == "." || app.name == ".." {
        return Err(NormalizeError::InvalidName(app.name));
    }
    for var in ["SHEP_INSTANCE", "SHEP_NAME"] {
        if app.env.contains_key(var) {
            return Err(NormalizeError::ReservedEnvVar {
                name: app.name.clone(),
                var,
            });
        }
    }
    if let Some(var) = app.increment_var.take() {
        return Err(NormalizeError::IncrementVarRemoved {
            name: app.name.clone(),
            var,
        });
    }
    for (key, value) in &app.env {
        validate_template(&app.name, &format!("env.{key}"), value)?;
    }
    for (index, value) in app.args.iter().enumerate() {
        validate_template(&app.name, &format!("args[{index}]"), value)?;
    }
    for (field, value) in [("out_file", &app.out_file), ("err_file", &app.err_file)] {
        if let Some(value) = value {
            validate_template(&app.name, field, value)?;
        }
    }
    if app.script.is_empty() {
        return Err(NormalizeError::MissingScript);
    }
    // After the emptiness checks, so a missing script is reported as missing
    // rather than as a path problem, and before every check below that reads
    // a path.
    expand_paths(&mut app, home)?;
    if app.instances == 0 {
        return Err(NormalizeError::ZeroInstances);
    }
    // After the template validation above, so a malformed `out_file`/`err_file`
    // is reported as a bad template rather than as a shared path.
    if app.instances > 1 && !app.merge_logs {
        for (field, path) in [("out_file", &app.out_file), ("err_file", &app.err_file)] {
            // Rendered rather than searched for a substring: an escaped
            // `{{{{instance}}}}` contains the token's spelling but renders to
            // one literal path for every instance, which is exactly the
            // collision this refuses. Two slots that render alike collide.
            if let Some(path) = path
                && crate::config::template::render(path, &app.name, 0)
                    == crate::config::template::render(path, &app.name, 1)
            {
                return Err(NormalizeError::SharedLogPath {
                    name: app.name.clone(),
                    field,
                });
            }
        }
    }
    if let Some(pattern) = &app.cron_restart {
        CronSchedule::parse(pattern, app.cron_timezone.as_deref()).map_err(|e| match e {
            CronParseError::Pattern { pattern, reason } => {
                NormalizeError::InvalidCron { pattern, reason }
            }
            CronParseError::Timezone { name } => NormalizeError::InvalidTimezone { name },
        })?;
    } else if let Some(tz_name) = &app.cron_timezone {
        // A Flockfile can carry `cron_timezone` with no `cron_restart` to
        // pair it with, still a typo the user wants to hear about.
        crate::config::cron::parse_timezone_name(tz_name).ok_or_else(|| {
            NormalizeError::InvalidTimezone {
                name: tz_name.clone(),
            }
        })?;
    }
    validate_probe(
        app.readiness_probe.as_ref(),
        "readiness_probe",
        MIN_READINESS_INTERVAL,
    )?;
    validate_probe(
        app.liveness_probe.as_ref(),
        "liveness_probe",
        MIN_LIVENESS_INTERVAL,
    )?;
    if app.max_memory.is_some_and(|limit| limit.bytes() == 0) {
        // A ceiling every live process is already over: the enforcer would
        // report a breach on every reading, and the automatic restart that
        // follows resets the restart budget rather than spending it, so
        // `max_restarts` can never end the loop.
        return Err(NormalizeError::ZeroMaxMemory { name: app.name });
    }
    if let Some(name) = &app.kill_signal
        && KillSignal::parse(name).is_none()
    {
        // Rejected rather than clamped: a typo silently falling back to
        // SIGTERM would cost every stop and reload for the life of the
        // process, with no evidence but a detached daemon's log.
        return Err(NormalizeError::InvalidKillSignal {
            name: app.name,
            value: name.clone(),
        });
    }
    if app.action_timeout > MAX_ACTION_TIMEOUT {
        // Rejected rather than clamped: every value above the ceiling is
        // equally unreachable by any caller, so there is no honest lowered
        // value to silently fall back to.
        return Err(NormalizeError::ActionTimeoutTooLong {
            name: app.name,
            value: app.action_timeout,
            max: MAX_ACTION_TIMEOUT,
        });
    }
    if app.watch && app.cwd.is_none() {
        // `watch` asked for a feature the daemon has no directory to arm:
        // there is no cwd in the Flockfile, and defaulting to the daemon's
        // own cwd risks watching the whole filesystem under a systemd unit
        // with no `WorkingDirectory=`.
        return Err(NormalizeError::WatchWithoutCwd { name: app.name });
    }
    if app.watch_delay == Some(UpDuration::from_millis(0)) {
        // notify's debouncer derives its own poll tick as `watch_delay / 4`
        // on a dedicated OS thread, so a zero turns that thread into
        // `loop { sleep(0); lock(); }`, a CPU-spinning busy loop.
        return Err(NormalizeError::ZeroWatchDelay { name: app.name });
    }
    // Both lists are checked whether or not `watch` is on, so a typo'd
    // pattern is named now rather than the day `watch` flips on and nothing
    // happens.
    validate_watch_globs(&app.name, "watch_options", &app.watch_options)?;
    validate_watch_globs(&app.name, "ignore_watch", &app.ignore_watch)?;
    let mut seen = BTreeSet::new();
    let mut deduped = Vec::with_capacity(app.depends_on.len());
    for target in &app.depends_on {
        if target == &app.name {
            return Err(NormalizeError::SelfDependency(app.name.clone()));
        }
        if target.contains(':') {
            return Err(NormalizeError::InstanceDependency {
                sheep: app.name.clone(),
                target: target.clone(),
            });
        }
        if seen.insert(target.clone()) {
            deduped.push(target.clone());
        }
    }
    app.depends_on = deduped;
    Ok(ResolvedApp { config: app })
}

/// Validates one `{{instance}}`/`{{name}}` template value, naming `field` in
/// any rejection so the user knows which entry to edit.
///
/// # Errors
/// [`NormalizeError::BadTemplate`] if `value` carries a `{{...}}` this
/// grammar does not define, or a `{{` this value never closes. Both of
/// [`crate::config::template::validate`]'s own rejections map here, so the
/// two are told apart by the rendered `reason` the variant carries rather
/// than by the variant.
fn validate_template(name: &str, field: &str, value: &str) -> Result<(), NormalizeError> {
    crate::config::template::validate(value).map_err(|reason| NormalizeError::BadTemplate {
        name: name.to_string(),
        field: field.to_string(),
        reason: reason.to_string(),
    })
}

/// Validates one of an app's two watch glob lists, rejecting any pattern
/// globset will not compile. `field` is the Flockfile field name
/// (`"watch_options"` or `"ignore_watch"`), carried into any error so the
/// user knows which list to edit. The compiled globs are discarded: this
/// function's job is rejection, and the daemon builds its own watch filter
/// when it arms the watch.
fn validate_watch_globs(
    name: &str,
    field: &'static str,
    patterns: &[String],
) -> Result<(), NormalizeError> {
    for pattern in patterns {
        Glob::new(pattern).map_err(|err| NormalizeError::InvalidWatchGlob {
            name: name.to_string(),
            field,
            pattern: pattern.clone(),
            reason: err.to_string(),
        })?;
    }
    Ok(())
}

/// Validates one probe's target, `failure_threshold` and `interval`, if the
/// probe is configured. `probe` is the Flockfile field name
/// (`"readiness_probe"` or `"liveness_probe"`), carried into any error so
/// the user knows which field to edit; `min_interval` is the floor that
/// probe's own loop in the daemon honours. Its own parsed [`ProbeTarget`] is
/// discarded: the daemon re-parses when it arms the probe.
fn validate_probe(
    probe: Option<&ProbeConfig>,
    name: &'static str,
    min_interval: UpDuration,
) -> Result<(), NormalizeError> {
    let Some(probe) = probe else {
        return Ok(());
    };
    ProbeTarget::parse(probe).map_err(|reason| NormalizeError::InvalidProbe {
        probe: name,
        reason: reason.to_string(),
    })?;
    if probe.failure_threshold == 0 {
        // Unhealthy before the first probe ever runs would make the liveness
        // loop restart the sheep immediately and forever.
        return Err(NormalizeError::ZeroFailureThreshold { probe: name });
    }
    if probe.interval < min_interval {
        // A zero interval would spin either probe loop as fast as
        // `ProbeKind::Exec` can spawn processes. A small but nonzero
        // liveness interval is refused too: `spawn_liveness_task` rounds
        // it up silently, leaving nothing to report the discrepancy.
        return Err(NormalizeError::IntervalBelowMinimum {
            probe: name,
            value: probe.interval,
            min: min_interval,
        });
    }
    Ok(())
}

/// Validates a whole flock, rejecting duplicate sheep names
///
/// # Errors
///
/// Everything [`normalize`] returns, plus
/// [`NormalizeError::DuplicateName`]: two apps share a `name`.
/// [`NormalizeError::DependencyCycle`]: two apps in the document depend on each other.
pub fn normalize_all(apps: Vec<AppConfig>) -> Result<Vec<ResolvedApp>, NormalizeError> {
    let mut seen = BTreeSet::new();
    let resolved: Vec<ResolvedApp> = apps
        .into_iter()
        .map(|app| {
            if !seen.insert(app.name.clone()) {
                return Err(NormalizeError::DuplicateName(app.name));
            }
            normalize(app)
        })
        .collect::<Result<_, _>>()?;
    // Document-local only: a name this document does not hold is left to the
    // daemon, which is the only place that knows the whole flock.
    let nodes: Vec<crate::config::graph::BootNode> = resolved
        .iter()
        .map(|app| crate::config::graph::BootNode {
            name: app.config().name.clone(),
            depends_on: app.config().depends_on.clone(),
            kind: crate::config::graph::NodeKind::Sheep,
        })
        .collect();
    if let Some(cycle) = crate::config::graph::plan(&nodes).cycles.into_iter().next() {
        return Err(NormalizeError::DependencyCycle(cycle));
    }
    Ok(resolved)
}

/// Error type returned from [`normalize`] and [`normalize_all`]
///
/// `#[non_exhaustive]`: every config surface this crate learns to validate
/// brings its own rejection reasons with it.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NormalizeError {
    /// `name` is empty
    MissingName,
    /// `name` contains `/`, `\` or `:`, or is `.`/`..`. A path separator
    /// would escape the shep home, since the name becomes a filesystem path
    /// stem; a colon is the `name:slot` separator, and is also illegal in a
    /// Windows filename, which a sheep name becomes part of. Carries the
    /// name.
    InvalidName(String),
    /// An app's `env` sets a variable shep injects itself. Carries the sheep
    /// name and the variable, so the error names the entry to edit.
    ReservedEnvVar {
        /// The sheep name
        name: String,
        /// The variable the app tried to set
        var: &'static str,
    },
    /// `increment_var` was removed in favour of `{{instance}}` templating.
    /// Carries the variable the app named, so the error can show the exact
    /// line to write instead.
    IncrementVarRemoved {
        /// The sheep name
        name: String,
        /// The variable the app asked for
        var: String,
    },
    /// `script` is empty
    MissingScript,
    /// `instances` is zero
    ZeroInstances,
    /// `cron_restart` is not valid in croner's dialect. Carries the pattern
    /// and the rejection reason.
    InvalidCron {
        /// The pattern as the user wrote it
        pattern: String,
        /// Why it was rejected
        reason: String,
    },
    /// `cron_timezone` is not a name in the IANA time-zone database
    InvalidTimezone {
        /// The value as the user wrote it
        name: String,
    },
    /// Two apps in one flock share this name
    DuplicateName(String),
    /// Two or more apps in one document depend on each other. Carries the
    /// cycle as a path, so the refusal names it rather than only reporting
    /// that one exists.
    DependencyCycle(Vec<String>),
    /// A `readiness_probe` or `liveness_probe` target is malformed. Carries
    /// which probe and the rendered reason.
    InvalidProbe {
        /// `"readiness_probe"` or `"liveness_probe"`, so the error names the
        /// line the user has to edit.
        probe: &'static str,
        /// [`ProbeTarget::parse`]'s rendered rejection reason.
        reason: String,
    },
    /// A `readiness_probe` or `liveness_probe` has `failure_threshold == 0`.
    ZeroFailureThreshold {
        /// `"readiness_probe"` or `"liveness_probe"`, so the error names the
        /// line the user has to edit.
        probe: &'static str,
    },
    /// A `readiness_probe` or `liveness_probe` has an `interval` under the
    /// floor its own loop in the daemon honours. At `0` that would spin the
    /// loop as fast as the runtime allows; a `liveness_probe` under a full
    /// second would instead be silently polled at that second.
    IntervalBelowMinimum {
        /// `"readiness_probe"` or `"liveness_probe"`, so the error names the
        /// line the user has to edit.
        probe: &'static str,
        /// The value as the user wrote it.
        value: UpDuration,
        /// The floor it failed.
        min: UpDuration,
    },
    /// `max_memory` is `0`, a ceiling every live process is already over, so
    /// the enforcer would restart the sheep on every poll forever. Carries
    /// the app name.
    ZeroMaxMemory {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
    },
    /// `action_timeout` is at or above `normalize`'s own ceiling: a wait no
    /// RPC caller could ever be given enough deadline to outlast, since the
    /// daemon clamps every deadline a caller can ask for. Carries the app
    /// name, the value as written, and the ceiling it failed.
    ActionTimeoutTooLong {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
        /// The value as the user wrote it.
        value: UpDuration,
        /// The ceiling it failed.
        max: UpDuration,
    },
    /// `kill_signal` names a signal the daemon's stop ladder cannot send.
    /// Carries the app name and the value as written.
    InvalidKillSignal {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
        /// The value as the user wrote it.
        value: String,
    },
    /// `watch` is enabled but the app sets no `cwd`, so there is no
    /// directory to watch. Carries the app name.
    WatchWithoutCwd {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
    },
    /// A path begins `~user/`, naming another user's home.
    ///
    /// Refused rather than resolved: answering it means a passwd lookup, and
    /// under a systemd unit the answer is not obviously the one anyone meant.
    /// `~/` is supported; this is not.
    TildeUser {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
        /// Which field carried it.
        field: &'static str,
        /// The path as written.
        value: String,
    },
    /// A path begins `~/` and no home directory could be determined.
    NoHomeForTilde {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
        /// Which field carried it.
        field: &'static str,
    },
    /// `watch_delay` is `0`, which would spin the debouncer's own OS thread.
    /// Carries the app name.
    ZeroWatchDelay {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
    },
    /// A `watch_options` or `ignore_watch` pattern is one globset will not
    /// compile, so the watch it describes could never be armed.
    InvalidWatchGlob {
        /// The sheep name, so the error names which Flockfile entry to edit.
        name: String,
        /// `"watch_options"` or `"ignore_watch"`, so the error names which
        /// of the two lists to edit.
        field: &'static str,
        /// The pattern as the user wrote it.
        pattern: String,
        /// globset's own rendered reason.
        reason: String,
    },
    /// A value carries a `{{...}}` that is not a template token, or a `{{`
    /// it never closes. Carries the sheep name, which field held it, and the
    /// rejection rendered.
    BadTemplate {
        /// The sheep name
        name: String,
        /// Which field, for example `env.WORKER` or `args[1]`
        field: String,
        /// The template grammar's own error, rendered, so this
        /// variant does not have to restate the grammar's own copy
        reason: String,
    },
    /// An explicit log path renders to the same string for two different
    /// slots, the app runs more than one instance, and `merge_logs` is off,
    /// so every instance would write to one file without having asked to.
    /// A path with no `{{instance}}` is the ordinary case; a `{{name}}`-only
    /// path and an escaped `{{{{instance}}}}` collide for the same reason.
    SharedLogPath {
        /// The sheep name
        name: String,
        /// `out_file` or `err_file`
        field: &'static str,
    },
    /// An app names itself in `depends_on`. Carries the sheep name. A
    /// one-node cycle, caught here rather than in the graph because it is
    /// visible in a single `AppConfig`.
    SelfDependency(String),
    /// A `depends_on` entry names one instance rather than an app. Carries
    /// the sheep and the offending target, so the refusal can name both.
    InstanceDependency {
        /// The sheep whose list holds the entry
        sheep: String,
        /// The entry as written
        target: String,
    },
}

impl fmt::Display for NormalizeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingName => f.write_str("app config is missing a name"),
            Self::InvalidName(n) => {
                write!(
                    f,
                    "sheep name `{n}` may not contain a path separator or a colon, or be `.` or `..`; use `-` in place of a colon"
                )
            }
            Self::ReservedEnvVar { name, var } => write!(
                f,
                "sheep `{name}` sets `{var}` in env, but shep injects it: use a different name, or `{{{{instance}}}}` in your own variable"
            ),
            Self::IncrementVarRemoved { name, var } => write!(
                f,
                "sheep `{name}` sets `increment_var`, which was removed: write `{var} = \"{{{{instance}}}}\"` under `[app.env]` instead"
            ),
            Self::MissingScript => f.write_str("app config is missing a script"),
            Self::ZeroInstances => f.write_str("instances must be at least 1"),
            Self::InvalidCron { pattern, reason } => {
                write!(f, "invalid cron_restart pattern `{pattern}`: {reason}")
            }
            Self::InvalidTimezone { name } => {
                write!(f, "`{name}` is not a recognized IANA timezone")
            }
            Self::DuplicateName(n) => write!(f, "duplicate sheep name `{n}`"),
            Self::DependencyCycle(cycle) => write!(
                f,
                "dependency cycle: {}",
                crate::config::graph::render_cycle(cycle)
            ),
            Self::InvalidProbe { probe, reason } => write!(f, "{probe}: {reason}"),
            Self::ZeroFailureThreshold { probe } => {
                write!(f, "{probe}.failure_threshold must be at least 1")
            }
            Self::IntervalBelowMinimum { probe, value, min } => {
                write!(f, "{probe}.interval is `{value}`: must be at least {min}")
            }
            Self::ZeroMaxMemory { name } => {
                write!(
                    f,
                    "sheep `{name}` has max_memory = 0, a limit nothing can stay under"
                )
            }
            Self::ActionTimeoutTooLong { name, value, max } => {
                write!(
                    f,
                    "sheep `{name}` has action_timeout = {value}: must be at most {max}, \
                     the longest wait any caller's deadline could ever cover"
                )
            }
            Self::InvalidKillSignal { name, value } => {
                write!(
                    f,
                    "`{name}`: kill_signal `{value}` is not one shep can send (accepted: {})",
                    KillSignal::ACCEPTED.join(", ")
                )
            }
            Self::TildeUser { name, field, value } => write!(
                f,
                "`{name}`: {field} is `{value}`, and shep expands only `~/` (your own home). \
                 Another user's home needs a passwd lookup whose answer depends on who the \
                 daemon runs as, so write the path out in full instead."
            ),
            Self::NoHomeForTilde { name, field } => write!(
                f,
                "`{name}`: {field} begins with `~/` but no home directory could be found. \
                 Set $HOME, or write the path out in full."
            ),
            Self::WatchWithoutCwd { name } => {
                write!(f, "sheep `{name}` has watch = true but no cwd to watch")
            }
            Self::ZeroWatchDelay { name } => {
                write!(
                    f,
                    "sheep `{name}` has watch_delay = 0: must be greater than 0"
                )
            }
            Self::InvalidWatchGlob {
                name,
                field,
                pattern,
                reason,
            } => write!(
                f,
                "sheep `{name}` has an invalid {field} pattern `{pattern}`: {reason}"
            ),
            Self::BadTemplate {
                name,
                field,
                reason,
            } => write!(f, "sheep `{name}`, {field}: {reason}"),
            Self::SharedLogPath { name, field } => write!(
                f,
                "sheep `{name}` runs several instances and sets `{field}` to one path: put `{{{{instance}}}}` in it, or set `merge_logs = true` to share it on purpose"
            ),
            Self::SelfDependency(n) => {
                write!(f, "`{n}` names itself in depends_on")
            }
            Self::InstanceDependency { sheep, target } => {
                let app = target.split(':').next().unwrap_or(target);
                write!(
                    f,
                    "`{sheep}` depends on `{target}`, which names one instance. \
                     Depend on `{app}` instead: a dependency waits for every \
                     instance of an app"
                )
            }
        }
    }
}

impl core::error::Error for NormalizeError {}

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

    /// All four path fields expand `~/`, and expanding some but not others
    /// would be worse than expanding none: it teaches that tildes work and
    /// then fails where the operator has no reason to suspect it.
    #[test]
    fn every_path_field_expands_a_leading_tilde() {
        let home = Path::new("/home/ada");
        let mut app = AppConfig::minimal("web", "~/app/server.js");
        app.cwd = Some("~/app".to_string());
        app.out_file = Some("~/logs/out.log".to_string());
        app.err_file = Some("~/logs/err.log".to_string());

        let resolved = normalize_with_home(app, Some(home)).expect("all four expand");
        let c = resolved.config();
        // Expectations are built with `join` rather than written as literals:
        // the separator is `/` here and `\` on Windows, and hardcoding one
        // turned CI's three Windows legs red when this test first landed.
        let expect = |rest: &str| home.join(rest).to_string_lossy().into_owned();
        assert_eq!(c.script, expect("app/server.js"));
        assert_eq!(c.cwd.as_deref(), Some(expect("app").as_str()));
        assert_eq!(c.out_file.as_deref(), Some(expect("logs/out.log").as_str()));
        assert_eq!(c.err_file.as_deref(), Some(expect("logs/err.log").as_str()));
    }

    /// The anti-drift half. A fifth path field added to `AppConfig` fails
    /// here until `expand_paths` handles it, which is the only thing keeping
    /// the "all four or none" rule true over time.
    #[test]
    fn the_path_field_list_matches_what_expand_paths_walks() {
        let home = Path::new("/home/ada");
        let mut app = AppConfig::minimal("web", "~/s");
        app.cwd = Some("~/c".to_string());
        app.out_file = Some("~/o".to_string());
        app.err_file = Some("~/e".to_string());

        let resolved = normalize_with_home(app, Some(home)).expect("expands");
        let c = resolved.config();
        let expanded = [
            ("script", Some(c.script.as_str())),
            ("cwd", c.cwd.as_deref()),
            ("out_file", c.out_file.as_deref()),
            ("err_file", c.err_file.as_deref()),
        ];
        assert_eq!(
            expanded.len(),
            PATH_FIELDS.len(),
            "PATH_FIELDS and this test must name the same set"
        );
        for (field, value) in expanded {
            assert!(
                PATH_FIELDS.contains(&field),
                "`{field}` is not in PATH_FIELDS"
            );
            assert!(
                value.is_some_and(|v| v.starts_with("/home/ada")),
                "`{field}` was not expanded: {value:?}"
            );
        }
    }

    /// A path with no tilde is untouched, so this is a no-op for every
    /// absolute and relative path anyone already has.
    #[test]
    fn a_path_without_a_tilde_is_left_exactly_as_written() {
        let app = AppConfig::minimal("web", "./server.js");
        let resolved =
            normalize_with_home(app, Some(Path::new("/home/ada"))).expect("no tilde, no change");
        assert_eq!(resolved.config().script, "./server.js");
    }

    /// `~user/` needs a passwd lookup whose answer depends on who the daemon
    /// runs as, so it is refused rather than guessed at.
    #[test]
    fn another_users_home_is_refused_rather_than_resolved() {
        let app = AppConfig::minimal("web", "~deploy/app/server.js");
        let err = normalize_with_home(app, Some(Path::new("/home/ada")))
            .expect_err("~user/ must not resolve");
        assert!(
            matches!(err, NormalizeError::TildeUser { field, .. } if field == "script"),
            "the refusal names the field: {err:?}"
        );
        let rendered = err.to_string();
        assert!(
            rendered.contains("~/"),
            "and says what IS supported: {rendered}"
        );
        assert!(
            !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
            "no em or en dash in copy a user reads: {rendered}"
        );
    }

    /// `$VAR` is not expanded, here or anywhere. A config file that expands
    /// variables has to answer whose environment it means.
    #[test]
    fn a_dollar_variable_is_not_expanded() {
        let app = AppConfig::minimal("web", "$HOME/server.js");
        let resolved = normalize_with_home(app, Some(Path::new("/home/ada"))).expect("left alone");
        assert_eq!(resolved.config().script, "$HOME/server.js");
    }

    /// `~/` with no home to expand against is an error naming the field
    /// rather than a path containing a literal tilde.
    #[test]
    fn a_tilde_with_no_home_is_an_error_not_a_literal_path() {
        let app = AppConfig::minimal("web", "~/server.js");
        let err = normalize_with_home(app, None).expect_err("nothing to expand against");
        assert!(
            matches!(err, NormalizeError::NoHomeForTilde { .. }),
            "{err:?}"
        );
    }

    /// Pins [`expand_home_tilde`]'s own contract, apart from
    /// [`expand_tilde`]'s wrapping into a [`NormalizeError`]: `shep-cli`'s
    /// `shep adopt` calls it directly, with no app name or field to attach.
    #[test]
    fn expand_home_tilde_covers_its_four_documented_cases() {
        let home = Path::new("/home/ada");
        assert_eq!(
            expand_home_tilde("~/bin/dog", Some(home)).unwrap(),
            home.join("bin/dog").to_string_lossy()
        );
        assert_eq!(
            expand_home_tilde("/opt/bin/dog", Some(home)).unwrap(),
            "/opt/bin/dog",
            "a value with no leading ~ is returned unchanged"
        );
        assert_eq!(
            expand_home_tilde("~/bin/dog", None).unwrap_err(),
            TildeError::NoHome
        );
        assert_eq!(
            expand_home_tilde("~deploy/bin/dog", Some(home)).unwrap_err(),
            TildeError::OtherUser
        );
    }

    /// `reuse_port` loads because reload's overlap mode is chosen from it:
    /// refusing it would deny an operator the only way to ask for an
    /// overlapping reload.
    #[test]
    fn reuse_port_loads_now_that_reload_reads_it() {
        let mut app = AppConfig::minimal("web", "./server");
        app.reuse_port = true;

        let resolved = normalize(app).expect("reuse_port is implemented");
        assert!(resolved.config().reuse_port);
    }

    /// The default is off, so every Flockfile that does not mention it keeps
    /// loading.
    #[test]
    fn an_app_that_never_mentions_reuse_port_still_normalizes() {
        let resolved = normalize(AppConfig::minimal("web", "./server"))
            .expect("the common case must be untouched");
        assert!(!resolved.config().reuse_port);
    }
    use crate::config::AppConfig;

    #[test]
    fn a_colon_in_a_name_is_refused_because_it_is_the_instance_separator() {
        let err = normalize(AppConfig::minimal("web:2", "./srv")).unwrap_err();
        assert_eq!(err, NormalizeError::InvalidName("web:2".to_string()));

        let rendered = err.to_string();
        assert!(rendered.contains(':'), "says which character: {rendered}");
        // Spec D3 requires the error to name the character and suggest `-`.
        assert!(
            rendered.contains("`-`"),
            "suggests the stand-in: {rendered}"
        );
        assert!(
            !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
            "no em or en dash in copy a user reads: {rendered}"
        );

        assert!(normalize(AppConfig::minimal("web-2", "./srv")).is_ok());
    }

    #[test]
    fn increment_var_is_refused_and_says_what_replaced_it() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.increment_var = Some("WORKER_ID".to_string());
        let err = normalize(app).unwrap_err();
        let rendered = err.to_string();
        assert!(rendered.contains("increment_var"), "{rendered}");
        assert!(
            rendered.contains("WORKER_ID"),
            "keeps their name: {rendered}"
        );
        assert!(rendered.contains("{{instance}}"), "and the fix: {rendered}");
        assert!(
            !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
            "no em or en dash in copy a user reads: {rendered}"
        );
    }

    #[test]
    fn the_reserved_env_vars_are_refused_rather_than_overwritten() {
        for var in ["SHEP_INSTANCE", "SHEP_NAME"] {
            let mut app = AppConfig::minimal("web", "./srv");
            app.env.insert(var.to_string(), "mine".to_string());
            let err = normalize(app).unwrap_err();
            let rendered = err.to_string();
            assert!(rendered.contains(var), "names the variable: {rendered}");
            assert!(
                !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
                "no em or en dash in copy a user reads: {rendered}"
            );
        }
    }

    #[test]
    fn valid_minimal_config_normalizes() {
        let resolved = normalize(AppConfig::minimal("web", "./srv")).unwrap();
        assert_eq!(resolved.config().name, "web");
    }

    #[test]
    fn names_that_reach_the_filesystem_are_rejected() {
        // A name becomes a log/pid file stem via Path::join; a slash-prefixed
        // or dotdot name would escape $SHEP_HOME. Reject at the config boundary.
        for bad in ["/etc/passwd", "..", ".", "a/b", "a\\b"] {
            assert_eq!(
                normalize(AppConfig::minimal(bad, "./srv")).unwrap_err(),
                NormalizeError::InvalidName(bad.to_string())
            );
        }
        assert!(normalize(AppConfig::minimal("web-1", "./srv")).is_ok());
    }

    #[test]
    fn missing_name_and_script_are_distinct_errors() {
        assert_eq!(
            normalize(AppConfig::minimal("", "./srv")).unwrap_err(),
            NormalizeError::MissingName
        );
        assert_eq!(
            normalize(AppConfig::minimal("web", "")).unwrap_err(),
            NormalizeError::MissingScript
        );
    }

    #[test]
    fn zero_instances_rejected() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.instances = 0;
        assert_eq!(normalize(app).unwrap_err(), NormalizeError::ZeroInstances);
    }

    #[test]
    fn bad_cron_pattern_rejected_with_pattern_and_reason_carried_through() {
        // fails if the reason is not carried through from croner.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_restart = Some("not a cron".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidCron { pattern, reason } => {
                assert_eq!(pattern, "not a cron");
                assert!(!reason.is_empty());
            }
            other => panic!("expected InvalidCron, got {other:?}"),
        }
    }

    #[test]
    fn five_tokens_of_garbage_cron_pattern_rejected() {
        // fails if the validator only counts whitespace-separated tokens
        // instead of checking each field's range: five numeric-looking
        // tokens, all out of range.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_restart = Some("99 99 99 99 99".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidCron { pattern, .. } => {
                assert_eq!(pattern, "99 99 99 99 99");
            }
            other => panic!("expected InvalidCron, got {other:?}"),
        }
    }

    #[test]
    fn bad_cron_timezone_rejected_alongside_a_valid_cron_restart() {
        // fails if the `cron_restart` branch maps CronParseError::Timezone to
        // anything but NormalizeError::InvalidTimezone. CronSchedule::parse
        // resolves the zone before the pattern, so a valid pattern paired
        // with a bad zone is the only input that reaches that arm.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_restart = Some("0 3 * * *".to_string());
        app.cron_timezone = Some("Mars/Olympus".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidTimezone { name } => assert_eq!(name, "Mars/Olympus"),
            other => panic!("expected InvalidTimezone, got {other:?}"),
        }
    }

    #[test]
    fn cron_timezone_validated_even_without_cron_restart() {
        // fails if timezone validation is skipped when there's no pattern to
        // pair it with: a Flockfile with only a bad `cron_timezone` is a
        // typo the user wants to hear about.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_timezone = Some("Mars/Olympus".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidTimezone { name } => assert_eq!(name, "Mars/Olympus"),
            other => panic!("expected InvalidTimezone, got {other:?}"),
        }
    }

    #[test]
    fn duplicate_names_rejected_across_a_flock() {
        let apps = vec![
            AppConfig::minimal("web", "./a"),
            AppConfig::minimal("web", "./b"),
        ];
        assert_eq!(
            normalize_all(apps).unwrap_err(),
            NormalizeError::DuplicateName("web".to_string())
        );
    }

    #[test]
    fn a_cycle_inside_one_document_is_refused_and_named() {
        // fails if normalize_all accepts a cycle, or reports it without a path
        let mut a = AppConfig::minimal("a", "./a");
        a.depends_on = vec!["b".to_string()];
        let mut b = AppConfig::minimal("b", "./b");
        b.depends_on = vec!["a".to_string()];
        match normalize_all(vec![a, b]) {
            Err(NormalizeError::DependencyCycle(cycle)) => {
                let rendered = NormalizeError::DependencyCycle(cycle).to_string();
                assert!(rendered.contains("a"), "{rendered}");
                assert!(rendered.contains("b"), "{rendered}");
                assert!(
                    rendered.contains(" -> "),
                    "the path must be shown: {rendered}"
                );
            }
            other => panic!("expected DependencyCycle, got {other:?}"),
        }
    }

    #[test]
    fn a_dependency_on_an_app_outside_the_document_is_accepted() {
        // fails if the document-local check refuses a cross-repository
        // dependency, which would make depends_on unusable across Flockfiles
        let mut api = AppConfig::minimal("api", "./api");
        api.depends_on = vec!["db-in-another-repo".to_string()];
        normalize_all(vec![api]).expect("an unresolved name is not a document error");
    }

    fn probe_config(target: &str) -> crate::config::ProbeConfig {
        crate::config::ProbeConfig {
            kind: crate::config::ProbeKind::Http,
            target: target.to_string(),
            interval: crate::values::UpDuration::from_millis(10_000),
            timeout: crate::values::UpDuration::from_millis(5_000),
            failure_threshold: 3,
        }
    }

    #[test]
    fn malformed_readiness_probe_target_rejected_naming_the_field() {
        // fails if validate_probe is never called for readiness_probe, or if
        // it drops which of the two probe fields the rejection came from
        let mut app = AppConfig::minimal("web", "./srv");
        app.readiness_probe = Some(probe_config("not-a-url"));
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidProbe { probe, reason } => {
                assert_eq!(probe, "readiness_probe");
                assert!(!reason.is_empty());
            }
            other => panic!("expected InvalidProbe, got {other:?}"),
        }
    }

    #[test]
    fn malformed_liveness_probe_target_rejected_naming_the_field() {
        // fails if only readiness_probe is ever validated, leaving a bad
        // liveness_probe target to surface later at the daemon's first poll
        let mut app = AppConfig::minimal("web", "./srv");
        app.liveness_probe = Some(probe_config("not-a-url"));
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidProbe { probe, .. } => assert_eq!(probe, "liveness_probe"),
            other => panic!("expected InvalidProbe, got {other:?}"),
        }
    }

    #[test]
    fn valid_probe_targets_accepted() {
        // fails if validate_probe rejects a well-formed target outright
        let mut app = AppConfig::minimal("web", "./srv");
        app.readiness_probe = Some(probe_config("http://127.0.0.1:8080/healthz"));
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn zero_failure_threshold_rejected() {
        // fails if failure_threshold is never inspected: a threshold of 0
        // means "unhealthy before the first probe ever runs"
        let mut app = AppConfig::minimal("web", "./srv");
        let mut probe = probe_config("http://127.0.0.1:8080/healthz");
        probe.failure_threshold = 0;
        app.readiness_probe = Some(probe);
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::ZeroFailureThreshold {
                probe: "readiness_probe"
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("at least 1"), "{err}");
    }

    #[test]
    fn zero_interval_rejected() {
        // fails if interval is never inspected: a zero interval would spin
        // the readiness wait as fast as the runtime allows for the whole
        // `listen_timeout` (`await_ready` does not floor it)
        let mut app = AppConfig::minimal("web", "./srv");
        let mut probe = probe_config("http://127.0.0.1:8080/healthz");
        probe.interval = UpDuration::from_millis(0);
        app.readiness_probe = Some(probe);
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::IntervalBelowMinimum {
                probe: "readiness_probe",
                value: UpDuration::from_millis(0),
                min: MIN_READINESS_INTERVAL,
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("must be at least"), "{err}");
    }

    #[test]
    fn a_liveness_interval_under_the_floor_is_rejected_rather_than_clamped() {
        // fails if the liveness check is `interval == 0` rather than a
        // floor: a 500ms interval survives equality and is then silently
        // rounded up to a full second by `MIN_PROBE_INTERVAL`. Also fails
        // if the rejection drops the value the user wrote.
        let mut app = AppConfig::minimal("web", "./srv");
        let mut probe = probe_config("http://127.0.0.1:8080/healthz");
        probe.interval = UpDuration::from_millis(500);
        app.liveness_probe = Some(probe);
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::IntervalBelowMinimum {
                probe: "liveness_probe",
                value: UpDuration::from_millis(500),
                min: MIN_LIVENESS_INTERVAL,
            }
        );
        assert!(err.to_string().contains("500"), "{err}");
    }

    #[test]
    fn a_liveness_interval_exactly_at_the_floor_is_accepted() {
        // fails if the comparison is `<=` rather than `<`: the floor is a
        // value the liveness loop honours exactly, so naming it must not be
        // an error.
        let mut app = AppConfig::minimal("web", "./srv");
        let mut probe = probe_config("http://127.0.0.1:8080/healthz");
        probe.interval = MIN_LIVENESS_INTERVAL;
        app.liveness_probe = Some(probe);
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn a_sub_second_readiness_interval_is_accepted() {
        // fails if both probes are validated against the liveness floor: a
        // readiness wait is bounded by `listen_timeout` and honours its
        // `interval` exactly as written, so a fast app polling every 50ms
        // to leave `starting` sooner must not be refused.
        let mut app = AppConfig::minimal("web", "./srv");
        let mut probe = probe_config("http://127.0.0.1:8080/healthz");
        probe.interval = UpDuration::from_millis(50);
        app.readiness_probe = Some(probe);
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn zero_max_memory_rejected() {
        // fails if `max_memory` is never inspected: zero is a ceiling every
        // live process is already over, so the enforcer breaches on every
        // reading and the automatic restart that follows resets the
        // restart budget instead of spending it.
        let mut app = AppConfig::minimal("web", "./srv");
        app.max_memory = Some(crate::values::MemSize::from_bytes(0));
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::ZeroMaxMemory {
                name: "web".to_string()
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("max_memory"), "{err}");
    }

    #[test]
    fn a_nonzero_max_memory_is_accepted() {
        // fails if the check fires on `max_memory` being set at all rather
        // than on its being zero: that would refuse every app that
        // configures a limit, which is the whole feature
        let mut app = AppConfig::minimal("web", "./srv");
        app.max_memory = Some("512M".parse().unwrap());
        assert!(normalize(app).is_ok());
    }

    /// fails if a `kill_signal` shep cannot send is accepted here: that puts
    /// SIGTERM on the wire for the life of the process with nothing but one
    /// daemon log line to say so.
    #[test]
    fn a_kill_signal_shep_cannot_send_is_refused_by_name() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.kill_signal = Some("SIGUSR1".to_string());

        let err = normalize(app).unwrap_err();

        assert_eq!(
            err,
            NormalizeError::InvalidKillSignal {
                name: "web".to_string(),
                value: "SIGUSR1".to_string(),
            }
        );
        // The message has to name the accepted set, because the operator's next
        // move is picking a different word and there is nowhere else to look.
        let rendered = err.to_string();
        assert!(rendered.contains("SIGUSR1"), "{rendered}");
        assert!(rendered.contains("SIGTERM"), "{rendered}");
        assert!(rendered.contains("SIGUSR2"), "{rendered}");
    }

    /// fails if the four supported names, their bare forms, or a lowercase
    /// spelling stop being accepted. This is the compatibility half: every
    /// spelling `stop_signal` accepted before this task must still normalize.
    #[test]
    fn every_spelling_the_daemon_already_accepted_still_normalizes() {
        for name in [
            "SIGTERM", "TERM", "sigterm", "term", "SIGINT", "INT", "SIGQUIT", "QUIT", "SIGUSR2",
            "USR2", "sigusr2",
        ] {
            let mut app = AppConfig::minimal("web", "./srv");
            app.kill_signal = Some(name.to_string());
            assert!(
                normalize(app).is_ok(),
                "`{name}` was accepted before this task and must still be"
            );
        }
    }

    /// fails if an unset `kill_signal` is refused: the overwhelmingly common
    /// case, and the one a validation pass is most likely to break by
    /// treating `None` as an empty string.
    #[test]
    fn an_unset_kill_signal_is_not_a_config_error() {
        let app = AppConfig::minimal("web", "./srv");
        assert!(app.kill_signal.is_none());
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn action_timeout_past_the_ceiling_is_rejected() {
        // fails if `action_timeout` is never inspected. One millisecond over
        // the ceiling is deliberate: a test at a round number like 60s could
        // pass by coincidence if the check used the wrong constant entirely
        // (`MAX_DEADLINE_MS` itself, say, instead of the margin under it).
        let mut app = AppConfig::minimal("web", "./srv");
        app.action_timeout = UpDuration::from_millis(MAX_ACTION_TIMEOUT.as_millis() + 1);
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::ActionTimeoutTooLong {
                name: "web".to_string(),
                value: UpDuration::from_millis(MAX_ACTION_TIMEOUT.as_millis() + 1),
                max: MAX_ACTION_TIMEOUT,
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("action_timeout"), "{err}");
    }

    #[test]
    fn action_timeout_at_the_ceiling_is_accepted() {
        // fails if the comparison is `>=` rather than `>`: the ceiling
        // itself still leaves the daemon its full margin under the hard
        // clamp, so it is not one of the values nothing could ever satisfy.
        let mut app = AppConfig::minimal("web", "./srv");
        app.action_timeout = MAX_ACTION_TIMEOUT;
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn the_default_action_timeout_is_accepted() {
        // fails if `AppConfig::default()`'s own value ever drifts past the
        // ceiling normalize enforces: the one combination that must never
        // reject the config nobody customized.
        assert!(normalize(AppConfig::minimal("web", "./srv")).is_ok());
    }

    #[test]
    fn zero_watch_delay_rejected() {
        // fails if `watch_delay` is never inspected. notify's debouncer
        // derives its poll tick as `watch_delay / 4` and sleeps it on its own
        // OS thread, so zero is `loop { sleep(0); lock(); }`, a CPU-spinning
        // busy loop.
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        app.watch_delay = Some(UpDuration::from_millis(0));
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::ZeroWatchDelay {
                name: "web".to_string()
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("watch_delay"), "{err}");
    }

    #[test]
    fn a_zero_watch_delay_is_rejected_with_watch_off() {
        // fails if the check is nested inside the `watch` block: an app
        // carrying `watch_delay = "0"` with `watch = false` would normalize
        // clean, and the spin would arrive the day someone flips `watch =
        // true`
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch_delay = Some(UpDuration::from_millis(0));
        assert!(matches!(
            normalize(app).unwrap_err(),
            NormalizeError::ZeroWatchDelay { .. }
        ));
    }

    #[test]
    fn a_nonzero_watch_delay_is_accepted() {
        // fails if the check fires on `watch_delay` being set at all rather
        // than on its being zero: that would refuse every app that tunes
        // its own debounce
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        app.watch_delay = Some(UpDuration::from_millis(1));
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn default_failure_threshold_from_toml_accepted() {
        // fails if the check fires on the ordinary default instead of only
        // an explicit 0. Deserializes a Flockfile snippet that omits
        // `failure_threshold`, exercising the real serde default rather
        // than `probe_config`'s hardcoded `3`.
        let src = r#"
name = "web"
script = "./srv"

[readiness_probe]
kind = "http"
target = "http://127.0.0.1:8080/healthz"
"#;
        let app: AppConfig = toml::from_str(src).unwrap();
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn watch_true_without_cwd_rejected_naming_the_app() {
        // fails if a validator never looks at `watch`, or looks at it but
        // carries no app name, leaving the user unable to tell which
        // Flockfile entry to edit
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::WatchWithoutCwd {
                name: "web".to_string()
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("no cwd to watch"), "{err}");
    }

    #[test]
    fn watch_true_with_cwd_accepted() {
        // fails if the check fires on `watch` alone, ignoring that a cwd was
        // actually provided
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn a_watch_options_glob_that_will_not_compile_is_rejected() {
        // fails if `watch_options` patterns are never compiled at config
        // time. Also fails if the rejection blames the whole list instead
        // of the one bad pattern: the valid `src/**` comes first, so
        // naming it, or the patterns joined together, is wrong.
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        app.watch_options = vec!["src/**".to_string(), "[".to_string()];
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::InvalidWatchGlob {
                name: "web".to_string(),
                field: "watch_options",
                pattern: "[".to_string(),
                reason: Glob::new("[").unwrap_err().to_string(),
            }
        );
        // fails if the message drops the app name, the list or the pattern:
        // the three things that name the Flockfile line to edit.
        let rendered = err.to_string();
        for expected in ["web", "watch_options", "`[`"] {
            assert!(
                rendered.contains(expected),
                "{expected} missing: {rendered}"
            );
        }
    }

    #[test]
    fn an_ignore_watch_glob_that_will_not_compile_is_rejected() {
        // fails if only `watch_options` is ever compiled, leaving a mistyped
        // `ignore_watch` to cost the app its watch at arm time instead
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        app.ignore_watch = vec!["[".to_string()];
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidWatchGlob { field, pattern, .. } => {
                assert_eq!(field, "ignore_watch");
                assert_eq!(pattern, "[");
            }
            other => panic!("expected InvalidWatchGlob, got {other:?}"),
        }
    }

    #[test]
    fn a_glob_that_will_not_compile_is_rejected_with_watch_off() {
        // fails if glob validation is nested inside the `watch` check: an app
        // carrying a mistyped glob with `watch = false` would then normalize
        // clean, and the typo would surface only the day someone flips
        // `watch = true`
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch_options = vec!["[".to_string()];
        assert!(matches!(
            normalize(app).unwrap_err(),
            NormalizeError::InvalidWatchGlob { .. }
        ));
    }

    #[test]
    fn well_formed_watch_globs_are_accepted() {
        // fails if the check rejects patterns globset compiles happily:
        // recursive `**`, a character class, a negated class and a brace
        // alternation. Also fails if it is wired to a parser that is not
        // globset's, since these are a syntax error to a regex engine.
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        app.watch_options = vec!["src/**/*.rs".to_string(), "*.[ch]".to_string()];
        app.ignore_watch = vec!["target/**".to_string(), "**/[!.]*.{tmp,swp}".to_string()];
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn a_typo_in_an_env_template_is_refused_and_names_the_field() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.env
            .insert("WORKER".to_string(), "w-{{instnace}}".to_string());
        let err = normalize(app).unwrap_err();
        let rendered = err.to_string();
        assert!(rendered.contains("instnace"), "names the typo: {rendered}");
        assert!(rendered.contains("WORKER"), "and the field: {rendered}");
    }

    #[test]
    fn a_typo_in_an_arg_template_is_refused_too() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.args = vec!["--port".to_string(), "91{{slot}}".to_string()];
        let err = normalize(app).unwrap_err();
        assert!(err.to_string().contains("slot"), "{err}");
    }

    #[test]
    fn an_explicit_log_path_shared_by_every_instance_is_refused() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.instances = 3;
        app.out_file = Some("/var/log/web.log".to_string());
        let err = normalize(app).unwrap_err();
        let rendered = err.to_string();
        assert!(rendered.contains("out_file"), "names the field: {rendered}");
        assert!(
            rendered.contains("{{instance}}") && rendered.contains("merge_logs"),
            "and both ways out: {rendered}"
        );
        assert!(
            !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
            "no em or en dash in copy a user reads: {rendered}"
        );
    }

    #[test]
    fn the_three_ways_out_of_the_shared_log_refusal_all_work() {
        // A slot in the path.
        let mut templated = AppConfig::minimal("web", "./srv");
        templated.instances = 3;
        templated.out_file = Some("/var/log/web-{{instance}}.log".to_string());
        assert!(normalize(templated).is_ok());

        // Asking for the merge on purpose.
        let mut merged = AppConfig::minimal("web", "./srv");
        merged.instances = 3;
        merged.out_file = Some("/var/log/web.log".to_string());
        merged.merge_logs = true;
        assert!(normalize(merged).is_ok());

        // One instance cannot collide with itself.
        let mut single = AppConfig::minimal("web", "./srv");
        single.out_file = Some("/var/log/web.log".to_string());
        assert!(normalize(single).is_ok());
    }

    #[test]
    fn an_escaped_template_in_a_log_path_does_not_satisfy_the_refusal() {
        // `{{{{instance}}}}` spells the token but renders to one literal path
        // for every instance, so a substring check would wave it through.
        let mut app = AppConfig::minimal("web", "./srv");
        app.instances = 3;
        app.out_file = Some("/var/log/web-{{{{instance}}}}.log".to_string());
        assert!(normalize(app).is_err());
    }

    #[test]
    fn a_name_only_template_does_not_resolve_the_collision() {
        // `{{name}}` is the same for every instance, so a path carrying only it
        // still puts every instance on one file. Presence of a token is not the
        // test; rendering differently is.
        let mut app = AppConfig::minimal("web", "./srv");
        app.instances = 3;
        app.out_file = Some("/var/log/{{name}}.log".to_string());
        assert!(normalize(app).is_err());
    }

    #[test]
    fn a_bad_template_in_a_log_path_is_reported_as_bad_template_not_shared_path() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.instances = 3;
        app.out_file = Some("/var/log/web-{{instnace}}.log".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::BadTemplate { field, reason, .. } => {
                assert_eq!(field, "out_file");
                assert!(reason.contains("instnace"), "{reason}");
            }
            other => panic!("expected BadTemplate, got {other:?}"),
        }
    }

    #[test]
    fn watch_options_without_watch_or_cwd_accepted() {
        // fails if the check is keyed on `watch_options` being non-empty
        // rather than on `watch` being true: that would reject a Flockfile
        // that never asked to be watched
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch_options = vec!["src/**".to_string()];
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn a_sheep_that_depends_on_itself_is_refused_by_name() {
        // fails if the self-edge check is missing, or if it reports a bare
        // cycle rather than naming the sheep
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["api".to_string()];
        match normalize(app) {
            Err(NormalizeError::SelfDependency(name)) => assert_eq!(name, "api"),
            other => panic!("expected SelfDependency, got {other:?}"),
        }
    }

    #[test]
    fn a_dependency_on_one_instance_is_refused_naming_the_app_form() {
        // fails if `name:slot` is accepted as a dependency target
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["db:2".to_string()];
        match normalize(app) {
            Err(NormalizeError::InstanceDependency { sheep, target }) => {
                assert_eq!(sheep, "api");
                assert_eq!(target, "db:2");
            }
            other => panic!("expected InstanceDependency, got {other:?}"),
        }
        let rendered = NormalizeError::InstanceDependency {
            sheep: "api".to_string(),
            target: "db:2".to_string(),
        }
        .to_string();
        assert!(
            rendered.contains("`db`"),
            "the refusal must name the app-level form: {rendered}"
        );
    }

    #[test]
    fn duplicate_dependencies_dedupe_rather_than_refusing() {
        // fails if a repeated name is an error, or if it survives into the
        // normalized config twice
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["db".to_string(), "db".to_string()];
        let resolved = normalize(app).expect("a repeated name is not an error");
        assert_eq!(resolved.config().depends_on, vec!["db".to_string()]);
    }

    #[test]
    fn an_ordinary_dependency_list_survives_normalize() {
        // fails if the field is dropped or reordered
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["db".to_string(), "cache".to_string()];
        let resolved = normalize(app).expect("an ordinary list normalizes");
        assert_eq!(
            resolved.config().depends_on,
            vec!["db".to_string(), "cache".to_string()]
        );
    }
}