shep-daemon 0.7.2

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
//! The muster roll: persisted flock state for restart-survival (`shep muster`)
//!
//! `FlockRegistry::roll` turns the registry's [`AppConfig`]s plus a live
//! [`ProcessInfo`] listing into a [`FlockSnapshot`], written to `flock.json`
//! by `write_atomic`. A `SnapshotWriter` task debounces lifecycle events so a
//! restart storm produces one write. `restorable` re-validates every entry,
//! since the file is human-editable.
//!
//! `muster` reads the roll and starts those apps, from `boot` and from the
//! `Muster` request alike, stage by stage in `depends_on` order
//! (`crate::boot_order`). An app restores iff it was running when the roll was
//! saved (`instances_running > 0`) and `autostart` is still true; one the flock
//! already has is left where it stands, still reported as restored. Nothing
//! about the graph refuses a restore: a cycle, a name nothing answers to and a
//! dependency that opted out of `autostart` are each warned about and started
//! around, because the machine this runs on has nobody watching it.

use core::fmt;

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};

use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
use tokio::sync::Notify;
use tokio::sync::broadcast::{self, error::RecvError};
use tokio::task::JoinHandle;
use tokio::time::{Duration, Instant, sleep_until};

use shep_core::config::graph::{BootPlan, render_cycle};
use shep_core::config::{AppConfig, NormalizeError, ResolvedApp, normalize};
use shep_core::protocol::{BusEvent, ProcessInfo};
use shep_core::status::ProcStatus;

use crate::bus::{Bus, SharedEvent};
use crate::supervisor::{BatchPolicy, SupervisorHandle};

/// Schema version of `flock.json`
pub(crate) const SNAPSHOT_VERSION: u32 = 1;

/// How long the writer lets a burst of lifecycle events settle before it
/// rewrites the roll.
///
/// One restart emits Exit + Restart + Start + Online within microseconds;
/// 250 ms folds a whole restart storm into a single atomic write while still
/// landing the roll orders of magnitude faster than the reboot it protects
/// against (spec §13.4).
pub(crate) const SNAPSHOT_DEBOUNCE_MS: u64 = 250;

/// The muster roll: which apps were registered, and how many were up
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FlockSnapshot {
    /// Schema version this roll was written under (`SNAPSHOT_VERSION`)
    pub version: u32,
    /// Wall-clock milliseconds since the Unix epoch when this roll was built
    pub saved_at_ms: u64,
    /// One entry per sheep still known to the flock at save time
    pub apps: Vec<SavedApp>,
}

/// One sheep's entry in a [`FlockSnapshot`]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SavedApp {
    /// The config the sheep was started from (Debug redacts `env`, through
    /// [`AppConfig`]'s own redacting `Debug`)
    pub app: AppConfig,
    /// How many instances of this sheep were running when the roll was built
    pub instances_running: u32,
}

/// The daemon's record of the config each registered sheep was started from
///
/// The supervisor owns runtime state; nothing in a [`ProcessInfo`] can
/// reproduce the `AppConfig` a sheep came from, which is exactly what a roll
/// needs. Cheap to clone (one `Arc`).
#[derive(Debug, Clone, Default)]
pub(crate) struct FlockRegistry {
    apps: Arc<Mutex<BTreeMap<String, AppConfig>>>,
    /// Woken by every write to `apps`, so the roll writer schedules a file
    /// write for a change that moves no process and so publishes no
    /// [`BusEvent::Process`] of its own.
    dirty: Arc<Notify>,
}

impl FlockRegistry {
    /// Builds an empty registry
    #[must_use]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Records (or re-records) each app's config, keyed by name.
    pub(crate) fn record(&self, apps: &[ResolvedApp]) {
        let mut map = self.apps.lock().unwrap_or_else(PoisonError::into_inner);
        for app in apps {
            map.insert(app.config().name.clone(), app.config().clone());
        }
        drop(map);
        self.dirty.notify_one();
    }

    /// Records one app's config directly, for a successor rebuilding this
    /// registry from a handover blob.
    ///
    /// [`Self::record`] takes [`ResolvedApp`]s because every other caller has
    /// just normalized one. A successor holds only the [`AppConfig`] the blob
    /// carried, and the supervisor re-normalizes that on its own way to
    /// installing the sheep.
    ///
    /// The roll is written from this registry, so a successor that left it
    /// empty would overwrite a good roll within seconds of taking over.
    #[cfg(unix)]
    pub(crate) fn record_config(&self, config: &AppConfig) {
        self.apps
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(config.name.clone(), config.clone());
        self.dirty.notify_one();
    }

    /// Drops every recorded app, so the next [`Self::roll`] describes an
    /// empty flock regardless of what is still live in the supervisor's own
    /// listing.
    ///
    /// The one caller is [`crate::boot::RunningDaemon::run`]'s teardown, under
    /// `BootOptions::delete_flock_on_shutdown`: `shep dev`'s isolated session,
    /// where nothing should survive for a later `shep muster`. A production
    /// shutdown never calls it.
    pub(crate) fn clear(&self) {
        self.apps
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clear();
        self.dirty.notify_one();
    }

    /// Every registered sheep's name, with the names it says it waits for.
    ///
    /// Infallible, one lock and no normalize: the teardown builds its stop
    /// plan from this, and a fallible step on the one path that always runs
    /// would silently skip the staged stop instead of failing loudly.
    pub(crate) fn depends_on_by_name(&self) -> BTreeMap<String, Vec<String>> {
        self.apps
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .iter()
            .map(|(name, app)| (name.clone(), app.depends_on.clone()))
            .collect()
    }

    /// `name`'s `listen_timeout` and `graceful_timeout`, in that order, or
    /// `None` when no registered sheep has that name.
    ///
    /// The pair an ordered restart or reload bounds a stage's wait by. Read
    /// here because a `ProcessInfo` carries no timeout at all, and the
    /// alternative is a round trip to the actor per member of a stage.
    pub(crate) fn timeouts_of(&self, name: &str) -> Option<(Duration, Duration)> {
        self.apps
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(name)
            .map(|app| {
                (
                    app.listen_timeout.as_duration(),
                    app.graceful_timeout.as_duration(),
                )
            })
    }

    /// Builds the roll from the live listing, pruning names the flock no
    /// longer has (a deleted sheep must not resurrect).
    #[must_use]
    pub(crate) fn roll(&self, infos: &[ProcessInfo], now_ms: u64) -> FlockSnapshot {
        // A poisoned lock recovers instead of panicking: the map is a plain
        // BTreeMap, so a panic elsewhere cannot leave it inconsistent, and
        // taking the daemon down over it would be the worse failure.
        let mut apps = self.apps.lock().unwrap_or_else(PoisonError::into_inner);
        apps.retain(|name, _| infos.iter().any(|info| &info.name == name));
        let saved = apps
            .iter()
            .map(|(name, app)| SavedApp {
                app: app.clone(),
                instances_running: u32::try_from(
                    infos
                        .iter()
                        .filter(|i| &i.name == name && is_running(i.status))
                        .count(),
                )
                .unwrap_or(u32::MAX),
            })
            .collect();
        FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: now_ms,
            apps: saved,
        }
    }
}

/// True for the statuses [`FlockRegistry::roll`] counts as "up".
///
/// [`ProcStatus::Stopping`] is absent: a reload's drainee and its replacement
/// hold the same instance slot, so counting both would report two running
/// instances for one.
fn is_running(status: ProcStatus) -> bool {
    matches!(
        status,
        ProcStatus::Online | ProcStatus::Starting | ProcStatus::WaitingRestart
    )
}

/// Error type returned from `write_atomic` and [`read`]
///
/// Wraps `io::Error`/`serde_json::Error` directly rather than stringifying
/// them, so callers keep the underlying diagnostic through
/// [`core::error::Error::source`]. That costs the enum
/// `Clone`/`PartialEq`/`Eq`.
///
/// `#[non_exhaustive]`: a future roll-format refusal would need its own
/// variant, distinct from [`Self::Parse`]'s catch-all.
#[non_exhaustive]
#[derive(Debug)]
pub enum SnapshotError {
    /// The roll path has no parent directory to create the temp file in
    /// (carries the path)
    NoParent(PathBuf),
    /// The roll failed to serialize to JSON
    Encode(serde_json::Error),
    /// The temp file, `fsync`, rename, or read failed
    Io(std::io::Error),
    /// The roll on disk is not valid JSON, or its `version` is one this
    /// daemon does not know how to restore (carries the parse/version
    /// message)
    Parse(String),
}

impl fmt::Display for SnapshotError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoParent(path) => {
                write!(f, "roll path `{}` has no parent directory", path.display())
            }
            Self::Encode(err) => write!(f, "muster roll failed to serialize: {err}"),
            Self::Io(err) => write!(f, "muster roll I/O failed: {err}"),
            Self::Parse(msg) => write!(f, "muster roll is unreadable: {msg}"),
        }
    }
}

impl core::error::Error for SnapshotError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Encode(err) => Some(err),
            Self::Io(err) => Some(err),
            Self::NoParent(_) | Self::Parse(_) => None,
        }
    }
}

impl From<serde_json::Error> for SnapshotError {
    fn from(source: serde_json::Error) -> Self {
        Self::Encode(source)
    }
}

impl From<std::io::Error> for SnapshotError {
    fn from(source: std::io::Error) -> Self {
        Self::Io(source)
    }
}

/// Writes `snapshot` to `path` atomically: a temp file in the same directory,
/// since `rename(2)` is atomic only within one filesystem, `fsync`ed, renamed
/// over `path`, then on unix the directory `fsync`ed so the rename survives a
/// power cut (a no-op on Windows). The temp file is owner-only (unix mode
/// 0600) and `persist` keeps that mode: the roll stores app `env` verbatim,
/// the one place shep writes secrets to disk.
///
/// # Errors
/// - [`SnapshotError::NoParent`]: the roll path has no directory to write into.
/// - [`SnapshotError::Encode`]: the roll failed to serialize.
/// - [`SnapshotError::Io`]: the temp file, fsync, or rename failed.
pub(crate) fn write_atomic(path: &Path, snapshot: &FlockSnapshot) -> Result<(), SnapshotError> {
    use std::io::Write;

    let parent = path
        .parent()
        .ok_or_else(|| SnapshotError::NoParent(path.to_path_buf()))?;
    let json = serde_json::to_vec_pretty(snapshot)?;

    let mut tmp = NamedTempFile::new_in(parent)?;
    tmp.write_all(&json)?;
    shep_core::atomic_file::publish(tmp, path).map_err(SnapshotError::Io)
}

/// Reads and validates a muster roll written by `write_atomic`.
///
/// Public only for `tests/daemon_e2e.rs`, which asserts on the roll a live
/// daemon wrote; the daemon's own restore path calls it from inside `boot`.
///
/// # Errors
/// - [`SnapshotError::Io`]: the roll could not be read.
/// - [`SnapshotError::Parse`]: invalid JSON, or a schema version this daemon
///   does not know.
pub fn read(path: &Path) -> Result<FlockSnapshot, SnapshotError> {
    let bytes = std::fs::read(path)?;
    let snapshot: FlockSnapshot =
        serde_json::from_slice(&bytes).map_err(|err| SnapshotError::Parse(err.to_string()))?;
    if snapshot.version != SNAPSHOT_VERSION {
        return Err(SnapshotError::Parse(format!(
            "roll schema version {} is not one this daemon knows (expected {SNAPSHOT_VERSION})",
            snapshot.version
        )));
    }
    Ok(snapshot)
}

/// What a `muster` should put back: every member, which of them to start, and
/// the ones that failed re-validation
#[derive(Debug)]
pub(crate) struct Restorable {
    /// Every entry that still normalizes, in roll order. The flock is a
    /// membership list, so all of these are registered whether or not they
    /// run.
    pub(crate) members: Vec<ResolvedApp>,
    /// The subset of [`Self::members`] that was up when the roll was written
    /// and still opts into `autostart`.
    pub(crate) to_start: Vec<ResolvedApp>,
    /// Sheep name, and why its saved config failed to normalize
    pub(crate) rejected: Vec<(String, NormalizeError)>,
}

/// Splits a loaded [`FlockSnapshot`] into members, the subset to start, and
/// the entries rejected on re-validation.
///
/// Membership survives everything but `delete`: a sheep stopped when the roll
/// was written comes back registered and `Stopped`. What to START is a
/// separate question, answered by `instances_running > 0 && autostart`.
///
/// The roll is a file a human can edit, so every entry is run back through
/// [`normalize()`] like peer input, and a bad one is collected into `rejected`
/// rather than aborting the muster.
#[must_use]
pub(crate) fn restorable(snapshot: FlockSnapshot) -> Restorable {
    let mut members = Vec::new();
    let mut to_start = Vec::new();
    let mut rejected = Vec::new();
    for saved in snapshot.apps {
        let name = saved.app.name.clone();
        let was_up = saved.instances_running > 0;
        let autostart = saved.app.autostart;
        match normalize(saved.app) {
            Ok(resolved) => {
                if was_up && autostart {
                    to_start.push(resolved.clone());
                }
                members.push(resolved);
            }
            Err(err) => rejected.push((name, err)),
        }
    }
    Restorable {
        members,
        to_start,
        rejected,
    }
}

/// Reads the muster roll and starts every app it restores, returning the
/// names it restored.
///
/// The daemon's one restore path: `boot` runs it under `--restore`, the
/// `Muster` request runs it for an operator. An app the flock already has is
/// left where it stands, still counted as restored, which makes the verb
/// idempotent; starting it again is not a no-op, since
/// [`instance_slots`](crate::assemble::instance_slots) takes the lowest free
/// slot. A missing roll is not an error; an unparseable one is reported.
///
/// `dogs` names every dog this shepherd holds and `boot_first_dogs` the ones
/// `[daemon] boot_first_dogs` promotes ahead of the flock. Neither is spawned
/// here: they are the graph's dog nodes, and the split is what positions a
/// dog in the plan. Which of them [`warn_about_the_graph`] reports on is
/// decided by the live flock as well, since an unpromoted dog is already up
/// on every restore but the boot's own.
///
/// # Errors
/// - [`SnapshotError`]: the roll exists but could not be read or parsed.
pub(crate) async fn muster(
    path: &Path,
    registry: &FlockRegistry,
    supervisor: &SupervisorHandle,
    events: &Bus,
    dogs: &[String],
    boot_first_dogs: &[String],
) -> Result<Vec<String>, SnapshotError> {
    let saved = match read(path) {
        Ok(saved) => saved,
        Err(SnapshotError::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(Vec::new());
        }
        Err(err) => return Err(err),
    };
    let restorable = restorable(saved);
    for (name, err) in &restorable.rejected {
        tracing::warn!(name, %err, "muster roll entry rejected on restore");
    }
    if restorable.members.is_empty() {
        return Ok(Vec::new());
    }
    let restored: Vec<String> = restorable
        .members
        .iter()
        .map(|app| app.config().name.clone())
        .collect();

    // A supervisor that cannot be listed has no flock left to collide with,
    // and the `start` below announces its own failure.
    let running = supervisor.list_checked().await.unwrap_or_default();
    let known = |app: &ResolvedApp| running.iter().any(|info| info.name == app.config().name);
    warn_about_dogs_holding_sheep_names(&restorable.members, &running);

    // Membership for every entry `start` will not bring up, so a sheep saved
    // while stopped comes back listed. The ones being started are excluded:
    // registering them at rest first would leave an idle `instance: 0` entry
    // for `start` to allocate around, and the sheep would show up twice.
    let starting: Vec<&str> = restorable
        .to_start
        .iter()
        .map(|app| app.config().name.as_str())
        .collect();
    let members: Vec<ResolvedApp> = restorable
        .members
        .iter()
        .filter(|app| !known(app) && !starting.contains(&app.config().name.as_str()))
        .cloned()
        .collect();
    if !members.is_empty() {
        registry.record(&members);
        if let Err(err) = supervisor.register_at_rest(members).await {
            tracing::warn!(%err, "muster roll restore could not register one or more apps");
        }
    }

    let to_start: Vec<ResolvedApp> = restorable
        .to_start
        .into_iter()
        .filter(|app| !known(app))
        .collect();
    if to_start.is_empty() {
        return Ok(restored);
    }
    // Recorded whether or not the stages fully succeed: already-registered
    // entries must persist even when a later spawn fails. Only what this call
    // starts, so an app left where it stands keeps the config it is actually
    // running under.
    registry.record(&to_start);

    let plan = crate::boot_order::plan_for(&to_start, dogs, boot_first_dogs);
    warn_about_the_graph(
        &plan,
        &to_start,
        &restorable.members,
        &running,
        dogs,
        boot_first_dogs,
    );
    // `BatchPolicy::PerApp`, not `AllOrNothing`: a whole-batch refusal over an
    // app whose script provably is not there is right for an operator typing
    // `shep start` and wrong at an unattended boot, where a binary missing
    // after a rebuild would cost the machine its entire flock.
    // `PerApp` never answers `Err`; warned rather than discarded so a later
    // change of policy here cannot lose a failure silently.
    if let Err(err) = crate::boot_order::start_in_stages(
        &plan,
        &to_start,
        supervisor,
        events,
        BatchPolicy::PerApp,
    )
    .await
    {
        tracing::warn!(%err, "muster roll restore could not start one or more apps");
    }
    Ok(restored)
}

/// Warns for every saved sheep whose name a running dog has taken.
///
/// A `[daemon] boot_first_dogs` dog spawns before this restore and registers
/// under its own name against an empty flock, so [`muster`]'s `known` finds
/// the name running and filters the roll's sheep of that name out of both the
/// membership pass and the start. Nothing refuses that collision, and without
/// this line an operator loses a sheep in silence.
///
/// The name stays in the restored list. It really is in the flock, and
/// dropping it would report the loss as an absence on a terminal that has no
/// room to say why; the reply carries no per-app note to put the reason in.
fn warn_about_dogs_holding_sheep_names(members: &[ResolvedApp], running: &[ProcessInfo]) {
    for app in members {
        let name = app.config().name.as_str();
        let Some(source) = running
            .iter()
            .find(|info| info.name == name)
            .and_then(|info| info.dog.as_ref())
        else {
            continue;
        };
        tracing::warn!(
            name,
            dog = ?source,
            "a dog holds this name, so the roll's sheep of that name is not restored"
        );
    }
}

/// Whether `running` holds an entry of this name that has been spawned and
/// not given up on.
///
/// `Stopped` and `Errored` are the two that answer `false`: a dog registered
/// under either has no process behind it, so a sheep that waits for it really
/// does start without it. Every other status covers a live child, a
/// `WaitingRestart` gap between two of them included.
fn is_up(running: &[ProcessInfo], name: &str) -> bool {
    running.iter().any(|info| {
        info.name == name && !matches!(info.status, ProcStatus::Stopped | ProcStatus::Errored)
    })
}

/// Reports every way the roll's dependency graph is not what it says it is.
///
/// Nothing here refuses. A restore runs on a machine nobody is watching, so
/// each of these brings the flock up and says what it did instead: a
/// dependency nothing in the roll answers to, one that opted out of
/// `autostart`, one that is a dog starting after the flock rather than
/// before it, and a cycle.
///
/// `running` is the flock as it stands, which is what keeps the dog warning
/// from firing on a dog that is already up: this runs at an operator's
/// `shep muster` as well as at boot.
fn warn_about_the_graph(
    plan: &BootPlan,
    to_start: &[ResolvedApp],
    members: &[ResolvedApp],
    running: &[ProcessInfo],
    dogs: &[String],
    boot_first_dogs: &[String],
) {
    // A member the roll holds but this restore will not start. Named
    // separately from the unresolved edges below, since "the sheep exists and
    // opted out" is a different thing for an operator to do about than "the
    // name is a typo".
    let opted_out: BTreeSet<&str> = members
        .iter()
        .filter(|app| !app.config().autostart)
        .map(|app| app.config().name.as_str())
        .collect();
    // Every name the roll can put back, whether or not this restore starts
    // it. The plan is built from `to_start` alone, so a dependency already
    // running, saved stopped, or opted out is absent from the graph and reads
    // as unresolved. On `shep muster` against a live flock that is the whole
    // flock, and the warning below would fire on the commonest path there is.
    let restorable: BTreeSet<&str> = members
        .iter()
        .map(|app| app.config().name.as_str())
        .collect();

    for unresolved in &plan.unresolved {
        // `opted_out` is a subset of this, and has its own warning below.
        if restorable.contains(unresolved.missing.as_str()) {
            continue;
        }
        tracing::warn!(
            sheep = %unresolved.dependent,
            missing = %unresolved.missing,
            "a dependency names nothing this flock has; starting without it"
        );
    }
    for app in to_start {
        for target in &app.config().depends_on {
            if opted_out.contains(target.as_str()) {
                tracing::warn!(
                    sheep = %app.config().name,
                    dependency = %target,
                    "the dependency sets autostart = false; starting without it"
                );
            }
        }
    }
    // A dog gets an ordinary graph position, but `boot` spawns dogs in two
    // groups and neither is at a stage boundary: the promoted ones before
    // this restore, the rest after every stage. So a dependency on an
    // unpromoted dog is ordered by the plan and by nothing else, and the
    // sheep starts while the dog is not running.
    let unpromoted: BTreeSet<&str> = dogs
        .iter()
        .map(String::as_str)
        .filter(|dog| !boot_first_dogs.iter().any(|first| first == dog))
        // A dog that is already up is not one this restore starts after the
        // flock, whatever the promotion list says. `muster` is the handler for
        // an operator's `Request::Muster` as well as the boot's restore, and
        // there both dog groups have been running for hours, so reading the
        // list alone would warn about every such edge on every `shep muster`.
        // The live flock, read the way `warn_about_dogs_holding_sheep_names`
        // reads it, is what tells the two apart.
        .filter(|dog| !is_up(running, dog))
        // A dog whose name a started sheep already holds is not a node at
        // all; the sheep is, and it is ordered properly. `plan_for` drops it
        // against exactly this list.
        .filter(|dog| !to_start.iter().any(|app| app.config().name == *dog))
        .collect();
    for app in to_start {
        for target in &app.config().depends_on {
            if unpromoted.contains(target.as_str()) {
                tracing::warn!(
                    sheep = %app.config().name,
                    dog = %target,
                    "the dependency is a dog outside [daemon] boot_first_dogs, \
                     which starts after the whole flock; starting without it"
                );
            }
        }
    }
    for cycle in &plan.cycles {
        tracing::warn!(
            cycle = %render_cycle(cycle),
            "a dependency cycle; those sheep start last, in no particular order"
        );
    }
    // `BootPlan::cycles` carries ONE representative path per knot, so a sheep
    // inside the knot but off that path is just as stuck and is never named by
    // the warning above. The cyclic stage is every one of them.
    //
    // Silent when the paths already named everybody, which is the plain
    // two-node cycle: `plan` puts every knot in one stage, so this line is
    // flock-wide and would otherwise repeat the line above verbatim.
    // `BootPlan::knots` carries the membership per knot; this line wants the
    // flock-wide set, which the cyclic stage already is.
    if let Some(stuck) = cyclic_stage(plan) {
        let named: BTreeSet<&str> = plan.cycles.iter().flatten().map(String::as_str).collect();
        if stuck.iter().any(|name| !named.contains(name.as_str())) {
            let names: Vec<&str> = stuck.iter().map(String::as_str).collect();
            tracing::warn!(
                stuck = ?names,
                "every sheep a dependency cycle holds; each of them starts last"
            );
        }
    }
}

/// The stage the plan lifted every cyclic node into, if the graph has a cycle.
///
/// [`BootPlan`] does not label that stage, so it is found by the property that
/// identifies it: a name the plan reports in a cycle appears in no other one.
fn cyclic_stage(plan: &BootPlan) -> Option<&Vec<String>> {
    let member = plan.cycles.first()?.first()?;
    plan.stages.iter().find(|stage| stage.contains(member))
}

/// True for lifecycle transitions the roll cares about; false for log
/// traffic and daemon-wide notices, which must not trigger a rewrite.
fn is_state_change(event: &BusEvent) -> bool {
    matches!(event, BusEvent::Process { .. })
}

/// Handle to the debounced writer task
#[derive(Debug)]
pub(crate) struct SnapshotWriter {
    handle: JoinHandle<()>,
    /// Read only by [`Self::writes`], which carries the same `allow`.
    #[allow(dead_code, reason = "read by this crate's own tests through `writes`")]
    writes: Arc<AtomicU64>,
}

impl SnapshotWriter {
    /// Completed roll writes since boot
    ///
    /// The metrics dog reads this off the wire, so the only callers are this
    /// module's tests and it is dead in a non-test build.
    // A trivial atomic load, not per-frame hot: #[inline], never #[inline(always)].
    #[inline]
    #[must_use]
    #[allow(dead_code, reason = "called by this module's own tests")]
    pub(crate) fn writes(&self) -> u64 {
        self.writes.load(Ordering::SeqCst)
    }

    /// Stops the writer and waits for it (the caller then owns roll timing)
    pub(crate) async fn stop(self) {
        self.handle.abort();
        let _ = self.handle.await;
    }
}

/// Spawns the debounced muster-roll writer.
///
/// Coalesces bursts of lifecycle events (spec §13.4: one restart storm, one
/// write) into a single [`write_atomic`] call per [`SNAPSHOT_DEBOUNCE_MS`]
/// window. Log traffic never resets or starts the debounce timer.
///
/// Woken by [`FlockRegistry`]'s own writes as well as by the bus, so a config
/// change that parks a field reaches the file without a process having moved.
pub(crate) fn spawn_snapshot_writer(
    path: PathBuf,
    supervisor: SupervisorHandle,
    registry: FlockRegistry,
    events: broadcast::Receiver<SharedEvent>,
) -> SnapshotWriter {
    let writes = Arc::new(AtomicU64::new(0));
    let task_writes = Arc::clone(&writes);
    let dirty = Arc::clone(&registry.dirty);
    let handle = tokio::spawn(run_writer(
        path,
        supervisor,
        registry,
        events,
        dirty,
        task_writes,
    ));
    SnapshotWriter { handle, writes }
}

/// The writer's actor loop. Cancel-safe: the debounce deadline is recomputed
/// from the stored `Option<Instant>` every iteration, so losing the `select!`
/// race never extends the window.
async fn run_writer(
    path: PathBuf,
    supervisor: SupervisorHandle,
    registry: FlockRegistry,
    mut events: broadcast::Receiver<SharedEvent>,
    dirty: Arc<Notify>,
    writes: Arc<AtomicU64>,
) {
    let mut deadline: Option<Instant> = None;
    loop {
        tokio::select! {
            received = events.recv() => match received {
                // Only lifecycle events change the roll; log lines must not
                // rewrite a file once per output line.
                Ok(event) => if is_state_change(&event) && deadline.is_none() {
                    deadline = Some(Instant::now() + Duration::from_millis(SNAPSHOT_DEBOUNCE_MS));
                },
                // A lag may have swallowed a lifecycle event: assume dirty.
                Err(RecvError::Lagged(_)) => if deadline.is_none() {
                    deadline = Some(Instant::now() + Duration::from_millis(SNAPSHOT_DEBOUNCE_MS));
                },
                Err(RecvError::Closed) => break,
            },
            // A config write that parks a field moves no process, so the bus
            // says nothing and only this arm reaches the file before the next
            // unrelated lifecycle event or a graceful shutdown.
            () = dirty.notified() => if deadline.is_none() {
                deadline = Some(Instant::now() + Duration::from_millis(SNAPSHOT_DEBOUNCE_MS));
            },
            () = sleep_until(deadline.unwrap_or_else(Instant::now)), if deadline.is_some() => {
                deadline = None;
                write_now(&path, &supervisor, &registry, &writes).await;
            }
        }
    }
}

// The write is a few KiB to a local file once per debounce window;
// `spawn_blocking` would buy a task hop and nothing else.
async fn write_now(
    path: &Path,
    supervisor: &SupervisorHandle,
    registry: &FlockRegistry,
    writes: &AtomicU64,
) {
    // Engine gone: there is nothing left to record and the shutdown path has
    // already written the final roll.
    let Ok(infos) = supervisor.list_checked().await else {
        return;
    };
    let roll = registry.roll(&infos, crate::now_ms()); // lock released before any IO
    match write_atomic(path, &roll) {
        Ok(()) => {
            writes.fetch_add(1, Ordering::SeqCst);
        }
        Err(err) => tracing::warn!(%err, "muster roll write failed"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fake::{ProcScript, ScriptedRunner};
    use crate::supervisor::spawn_supervisor;
    use crate::testing::{capture_logs, test_paths};
    use shep_core::config::graph::{BootNode, NodeKind, plan};
    use shep_core::config::{AppConfig, normalize};
    use shep_core::protocol::{BusEvent, DogSource, ProcessEventKind, ProcessInfo};
    use shep_core::status::ProcStatus;
    use shep_core::values::UpDuration;
    use std::time::Duration;

    fn info(id: u32, name: &str, status: ProcStatus) -> ProcessInfo {
        ProcessInfo::builder(id, name, status)
            .pid(Some(1000 + id))
            .out_file(Some(format!("/logs/{name}-0-out.log")))
            .err_file(Some(format!("/logs/{name}-0-err.log")))
            .build()
    }

    /// Spec decision 2's argument for shipping the store unencrypted is that
    /// a reference keeps plaintext in exactly two places: the store, and the
    /// child's own environment. The roll is the file that would break it,
    /// since it is written on every registry change and read back at boot.
    ///
    /// Assembles the same app first, so the fixture is one that really
    /// resolves rather than one whose reference never had a value to leak.
    #[test]
    fn a_resolved_secret_never_reaches_the_muster_roll() {
        const SENTINEL: &str = "hunter2-that-must-never-reach-disk";

        let mut config = AppConfig::minimal("web", "./srv");
        config
            .env
            .insert("PW".to_string(), "{{secret:DB_PASSWORD}}".to_string());
        let app = normalize(config).unwrap();

        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        let view = shep_core::secrets::SecretView::new(
            "production".to_string(),
            std::collections::BTreeMap::from([(
                "DB_PASSWORD".to_string(),
                std::collections::BTreeMap::from([(
                    "production".to_string(),
                    SENTINEL.to_string(),
                )]),
            )]),
            shep_core::secrets::ProviderCache::default(),
        );
        let spec = crate::assemble::assemble(&app, 0, &paths, None, &view).unwrap();
        assert_eq!(
            spec.env["PW"], SENTINEL,
            "the fixture must really resolve, or this case proves nothing"
        );

        let registry = FlockRegistry::new();
        registry.record(&[app]);
        let roll = registry.roll(&[info(0, "web", ProcStatus::Online)], 0);

        let json = serde_json::to_string(&roll).unwrap();
        assert!(!json.contains(SENTINEL), "the roll carries a value: {json}");
        assert!(
            json.contains("{{secret:DB_PASSWORD}}"),
            "the reference is what it carries instead: {json}"
        );

        // And through the writer, which is the file that lands on disk.
        let path = dir.path().join("flock.json");
        write_atomic(&path, &roll).unwrap();
        let on_disk = std::fs::read_to_string(&path).unwrap();
        assert!(
            !on_disk.contains(SENTINEL),
            "the roll on disk carries a value: {on_disk}"
        );
    }

    // fails if `is_running` starts counting `ProcStatus::Stopping`, the status
    // a reload's drainee wears once its replacement is spawned. Both share one
    // instance slot for the swap, so counting the drainee would roll a
    // one-instance app at two.
    #[test]
    fn roll_counts_running_instances_and_prunes_deleted_names() {
        let registry = FlockRegistry::new();
        let web = normalize(AppConfig::minimal("web", "./srv")).unwrap();
        let job = normalize(AppConfig::minimal("job", "./job")).unwrap();
        registry.record(&[web, job]);

        let infos = [
            info(0, "web", ProcStatus::Online),
            info(1, "web", ProcStatus::WaitingRestart),
            info(2, "web", ProcStatus::Stopped),
            info(3, "web", ProcStatus::Stopping),
        ]; // `job` was deleted: no entries left
        let roll = registry.roll(&infos, 1_700_000_000_000);

        assert_eq!(roll.version, SNAPSHOT_VERSION);
        assert_eq!(roll.saved_at_ms, 1_700_000_000_000);
        assert_eq!(roll.apps.len(), 1, "a name with no live entry is pruned");
        assert_eq!(roll.apps[0].app.name, "web");
        // online + waiting-restart; neither the stopped one nor the drainee
        assert_eq!(roll.apps[0].instances_running, 2);
        // The prune is sticky: a second roll must not resurrect `job`.
        assert_eq!(registry.roll(&infos, 0).apps.len(), 1);
    }

    #[test]
    fn write_atomic_round_trips_with_no_leftovers() {
        // The `0600` half lives in `write_atomic_is_owner_only_on_unix`.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("flock.json");
        let registry = FlockRegistry::new();
        registry.record(&[normalize(AppConfig::minimal("web", "./srv")).unwrap()]);
        let roll = registry.roll(&[info(0, "web", ProcStatus::Online)], 42);

        write_atomic(&path, &roll).unwrap();
        write_atomic(&path, &roll).unwrap(); // overwriting keeps the guarantees

        assert_eq!(read(&path).unwrap(), roll);
        let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
        assert_eq!(
            entries.len(),
            1,
            "no temp file may survive a completed write"
        );
    }

    #[cfg(unix)]
    #[test]
    fn write_atomic_is_owner_only_on_unix() {
        // The roll stores app env verbatim (spec §10): owner-only, always.
        // Unix-gated because `0600` has no Windows ACL equivalent.
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("flock.json");
        let registry = FlockRegistry::new();
        registry.record(&[normalize(AppConfig::minimal("web", "./srv")).unwrap()]);
        let roll = registry.roll(&[info(0, "web", ProcStatus::Online)], 42);

        write_atomic(&path, &roll).unwrap();

        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "the muster roll holds app env in cleartext");
    }

    #[test]
    fn read_rejects_corrupt_json_and_unknown_schema_versions() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("flock.json");
        std::fs::write(&path, b"{not json").unwrap();
        assert!(matches!(read(&path), Err(SnapshotError::Parse { .. })));

        let future = format!(
            "{{\"version\":{},\"saved_at_ms\":0,\"apps\":[]}}",
            SNAPSHOT_VERSION + 1
        );
        std::fs::write(&path, future.as_bytes()).unwrap();
        assert!(matches!(read(&path), Err(SnapshotError::Parse { .. })));
    }

    /// Restoring only the running ones would make `shep stop` destructive
    /// across a daemon restart: the sheep would leave the flock entirely.
    #[test]
    fn restorable_keeps_every_member_and_starts_only_what_was_up() {
        let mut stopped = AppConfig::minimal("stopped", "./s");
        stopped.instances = 1;
        let mut opted_out = AppConfig::minimal("manual", "./m");
        opted_out.autostart = false;

        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![
                SavedApp {
                    app: AppConfig::minimal("web", "./srv"),
                    instances_running: 2,
                },
                SavedApp {
                    app: stopped,
                    instances_running: 0,
                },
                SavedApp {
                    app: opted_out,
                    instances_running: 1,
                },
            ],
        };
        let restorable = restorable(roll);

        let members: Vec<&str> = restorable
            .members
            .iter()
            .map(|a| a.config().name.as_str())
            .collect();
        assert_eq!(
            members,
            ["web", "stopped", "manual"],
            "every entry that normalizes belongs to the flock, running or not"
        );

        let starting: Vec<&str> = restorable
            .to_start
            .iter()
            .map(|a| a.config().name.as_str())
            .collect();
        assert_eq!(
            starting,
            ["web"],
            "only the sheep that was up and opts into autostart is started"
        );
        assert!(restorable.rejected.is_empty());
    }

    /// So a later `restart` has something to find.
    #[test]
    fn a_sheep_saved_while_stopped_is_still_a_member() {
        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![SavedApp {
                app: AppConfig::minimal("zeus-auth", "./zeus-auth"),
                instances_running: 0,
            }],
        };
        let restorable = restorable(roll);
        assert_eq!(restorable.members.len(), 1, "stopping is not forgetting");
        assert_eq!(restorable.members[0].config().name, "zeus-auth");
        assert!(
            restorable.to_start.is_empty(),
            "but it stays stopped: it was not running when the roll was written"
        );
    }

    #[test]
    fn restorable_reports_a_hand_edited_invalid_app_instead_of_aborting() {
        let mut broken = AppConfig::minimal("broken", "./b");
        broken.instances = 0; // someone edited the roll
        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![
                SavedApp {
                    app: broken,
                    instances_running: 1,
                },
                SavedApp {
                    app: AppConfig::minimal("web", "./srv"),
                    instances_running: 1,
                },
            ],
        };
        let restorable = restorable(roll);
        assert_eq!(
            restorable.members.len(),
            1,
            "one bad entry must not sink the muster"
        );
        assert_eq!(
            restorable.rejected,
            vec![(
                "broken".to_string(),
                shep_core::config::NormalizeError::ZeroInstances
            )]
        );
    }

    #[test]
    fn debug_does_not_leak_env_values() {
        // The roll carries env, and its Debug lands in daemon logs.
        let mut app = AppConfig::minimal("web", "./srv");
        app.env
            .insert("DATABASE_URL".to_string(), "postgres://secret".to_string());
        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![SavedApp {
                app,
                instances_running: 1,
            }],
        };
        let rendered = format!("{roll:?}");
        assert!(!rendered.contains("postgres://secret"), "{rendered}");
        assert!(rendered.contains("<1 vars>"), "{rendered}");
    }

    /// fails if `muster` starts an app the roll says was down, skips one it
    /// says was up, or drops either from the flock. All three in one case: an
    /// inverted restore rule would pass any one alone.
    #[tokio::test(start_paused = true)]
    async fn muster_restores_both_and_starts_only_the_one_that_was_up() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![
                SavedApp {
                    app: AppConfig::minimal("up", "./srv"),
                    instances_running: 1,
                },
                SavedApp {
                    app: AppConfig::minimal("down", "./srv"),
                    instances_running: 0,
                },
            ],
        };
        write_atomic(&paths.snapshot, &roll).unwrap();

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();

        let restored = muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
            .await
            .unwrap();
        assert_eq!(
            restored,
            vec!["up".to_string(), "down".to_string()],
            "both are restored to the flock; only one of them runs"
        );

        let mut listed = handle.list().await;
        listed.sort_by(|a, b| a.name.cmp(&b.name));
        let seen: Vec<(&str, ProcStatus)> =
            listed.iter().map(|i| (i.name.as_str(), i.status)).collect();
        assert_eq!(
            seen,
            vec![("down", ProcStatus::Stopped), ("up", ProcStatus::Online)],
            "the sheep that was down is listed and stopped, not missing"
        );
        handle.shutdown().await;
    }

    /// fails if a bad entry that is not LAST takes every app after it down.
    ///
    /// `FlockRegistry` is a `BTreeMap`, so the roll is alphabetical and
    /// `restorable` preserves that order: the `a-`/`b-`/`c-` names here make
    /// the roll order the production order, with the wreck in the middle.
    ///
    /// One `muster` call: `shep muster`'s CLI path calls twice and the second
    /// re-registers what the first lost, so only the single unattended restore
    /// a `shep startup` unit performs can show this. `failing_to_spawn` is
    /// load-bearing, since scripts are consumed in spawn order.
    #[tokio::test(start_paused = true)]
    async fn a_bad_saved_app_does_not_take_the_apps_after_it_down() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        let saved = |name: &str| SavedApp {
            app: AppConfig::minimal(name, "./srv"),
            instances_running: 1,
        };
        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![saved("a-good"), saved("b-bad"), saved("c-good")],
        };
        write_atomic(&paths.snapshot, &roll).unwrap();

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            // Two scripts for the two that must come up. `b-bad` consumes
            // none, so a run that let it take one would starve `c-good` and
            // fail here for a reason of its own.
            ScriptedRunner::new(vec![ProcScript::never_exits(); 2]).failing_to_spawn(&["b-bad"]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();

        let restored = muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
            .await
            .unwrap();
        assert_eq!(
            restored,
            vec![
                "a-good".to_string(),
                "b-bad".to_string(),
                "c-good".to_string()
            ]
        );

        let mut listed = handle.list().await;
        listed.sort_by(|a, b| a.name.cmp(&b.name));
        let seen: Vec<(&str, ProcStatus)> =
            listed.iter().map(|i| (i.name.as_str(), i.status)).collect();
        assert_eq!(
            seen,
            vec![
                ("a-good", ProcStatus::Online),
                ("b-bad", ProcStatus::Errored),
                ("c-good", ProcStatus::Online),
            ],
            "every app after the broken one must still get its turn, and the \
             broken one must be visible rather than absent"
        );
        handle.shutdown().await;
    }

    /// fails if ONE saved app that cannot start keeps the rest of the flock
    /// down at the next boot.
    ///
    /// `muster` starts under `BatchPolicy::PerApp`, not `AllOrNothing`,
    /// because the pre-registration check refuses a whole batch over one app
    /// whose script is gone, which at an unattended boot costs the machine its
    /// flock.
    ///
    /// `refusing` is the preflight verdict `AllOrNothing` refuses a whole
    /// batch over, and under `PerApp` it is only warned about, so it asserts
    /// nothing here and stands for the input the two policies disagree on.
    /// `failing_to_spawn` is what makes `gone` land as a visible `Errored`
    /// row rather than vanishing, and it names the app rather than starving it
    /// of a script: the restore starts a stage's members in the plan's order,
    /// not the roll's, and `gone` sorts first.
    #[tokio::test(start_paused = true)]
    async fn one_unstartable_saved_app_does_not_keep_the_rest_of_the_flock_down() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![
                SavedApp {
                    app: AppConfig::minimal("good", "./srv"),
                    instances_running: 1,
                },
                SavedApp {
                    app: AppConfig::minimal("gone", "./deleted-by-a-rebuild"),
                    instances_running: 1,
                },
            ],
        };
        write_atomic(&paths.snapshot, &roll).unwrap();

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()])
                .refusing(&["gone"])
                .failing_to_spawn(&["gone"]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();

        let restored = muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
            .await
            .unwrap();
        assert_eq!(restored, vec!["good".to_string(), "gone".to_string()]);

        let mut listed = handle.list().await;
        listed.sort_by(|a, b| a.name.cmp(&b.name));
        let seen: Vec<(&str, ProcStatus)> =
            listed.iter().map(|i| (i.name.as_str(), i.status)).collect();
        assert_eq!(
            seen,
            vec![("gone", ProcStatus::Errored), ("good", ProcStatus::Online)],
            "the app that could still run must come up, and the one that \
             could not must be visible rather than absent"
        );
        handle.shutdown().await;
    }

    /// fails if `muster` starts an app the flock already has.
    ///
    /// `instance_slots` hands a second `Start` of a one-instance app the next
    /// free slot, so an unconditional muster would leave it running two. The
    /// single script makes that visible: the flock's own `web` consumes it, so
    /// a duplicate lands as `Errored`.
    #[tokio::test(start_paused = true)]
    async fn muster_leaves_an_app_the_flock_already_has_where_it_stands() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        let roll = FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: vec![SavedApp {
                app: AppConfig::minimal("web", "./srv"),
                instances_running: 1,
            }],
        };
        write_atomic(&paths.snapshot, &roll).unwrap();

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();
        let app = normalize(AppConfig::minimal("web", "./srv")).unwrap();
        registry.record(std::slice::from_ref(&app));
        handle.start(vec![app]).await.unwrap();

        let restored = muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
            .await
            .unwrap();
        assert_eq!(
            restored,
            vec!["web".to_string()],
            "the roll's app is restored whether or not this call is what started it"
        );
        let listed = handle.list().await;
        assert_eq!(listed.len(), 1, "one instance of a one-instance app");
        assert_eq!(listed[0].status, ProcStatus::Online);
        handle.shutdown().await;
    }

    /// A muster roll holding `apps`, every one of them recorded as running.
    fn roll_of(apps: Vec<AppConfig>) -> FlockSnapshot {
        FlockSnapshot {
            version: SNAPSHOT_VERSION,
            saved_at_ms: 0,
            apps: apps
                .into_iter()
                .map(|app| SavedApp {
                    app,
                    instances_running: 1,
                })
                .collect(),
        }
    }

    /// Every `process.start` name waiting on `rx`, in the order the bus
    /// carried them.
    fn start_order(rx: &mut broadcast::Receiver<SharedEvent>) -> Vec<String> {
        let mut order = Vec::new();
        while let Ok(event) = rx.try_recv() {
            if let BusEvent::Process {
                event: ProcessEventKind::Start,
                info,
                ..
            } = &*event
            {
                order.push(info.name.clone());
            }
        }
        order
    }

    /// fails if the restore still hands the whole roll over as one batch. The
    /// roll is written `api` first, which is the order that starts a sheep
    /// before the one it waits for.
    #[tokio::test(start_paused = true)]
    async fn a_restore_starts_the_roll_in_dependency_order() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        let mut db = AppConfig::minimal("db", "./srv");
        db.listen_timeout = UpDuration::from_millis(50);
        let mut api = AppConfig::minimal("api", "./srv");
        api.depends_on = vec!["db".to_string()];
        write_atomic(&paths.snapshot, &roll_of(vec![api, db])).unwrap();

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits(); 2]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();
        let mut seen = events.subscribe();

        muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
            .await
            .unwrap();

        assert_eq!(
            start_order(&mut seen),
            vec!["db", "api"],
            "the roll's order must not decide boot order"
        );
        handle.shutdown().await;
    }

    /// fails if a cycle refuses the restore, which would strand an unattended
    /// boot on a typo nobody is there to read.
    #[tokio::test(start_paused = true)]
    async fn a_cyclic_roll_still_brings_the_flock_up() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        let mut a = AppConfig::minimal("a", "./srv");
        a.depends_on = vec!["b".to_string()];
        let mut b = AppConfig::minimal("b", "./srv");
        b.depends_on = vec!["a".to_string()];
        write_atomic(&paths.snapshot, &roll_of(vec![a, b])).unwrap();

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits(); 2]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();

        let restored = muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
            .await
            .expect("a cycle must not refuse the restore");

        assert_eq!(restored, vec!["a".to_string(), "b".to_string()]);
        let mut listed = handle.list().await;
        listed.sort_by(|left, right| left.name.cmp(&right.name));
        let seen: Vec<(&str, ProcStatus)> = listed
            .iter()
            .map(|info| (info.name.as_str(), info.status))
            .collect();
        assert_eq!(
            seen,
            vec![("a", ProcStatus::Online), ("b", ProcStatus::Online)],
            "both members of the knot run; neither waits for the other"
        );
        handle.shutdown().await;
    }

    /// fails if `depends_on` overrides `autostart`, which would let one app's
    /// file start a sheep another app's file said not to start.
    #[tokio::test(start_paused = true)]
    async fn a_dependency_with_autostart_off_is_warned_about_and_skipped() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        let mut db = AppConfig::minimal("db", "./srv");
        db.autostart = false;
        let mut api = AppConfig::minimal("api", "./srv");
        api.depends_on = vec!["db".to_string()];
        write_atomic(&paths.snapshot, &roll_of(vec![db, api])).unwrap();

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();
        let mut seen = events.subscribe();

        muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
            .await
            .unwrap();

        assert_eq!(
            start_order(&mut seen),
            vec!["api"],
            "db opted out; api starts without it"
        );
        handle.shutdown().await;
    }

    /// An app named `name` that waits for `deps`, normalized.
    fn dependant(name: &str, deps: &[&str]) -> ResolvedApp {
        let mut app = AppConfig::minimal(name, "./srv");
        app.depends_on = deps.iter().map(|dep| (*dep).to_string()).collect();
        normalize(app).expect("a minimal app with edges normalizes")
    }

    /// fails if a dependency the roll still holds is reported as naming
    /// nothing this flock has. The plan is built from `to_start` alone, so on
    /// `shep muster` against a live flock every already-running dependency is
    /// unresolved, and this warning fired on the commonest path there is.
    ///
    /// The second half is the control: a name the roll does not hold either
    /// really is missing, and must still be said out loud.
    #[test]
    fn a_dependency_the_roll_still_holds_is_not_called_missing() {
        let api = dependant("api", &["db"]);
        let db = normalize(AppConfig::minimal("db", "./srv")).expect("a minimal app normalizes");
        let to_start = vec![api.clone()];
        let plan = crate::boot_order::plan_for(&to_start, &[], &[]);
        assert_eq!(
            plan.unresolved.len(),
            1,
            "the plan only ever sees what this restore starts"
        );

        let held = capture_logs(|| {
            warn_about_the_graph(&plan, &to_start, &[db, api.clone()], &[], &[], &[])
        });
        assert!(!held.contains("names nothing this flock has"), "{held}");

        let absent = capture_logs(|| warn_about_the_graph(&plan, &to_start, &[api], &[], &[], &[]));
        assert!(absent.contains("names nothing this flock has"), "{absent}");
    }

    /// fails if a sheep that waits for an unpromoted dog is ordered behind it
    /// in silence. `boot` spawns dogs in two groups, promoted before the
    /// restore and the rest after every stage, so only a promoted dog is
    /// running by the time a sheep that names it starts.
    ///
    /// The control is the same graph with the dog promoted: there the wait is
    /// honoured and there is nothing to say.
    #[test]
    fn a_dependency_on_a_dog_the_boot_never_promotes_is_warned_about() {
        let to_start = vec![dependant("api", &["metrics"])];
        let dogs = ["metrics".to_string()];

        let late = capture_logs(|| {
            let plan = crate::boot_order::plan_for(&to_start, &dogs, &[]);
            warn_about_the_graph(&plan, &to_start, &to_start, &[], &dogs, &[]);
        });
        assert!(late.contains("starts after the whole flock"), "{late}");

        let promoted = capture_logs(|| {
            let plan = crate::boot_order::plan_for(&to_start, &dogs, &dogs);
            warn_about_the_graph(&plan, &to_start, &to_start, &[], &dogs, &dogs);
        });
        assert!(
            !promoted.contains("starts after the whole flock"),
            "{promoted}"
        );
    }

    /// fails if the unpromoted-dog warning reads the promotion list alone.
    /// [`muster`] is also the handler for an operator's `Request::Muster`,
    /// reached long after boot with both dog groups up, so a sheep waiting on
    /// an unpromoted but LIVE dog would be warned about on every
    /// `shep muster`. That is the same false-positive class `restorable`
    /// closes for a sheep-to-sheep edge.
    ///
    /// Driven through `muster` rather than through `warn_about_the_graph`
    /// with a synthetic list: the sibling cases all hand it their own
    /// arguments, so none of them can see a flock at all. The control is the
    /// same roll against a shepherd holding no dog, which is boot's case and
    /// must still warn.
    ///
    /// `#[test]` with a `block_on` of its own, not `#[tokio::test]`:
    /// `capture_logs` scopes its subscriber to a synchronous closure.
    #[test]
    fn a_dependency_on_an_unpromoted_dog_that_is_already_running_is_not_warned_about() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        // `metrics` is a dog this shepherd holds and does not promote, and
        // `api` waits for it.
        let dogs = ["metrics".to_string()];
        let restore = |dog_running: bool| {
            let dir = tempfile::tempdir().unwrap();
            let paths = test_paths(&dir);
            std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
            let mut api = AppConfig::minimal("api", "./srv");
            api.depends_on = vec!["metrics".to_string()];
            let roll = FlockSnapshot {
                version: SNAPSHOT_VERSION,
                saved_at_ms: 0,
                apps: vec![SavedApp {
                    app: api,
                    instances_running: 1,
                }],
            };
            write_atomic(&paths.snapshot, &roll).unwrap();

            capture_logs(|| {
                rt.block_on(async {
                    let (events, _rx) = crate::bus::test_bus(64);
                    let handle = spawn_supervisor(
                        ScriptedRunner::new(vec![
                            ProcScript::never_exits(),
                            ProcScript::never_exits(),
                        ]),
                        paths.clone(),
                        events.clone(),
                    );
                    if dog_running {
                        let dog = normalize(AppConfig::minimal("metrics", "./srv"))
                            .expect("a minimal dog normalizes");
                        handle
                            .start_dog(dog, DogSource::BuiltIn)
                            .await
                            .expect("a scripted dog that never exits starts");
                    }
                    muster(
                        &paths.snapshot,
                        &FlockRegistry::new(),
                        &handle,
                        &events,
                        &dogs,
                        &[],
                    )
                    .await
                    .expect("the roll parses");
                });
            })
        };

        let live = restore(true);
        assert!(!live.contains("starts after the whole flock"), "{live}");

        let at_boot = restore(false);
        assert!(
            at_boot.contains("starts after the whole flock"),
            "{at_boot}"
        );
    }

    /// fails if a promoted dog takes a saved sheep's name in silence. It
    /// registers against an empty flock before the restore, so `muster` reads
    /// the name as already running and drops the sheep from both the
    /// membership pass and the start while still reporting it restored.
    ///
    /// The control is the same name running as an ordinary sheep, which is
    /// the idempotent restore this must not start warning about.
    #[test]
    fn a_dog_holding_a_saved_sheeps_name_is_warned_about() {
        let members = vec![normalize(AppConfig::minimal("metrics", "./srv")).expect("normalizes")];
        let as_dog = [ProcessInfo::builder(0, "metrics", ProcStatus::Online)
            .dog(Some(DogSource::BuiltIn))
            .build()];
        let as_sheep = [ProcessInfo::builder(0, "metrics", ProcStatus::Online).build()];

        let collided = capture_logs(|| warn_about_dogs_holding_sheep_names(&members, &as_dog));
        assert!(collided.contains("is not restored"), "{collided}");

        let plain = capture_logs(|| warn_about_dogs_holding_sheep_names(&members, &as_sheep));
        assert!(!plain.contains("is not restored"), "{plain}");
    }

    /// fails if a plain two-node cycle prints its membership twice. `plan`
    /// puts every knot into one stage, so the membership line is flock-wide,
    /// and on two nodes it repeats the representative path verbatim.
    ///
    /// The three-node knot is the control: there the path names two of the
    /// three, so the membership line is the only thing that names the third.
    #[test]
    fn a_two_node_knot_is_not_reported_twice_over() {
        let pair = vec![dependant("a", &["b"]), dependant("b", &["a"])];
        let plan = crate::boot_order::plan_for(&pair, &[], &[]);

        let two = capture_logs(|| warn_about_the_graph(&plan, &pair, &pair, &[], &[], &[]));
        assert!(
            !two.contains("every sheep a dependency cycle holds"),
            "{two}"
        );

        let trio = vec![
            dependant("a", &["b"]),
            dependant("b", &["a", "c"]),
            dependant("c", &["b"]),
        ];
        let plan = crate::boot_order::plan_for(&trio, &[], &[]);
        let three = capture_logs(|| warn_about_the_graph(&plan, &trio, &trio, &[], &[], &[]));
        assert!(
            three.contains("every sheep a dependency cycle holds"),
            "{three}"
        );
    }

    /// fails if the cycle warning names only the representative path. Every
    /// one of these three is stuck, and the path through the knot names two.
    #[test]
    fn the_cyclic_stage_names_every_sheep_in_the_knot() {
        let node = |name: &str, deps: &[&str]| BootNode {
            name: name.to_string(),
            depends_on: deps.iter().map(|dep| (*dep).to_string()).collect(),
            kind: NodeKind::Sheep,
        };
        let plan = plan(&[node("a", &["b"]), node("b", &["a", "c"]), node("c", &["b"])]);
        assert_eq!(plan.cycles.len(), 1, "one knot, one representative path");
        assert!(
            plan.cycles[0].len() < 3,
            "the point of the extra report is a member the path leaves out"
        );

        assert_eq!(
            cyclic_stage(&plan),
            Some(&vec!["a".to_string(), "b".to_string(), "c".to_string()]),
        );
    }

    /// fails if a missing roll becomes an error. A fresh `$SHEP_HOME` has
    /// none, and a daemon that refused over it could not boot on a clean
    /// machine.
    #[tokio::test(start_paused = true)]
    async fn a_missing_roll_restores_nothing_without_failing() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(paths.snapshot.parent().unwrap()).unwrap();
        assert!(!paths.snapshot.exists());

        let (events, _rx) = crate::bus::test_bus(64);
        let handle = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();

        assert_eq!(
            muster(&paths.snapshot, &registry, &handle, &events, &[], &[])
                .await
                .unwrap(),
            Vec::<String>::new()
        );
        assert!(handle.list().await.is_empty());
        handle.shutdown().await;
    }

    #[tokio::test(start_paused = true)]
    async fn writer_coalesces_a_burst_into_one_write() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(&paths.home).unwrap();
        let (events, _keep) = crate::bus::test_bus(64);
        let supervisor = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();
        let app = normalize(AppConfig::minimal("web", "./srv")).unwrap();
        registry.record(std::slice::from_ref(&app));
        supervisor.start(vec![app]).await.unwrap();

        // Subscribing here means the start's own events are already behind us.
        let writer = spawn_snapshot_writer(
            paths.snapshot.clone(),
            supervisor.clone(),
            registry,
            events.subscribe(),
        );
        for event in [
            ProcessEventKind::Exit,
            ProcessEventKind::Restart,
            ProcessEventKind::Online,
        ] {
            events
                .send(
                    BusEvent::Process {
                        event,
                        info: info(0, "web", ProcStatus::Online),
                        manually: false,
                        at_ms: 0,
                    }
                    .into(),
                )
                .unwrap();
        }
        tokio::time::sleep(Duration::from_millis(SNAPSHOT_DEBOUNCE_MS + 1)).await;

        assert_eq!(writer.writes(), 1, "one debounce window is one write");
        let roll = read(&paths.snapshot).unwrap();
        assert_eq!(roll.apps.len(), 1);
        assert_eq!(roll.apps[0].instances_running, 1);
        writer.stop().await;
    }

    /// fails if the bus is the writer's only schedule. A config write that
    /// parks a field moves no process, so it publishes no
    /// [`BusEvent::Process`], and the registry's own recording is the roll's
    /// only route to disk before the next unrelated lifecycle event or a
    /// graceful shutdown.
    #[tokio::test(start_paused = true)]
    async fn writer_schedules_a_write_for_a_recording_the_bus_says_nothing_about() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(&paths.home).unwrap();
        let (events, _keep) = crate::bus::test_bus(64);
        let supervisor = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()]),
            paths.clone(),
            events.clone(),
        );
        let registry = FlockRegistry::new();
        let app = normalize(AppConfig::minimal("web", "./srv")).unwrap();
        supervisor.start(vec![app.clone()]).await.unwrap();

        // Subscribing here means the start's own events are already behind us,
        // so the bus has nothing left to say about this flock.
        let writer = spawn_snapshot_writer(
            paths.snapshot.clone(),
            supervisor.clone(),
            registry.clone(),
            events.subscribe(),
        );
        assert!(!paths.snapshot.exists(), "nothing has recorded yet");

        registry.record(std::slice::from_ref(&app));
        tokio::time::sleep(Duration::from_millis(SNAPSHOT_DEBOUNCE_MS + 1)).await;

        assert_eq!(writer.writes(), 1, "a recording leaves the roll dirty");
        let roll = read(&paths.snapshot).unwrap();
        assert_eq!(roll.apps.len(), 1);
        writer.stop().await;
    }

    #[tokio::test(start_paused = true)]
    async fn writer_ignores_log_traffic() {
        let dir = tempfile::tempdir().unwrap();
        let paths = test_paths(&dir);
        std::fs::create_dir_all(&paths.home).unwrap();
        let (events, _keep) = crate::bus::test_bus(64);
        let supervisor = spawn_supervisor(
            ScriptedRunner::new(vec![ProcScript::never_exits()]),
            paths.clone(),
            events.clone(),
        );
        let writer = spawn_snapshot_writer(
            paths.snapshot.clone(),
            supervisor,
            FlockRegistry::new(),
            events.subscribe(),
        );
        for id in 0..50 {
            events
                .send(
                    BusEvent::LogOut {
                        id,
                        line: "chatty".to_string(),
                    }
                    .into(),
                )
                .unwrap();
        }
        tokio::time::sleep(Duration::from_millis(SNAPSHOT_DEBOUNCE_MS * 4)).await;
        assert_eq!(writer.writes(), 0, "log lines must never rewrite the roll");
        assert!(!paths.snapshot.exists());
        writer.stop().await;
    }
}