shep 0.1.2

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

use std::collections::HashMap;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::Path;

use futures_util::FutureExt;
use serde::Serialize;

use shep_client::{Client, EventStream, Lagged};
use shep_core::protocol::{BusEvent, ProcessInfo, Request, Response};
use shep_core::selector::ProcessSelector;

use crate::cli::{BleatsArgs, Format};
use crate::commands::selector::parse_selector;
use crate::exit::ExitCode;
use crate::output::{self, Streams, write_outcome};

/// One line of `bleats` output under `--format json` — a stability surface
/// of its own (Task 12's fixture), deliberately not wrapped in
/// [`output::OutputEnvelope`]: see this module's own doc for why.
#[derive(Debug, Serialize)]
struct BleatLine<'a> {
    /// [`output::SCHEMA_VERSION`] at the time this line was produced.
    schema_version: u32,
    /// The sheep's id.
    id: u32,
    /// The sheep's name if the initial listing resolved it, else the bare
    /// id rendered as a string.
    name: &'a str,
    /// Which of a sheep's two output streams this line came from.
    stream: &'static str,
    /// The line itself, no trailing newline.
    line: &'a str,
}

/// Issues the one `Request::ListFlock` `bleats` sends, before it ever
/// subscribes, and turns the answer into an id -> [`ProcessInfo`] cache.
///
/// # Errors
/// Renders and returns the exit code for a request that failed to reach
/// the daemon, or a response this client does not recognise (`Response` is
/// `#[non_exhaustive]`, Global Constraints).
async fn resolve_names(
    client: &Client,
    streams: &mut Streams<'_>,
) -> Result<HashMap<u32, ProcessInfo>, ExitCode> {
    match client.request(Request::ListFlock).await {
        Ok(Response::Flock(procs)) => Ok(procs.into_iter().map(|p| (p.id, p)).collect()),
        Ok(_unrecognised) => {
            let message = "the daemon answered with a response this client does not understand";
            Err(streams.fail(ExitCode::Internal, message))
        }
        Err(err) => {
            let code = ExitCode::from(&err);
            Err(streams.fail(code, &err.to_string()))
        }
    }
}

/// Subscribes to every topic `bleats` needs: `log.*` for the lines
/// themselves, `daemon.*` so a `BusEvent::DaemonShutdown` is observed
/// rather than the connection simply vanishing unexplained.
///
/// # Errors
/// Renders and returns the exit code for a subscribe request that failed.
async fn subscribe(client: &Client, streams: &mut Streams<'_>) -> Result<EventStream, ExitCode> {
    let topics = vec!["log.*".to_string(), "daemon.*".to_string()];
    match client.subscribe(topics).await {
        Ok(stream) => Ok(stream),
        Err(err) => {
            let code = ExitCode::from(&err);
            Err(streams.fail(code, &err.to_string()))
        }
    }
}

/// Resolves `id` to a name from `cache`, or the bare id if `id` was not in
/// the one listing `resolve_names` took — an id that shows up on the bus
/// later than that snapshot is not a reason to block on a second listing.
fn resolved_name(cache: &HashMap<u32, ProcessInfo>, id: u32) -> String {
    cache
        .get(&id)
        .map_or_else(|| id.to_string(), |info| info.name.clone())
}

/// Whether `selector` (parsed client-side) admits `id`, matched against
/// `cache`'s snapshot of that sheep if it has one.
///
/// An id the initial listing never saw has no name or fold to match
/// against; it is matched with an empty name and no fold, which is enough
/// for `all` and for `ProcessSelector::Id` (both work without identity)
/// while a name/regex/fold selector correctly excludes it — there is
/// nothing to prove it belongs.
fn selector_allows(selector: &ProcessSelector, cache: &HashMap<u32, ProcessInfo>, id: u32) -> bool {
    match cache.get(&id) {
        Some(info) => selector.matches(&info.name, info.id, info.fold.as_deref()),
        None => selector.matches("", id, None),
    }
}

/// Writes one rendered line to `out`. `stream` is `"out"` or `"err"` — the
/// sheep stream the line came from, not `out`'s own identity: every line
/// this function is called with lands on [`Streams::out`], per this
/// module's own doc.
fn write_line(
    out: &mut dyn io::Write,
    fmt: Format,
    id: u32,
    name: &str,
    stream: &'static str,
    line: &str,
) -> io::Result<()> {
    match fmt {
        Format::Json => {
            let payload = BleatLine {
                schema_version: output::SCHEMA_VERSION,
                id,
                name,
                stream,
                line,
            };
            serde_json::to_writer(&mut *out, &payload)?;
            writeln!(out)
        }
        Format::Table => writeln!(out, "{name} | {line}"),
    }
}

/// Writes one of this module's own notices — not a sheep's line, and not
/// `parse_selector`'s kind of usage error either — to `streams.err`, through
/// [`output::emit_notice`] rather than [`output::emit_error`]: a notice's
/// code (`log_path_unknown`, `dropped`, `daemon_shutdown`, ...) is not part
/// of [`crate::exit::ExitCode`]'s taxonomy, and a clean run can still emit
/// one on its way to exit 0 — reusing the error envelope would leave a
/// `--format json` consumer unable to tell a diagnostic from a failure
/// (whole-branch review item 4; `cli_e2e.rs`'s `assert_json_error` pins the
/// opposite rule for real errors: JSON on stderr means the command failed).
///
/// A no-op when `quiet` is set: `--quiet`'s own doc
/// (`cli::GlobalArgs::quiet`, "suppress non-essential output") is exactly
/// what a notice is — a sheep's own line and a real error both still print
/// regardless (whole-branch review item 2).
/// One of `bleats`' own notices, unless `--quiet` asked for silence.
///
/// Kept as a wrapper rather than folded into [`Streams::aside`] because the
/// `quiet` gate is this verb's, not every verb's: `bleats` is the one command
/// an operator leaves running, so its own asides are the ones worth being
/// able to switch off without losing a sheep's output.
fn write_notice(streams: &mut Streams<'_>, quiet: bool, code: &str, message: &str) {
    if quiet {
        return;
    }
    streams.aside(code, message);
}

/// The most of one log file a tail will read to find the lines it wants.
///
/// Binds only when lines average over 5 KiB, so in ordinary use the caller's
/// line count is the bound that decides. A line count alone cannot bound
/// memory on its own — one arbitrarily long line with no newline would
/// defeat it — hence both bounds.
const TAIL_WINDOW_BYTES: u64 = 256 * 1024;

/// The last `limit` lines of one log file, bounded twice over: a
/// [`TAIL_WINDOW_BYTES`] window from the end of the file, then `limit` once
/// that window is split into lines.
///
/// Returns the lines and whether EITHER bound was what cut them short — the
/// caller needs to tell "this is all of it" from "this is not", and
/// `whistle`'s `tail_bleats` (`crate::whistle::read`) surfaces that to a
/// model as `BleatTail::truncated`. A model that cannot tell the two apart
/// concludes a busy app went quiet. The line cap and the byte window are
/// both real ways to lose the older half of a log — a sheep logging long
/// structured lines fills [`TAIL_WINDOW_BYTES`] in under `limit` lines — so
/// a caller that only asked the line cap would report `false` on a tail
/// that is, in fact, not the whole story.
///
/// `limit` is a parameter rather than a constant because the callers each
/// have their own answer: [`tail_log_files`] passes `--lines`, and `whistle`
/// passes its own clamped `lines`.
///
/// `std::fs`, not `tokio::fs`: shep-cli's tokio does not carry the `fs`
/// feature, and this is a bounded read on a one-shot command with nothing
/// else on the runtime.
///
/// A window boundary can land mid-line. When the seek away from the start
/// of the file was non-zero, the bytes up to and including the first `\n`
/// in the window are discarded rather than rendered as a fragment — half a
/// line shown as a whole one is a lie. The remaining bytes are decoded with
/// [`String::from_utf8_lossy`]: a log file is whatever the child wrote and
/// is under no obligation to be UTF-8, and refusing to show a log over one
/// bad byte is the wrong failure.
///
/// # Errors
/// The file could not be opened, `stat`ed, seeked, or read. Notably
/// includes [`io::ErrorKind::NotFound`] (the sheep has never run in this
/// `$SHEP_HOME`) and `EISDIR` (`out_file`/`err_file` named a directory) —
/// [`tail_log_files`] gives the two different treatment.
pub(crate) fn read_tail(path: &Path, limit: usize) -> io::Result<(Vec<String>, bool)> {
    let mut file = std::fs::File::open(path)?;
    let len = file.metadata()?.len();
    let start = len.saturating_sub(TAIL_WINDOW_BYTES);
    // `start > 0` means the byte window itself left content behind, before
    // a single line has been counted — the file is bigger than the window.
    let window_truncated = start > 0;
    if start > 0 {
        file.seek(SeekFrom::Start(start))?;
    }

    let mut window = Vec::new();
    file.read_to_end(&mut window)?;

    let window: &[u8] = if start > 0 {
        match window.iter().position(|&b| b == b'\n') {
            Some(newline) => &window[newline + 1..],
            None => &[],
        }
    } else {
        &window
    };

    let text = String::from_utf8_lossy(window);
    let mut lines: Vec<String> = text.split('\n').map(String::from).collect();
    if lines.last().is_some_and(String::is_empty) {
        lines.pop();
    }
    let keep_from = lines.len().saturating_sub(limit);
    let truncated = window_truncated || keep_from > 0;
    lines.drain(..keep_from);
    Ok((lines, truncated))
}

/// Renders the selected files of every sheep the selector admits, in id
/// order, and returns the exit code that reports how that went.
///
/// Within one sheep, `out_file` (unless `--err`) prints before `err_file`
/// (unless `--out`) — this module's own doc states the ordering limitation
/// that follows from it. Ids are sorted before anything is read: `cache` is
/// a `HashMap`, whose iteration order is not the id order this command's
/// `--format json` output is pinned against.
///
/// A `None` path means the shepherd predates the field (module doc,
/// [`shep_core::protocol::ProcessInfo::out_file`]) — one `log_path_unknown`
/// notice per path the flags actually asked for, exit code unaffected. A
/// missing file ([`io::ErrorKind::NotFound`]) is silent: the daemon creates
/// both files at spawn, so a missing one means this sheep has never run in
/// this `$SHEP_HOME`, and a notice per quiet sheep would spam stderr on a
/// fresh flock. Any other read failure is one `log_unreadable` notice naming
/// the path and the OS error, and the rest of the flock still prints — only
/// this last case sets the final [`ExitCode::Failure`].
fn tail_log_files(
    streams: &mut Streams<'_>,
    quiet: bool,
    cache: &HashMap<u32, ProcessInfo>,
    selector: &ProcessSelector,
    args: &BleatsArgs,
) -> ExitCode {
    let mut matched: Vec<&ProcessInfo> = cache
        .values()
        .filter(|info| selector.matches(&info.name, info.id, info.fold.as_deref()))
        .collect();
    matched.sort_unstable_by_key(|info| info.id);

    let mut failure = false;

    for info in matched {
        let name = &info.name;
        let wanted: [(&'static str, Option<&str>, bool); 2] = [
            ("out", info.out_file.as_deref(), !args.err),
            ("err", info.err_file.as_deref(), !args.out),
        ];
        for (stream_name, path, show) in wanted {
            if !show {
                continue;
            }
            match path {
                None => write_notice(
                    streams,
                    quiet,
                    "log_path_unknown",
                    &format!("{name}: the daemon did not report a {stream_name} log path"),
                ),
                Some(path) => match read_tail(Path::new(path), args.lines) {
                    Ok((lines, _truncated)) => {
                        for line in lines {
                            if let Err(write_err) = write_line(
                                streams.out,
                                streams.fmt,
                                info.id,
                                name,
                                stream_name,
                                &line,
                            ) {
                                let code = write_outcome(Err(write_err));
                                let _ = streams.out.flush();
                                return code;
                            }
                        }
                    }
                    Err(err) if err.kind() == io::ErrorKind::NotFound => {
                        // Silent: the daemon creates both files at spawn, so
                        // a missing file means this sheep has never run in
                        // this $SHEP_HOME. A notice per quiet sheep would
                        // spam stderr on a fresh flock.
                    }
                    Err(err) => {
                        failure = true;
                        write_notice(
                            streams,
                            quiet,
                            "log_unreadable",
                            &format!("failed to read {path}: {err}"),
                        );
                    }
                },
            }
        }
    }

    let _ = streams.out.flush();
    if failure {
        ExitCode::Failure
    } else {
        ExitCode::Success
    }
}

/// Handles one [`BusEvent`] already known to be `Ok` (a `Lagged` item is
/// handled by the caller, not here).
///
/// `BusEvent` is `#[non_exhaustive]`: the `_` arm ignores anything this
/// client does not recognise, silently — a follow must not die on a bus
/// event a newer daemon added (Global Constraints). `Dropped` is NOT one of
/// those unrecognised events — it is a real, named variant this client
/// understands — so it gets its own arm rather than falling into that `_`.
fn handle_event(
    streams: &mut Streams<'_>,
    quiet: bool,
    cache: &HashMap<u32, ProcessInfo>,
    selector: &ProcessSelector,
    args: &BleatsArgs,
    event: BusEvent,
) -> io::Result<()> {
    match event {
        BusEvent::LogOut { id, line } => {
            if !args.err && selector_allows(selector, cache, id) {
                let name = resolved_name(cache, id);
                write_line(streams.out, streams.fmt, id, &name, "out", &line)?;
            }
            Ok(())
        }
        BusEvent::LogErr { id, line } => {
            if !args.out && selector_allows(selector, cache, id) {
                let name = resolved_name(cache, id);
                write_line(streams.out, streams.fmt, id, &name, "err", &line)?;
            }
            Ok(())
        }
        BusEvent::Dropped { count } => {
            // Daemon-side cause, deliberately NOT the `Lagged` arm's
            // wording below: `Dropped` is the daemon's own outbound queue
            // overflowing for this subscriber, while `Lagged` is this
            // client's receiver falling behind reading its socket. The two
            // failures live on opposite sides of the connection and must
            // read differently, or a user cannot tell which end to
            // investigate.
            write_notice(
                streams,
                quiet,
                "dropped",
                &format!("the daemon dropped {count} events (its own queue overflowed)"),
            );
            Ok(())
        }
        BusEvent::DaemonShutdown => {
            // Shep's own diagnostic, not a sheep's line: `streams.err`.
            write_notice(
                streams,
                quiet,
                "daemon_shutdown",
                "the daemon is shutting down",
            );
            Ok(())
        }
        _ => Ok(()),
    }
}

/// Follows the bleats (log output) of the sheep matching `args.selector`.
///
/// `quiet` is `cli::GlobalArgs::quiet` — it silences this module's own
/// notices (whole-branch review item 2) and nothing else: a sheep's own
/// line and a real error both still print regardless.
///
/// Delegates to [`bleats_with_signal`] with a real `SIGINT` as the
/// interrupt source — see that function's own doc for the shape both
/// share.
pub async fn bleats(
    client: &Client,
    streams: &mut Streams<'_>,
    quiet: bool,
    args: &BleatsArgs,
) -> ExitCode {
    bleats_with_signal(
        client,
        streams,
        quiet,
        args,
        tokio::signal::ctrl_c().map(|_| ()),
    )
    .await
}

/// [`bleats`] with the interrupt injected, so the Ctrl-C branch has a test
/// that does not need a real `SIGINT` — one would kill the test runner.
///
/// One `Request::ListFlock` always goes out first, building the id -> name
/// cache both paths share.
///
/// **`--no-follow`** (`args.no_follow`) stops there and hands off to
/// [`tail_log_files`]: it never issues `Request::Subscribe`, so there is no
/// stream, no `Lagged`, no `DaemonShutdown`, and nothing for `interrupt` to
/// race — a bounded file read terminates on its own.
///
/// **`--follow`** (the default) subscribes (`log.*`/`daemon.*`) and loops
/// over one `tokio::select!` with two arms, checked in this priority order
/// every iteration:
///
/// 1. The event stream — a normal line is rendered, a `Lagged` item is
///    noted to `streams.err` and the follow continues, and the stream
///    ending (`None`) means the daemon is gone: flush and exit
///    [`ExitCode::DaemonUnreachable`].
/// 2. `interrupt` — a user ending a follow deliberately has not failed:
///    flush and exit [`ExitCode::Success`].
///
/// `streams.out` is flushed on every exit path — a follow that ends with
/// lines still buffered would otherwise lose them silently.
pub async fn bleats_with_signal(
    client: &Client,
    streams: &mut Streams<'_>,
    quiet: bool,
    args: &BleatsArgs,
    interrupt: impl std::future::Future<Output = ()> + Send,
) -> ExitCode {
    let selector = match parse_selector(streams, &args.selector) {
        Ok(selector) => selector,
        Err(code) => return code,
    };

    // Order matters: the id/name cache is built from ONE listing taken
    // before subscribing. Subscribing first would lose every line pushed
    // while the listing is still in flight.
    let cache = match resolve_names(client, streams).await {
        Ok(cache) => cache,
        Err(code) => return code,
    };

    if args.no_follow {
        return tail_log_files(streams, quiet, &cache, &selector, args);
    }

    // The backlog first, then the stream. Following alone shows only what
    // arrives next, so a sheep that already died printed an empty screen
    // while the reason sat in its log file -- which is how a boot-looping
    // sheep came to look like it had logged nothing at all.
    //
    // Read before subscribing rather than after, so a line written in the
    // gap between the two is missed rather than printed twice. Neither is
    // free; a duplicate is the one a reader would notice and mistrust. The
    // same trade is already made just above, where the id/name cache is
    // built from a listing taken before the subscription.
    //
    // The tail's own exit code is deliberately discarded: an unreadable log
    // for one sheep must not stop a follow over the whole flock, and a
    // failed write to stdout will fail again in the loop below, where it is
    // handled properly.
    if args.lines > 0 {
        let _ = tail_log_files(streams, quiet, &cache, &selector, args);
    }

    let mut stream = match subscribe(client, streams).await {
        Ok(stream) => stream,
        Err(code) => return code,
    };

    tokio::pin!(interrupt);

    loop {
        tokio::select! {
            biased;
            item = stream.next() => {
                match item {
                    Some(Ok(event)) => {
                        if let Err(write_err) =
                            handle_event(streams, quiet, &cache, &selector, args, event)
                        {
                            let code = write_outcome(Err(write_err));
                            let _ = streams.out.flush();
                            return code;
                        }
                    }
                    Some(Err(Lagged { count })) => {
                        write_notice(
                            streams,
                            quiet,
                            "lagged",
                            &format!("{count} events dropped locally (lagged)"),
                        );
                    }
                    None => {
                        let _ = streams.out.flush();
                        return ExitCode::DaemonUnreachable;
                    }
                }
            }
            () = &mut interrupt => {
                let _ = streams.out.flush();
                return ExitCode::Success;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use shep_client::testing::fake_client_with_push;
    use shep_core::protocol::ProcessInfo;
    use shep_core::status::ProcStatus;

    use super::*;
    use crate::cli::{Cli, Commands};

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

    fn bleats_args(selector: &str, no_follow: bool, err: bool, out: bool) -> BleatsArgs {
        BleatsArgs {
            selector: selector.to_string(),
            no_follow,
            // The tail default is exercised by its own tests below. The
            // follow tests here predate the backlog and assert on what the
            // BUS delivers, so they ask for no history and keep testing
            // exactly what they were written to test.
            lines: crate::cli::DEFAULT_BLEAT_LINES,
            err,
            out,
        }
    }

    fn follow_args(selector: &str) -> BleatsArgs {
        BleatsArgs {
            lines: 0,
            ..bleats_args(selector, false, false, false)
        }
    }

    fn follow_args_err(selector: &str) -> BleatsArgs {
        bleats_args(selector, false, true, false)
    }

    fn follow_args_out(selector: &str) -> BleatsArgs {
        bleats_args(selector, false, false, true)
    }

    fn no_follow_args(selector: &str) -> BleatsArgs {
        bleats_args(selector, true, false, false)
    }

    fn no_follow_args_err(selector: &str) -> BleatsArgs {
        bleats_args(selector, true, true, false)
    }

    fn no_follow_args_out(selector: &str) -> BleatsArgs {
        bleats_args(selector, true, false, true)
    }

    /// Writes `content` to `dir/name` and returns the path as a `String` —
    /// what a scripted [`ProcessInfo`]'s `out_file`/`err_file` needs.
    fn write_log(dir: &Path, name: &str, content: &str) -> String {
        let path = dir.join(name);
        std::fs::write(&path, content).unwrap();
        path.to_str().unwrap().to_string()
    }

    #[test]
    fn no_follow_parses_and_plain_bleats_still_follows() {
        use clap::Parser;

        let Commands::Bleats(args) = Cli::try_parse_from(["shep", "bleats"]).unwrap().command
        else {
            panic!()
        };
        assert!(!args.no_follow, "the default is to follow");

        let Commands::Bleats(args) = Cli::try_parse_from(["shep", "bleats", "--no-follow"])
            .unwrap()
            .command
        else {
            panic!()
        };
        assert!(args.no_follow);

        // The flag stores NO value: `--no-follow` is `ArgAction::SetTrue`, so a
        // following token is not consumed by it and lands on the positional
        // instead.
        let Commands::Bleats(args) = Cli::try_parse_from(["shep", "bleats", "--no-follow", "true"])
            .unwrap()
            .command
        else {
            panic!()
        };
        assert!(args.no_follow);
        assert_eq!(
            args.selector, "true",
            "--no-follow takes no value; the token is the selector"
        );
    }

    /// Every `bleats(...)`/`bleats_with_signal(...)` call in this module is
    /// bounded by this timeout — a broken implementation that hangs (e.g. a
    /// drain that never terminates, or a follow that never observes an
    /// interrupt) fails with a named assertion instead of a killed CI job
    /// (Global Constraints: nine tests have already shipped that fail only
    /// by hanging).
    const RUN_TIMEOUT: Duration = Duration::from_secs(5);

    /// `daemon.close_after_subscribe()` — not `daemon.close()` — ends the
    /// connection right after the real `Subscribe` this test's `bleats`
    /// call issues has been served and anything queued via `push` has been
    /// flushed. That is what makes this test scheduler-independent: unlike
    /// the old `--no-follow` drain arm (retired by the amendment that reads
    /// log files instead), a follow that runs to end-of-stream observes
    /// everything pushed before the close, in order, on any executor —
    /// there is no longer a race between "the events arrived" and "the loop
    /// decided nothing was buffered".
    #[tokio::test]
    async fn ids_resolve_to_names_from_one_listing_and_unknown_ids_render_bare() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon
            .push(BusEvent::LogOut {
                id: 1,
                line: "hello".into(),
            })
            .await;
        daemon
            .push(BusEvent::LogOut {
                id: 9,
                line: "orphan".into(),
            })
            .await;
        daemon.close_after_subscribe().await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("all")),
            )
            .await
            .expect("close_after_subscribe ends the follow deterministically, not by hanging");
        }
        let out = String::from_utf8(out).unwrap();

        assert!(out.contains("web") && out.contains("hello"));
        assert!(
            out.contains('9') && out.contains("orphan"),
            "an unknown id renders bare, not blocked on: {out}"
        );
        assert_eq!(
            daemon.list_flock_count(),
            1,
            "one listing, not one per unknown line"
        );
    }

    /// Same `close_after_subscribe` reasoning as the test above.
    #[tokio::test]
    async fn err_and_out_filter_the_two_streams() {
        for (args, kept, gone) in [
            (follow_args_err("all"), "to-stderr", "to-stdout"),
            (follow_args_out("all"), "to-stdout", "to-stderr"),
        ] {
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("s.sock");
            let (client, daemon) = fake_client_with_push(&path).await;
            daemon.reply_to_list(vec![info(1, "web")]);
            daemon
                .push(BusEvent::LogOut {
                    id: 1,
                    line: "to-stdout".into(),
                })
                .await;
            daemon
                .push(BusEvent::LogErr {
                    id: 1,
                    line: "to-stderr".into(),
                })
                .await;
            daemon.close_after_subscribe().await;

            let mut out = Vec::new();
            let mut err = Vec::new();
            {
                let mut streams = Streams {
                    out: &mut out,
                    err: &mut err,
                    style: crate::style::Presentation::BARE,
                    fmt: Format::Table,
                };
                tokio::time::timeout(RUN_TIMEOUT, bleats(&client, &mut streams, false, &args))
                    .await
                    .expect(
                        "close_after_subscribe ends the follow deterministically, not by hanging",
                    );
            }
            let rendered = String::from_utf8(out).unwrap();
            assert!(
                rendered.contains(kept),
                "{kept} should have survived: {rendered}"
            );
            assert!(
                !rendered.contains(gone),
                "{gone} should have been filtered: {rendered}"
            );
        }
    }

    /// The daemon's topic filter globs on `log.out` / `log.err`, which carry
    /// no identity — so this filtering CANNOT have happened server-side,
    /// and a test that let the fake daemon pre-filter would prove nothing.
    /// Same `close_after_subscribe` reasoning as the test above.
    #[tokio::test]
    async fn a_selector_filters_client_side_on_the_resolved_id_set() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web"), info(2, "worker")]);
        // The fake queues BOTH; only the selector may narrow them.
        daemon
            .push(BusEvent::LogOut {
                id: 1,
                line: "from-web".into(),
            })
            .await;
        daemon
            .push(BusEvent::LogOut {
                id: 2,
                line: "from-worker".into(),
            })
            .await;
        daemon.close_after_subscribe().await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("web")),
            )
            .await
            .expect("close_after_subscribe ends the follow deterministically, not by hanging");
        }
        let out = String::from_utf8(out).unwrap();

        assert!(out.contains("from-web"));
        assert!(
            !out.contains("from-worker"),
            "the selector must narrow the resolved id set: {out}"
        );
    }

    /// The stream stays open for the whole test — the fake is never closed
    /// — so the ONLY thing that can end this follow is the injected
    /// interrupt. A `bleats` that ignored the interrupt arm hangs and the
    /// timeout fails it.
    #[tokio::test]
    async fn ctrl_c_during_a_follow_exits_success() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon
            .push(BusEvent::LogOut {
                id: 1,
                line: "still running".into(),
            })
            .await;

        let (interrupt_tx, interrupt_rx) = tokio::sync::oneshot::channel::<()>();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let mut streams = Streams {
            out: &mut out,
            err: &mut err,
            style: crate::style::Presentation::BARE,
            fmt: Format::Table,
        };

        let args = follow_args("all");
        let follow = bleats_with_signal(&client, &mut streams, false, &args, async {
            let _ = interrupt_rx.await;
        });
        let (_, code) = tokio::join!(
            async {
                tokio::task::yield_now().await;
                let _ = interrupt_tx.send(()); // a oneshot stays ready once sent
            },
            tokio::time::timeout(RUN_TIMEOUT, follow),
        );
        assert_eq!(
            code.expect("the interrupt arm must end the follow"),
            ExitCode::Success,
            "a user ending a follow deliberately has not failed"
        );
    }

    /// The pair that makes the shutdown branch bite. Both end in
    /// `DaemonUnreachable` — the daemon went away either way — so the exit
    /// code alone discriminates nothing. The NOTICE is the behaviour under
    /// test: a `bleats` that never matches `BusEvent::DaemonShutdown` and
    /// just maps any end-of-stream to `DaemonUnreachable` passes the first
    /// assertion of each and fails the stderr assertion of the first.
    ///
    /// `close_after_subscribe`, not `close()`: this test genuinely needs
    /// the connection to end mid-follow (there is no interrupt here, and
    /// `follow_args` never terminates on its own), and `close_after_subscribe`
    /// ends it deterministically, right after the real `Subscribe` this
    /// test's `bleats` call issues has been served.
    #[tokio::test]
    async fn a_daemon_shutdown_mid_follow_is_announced_before_the_stream_ends() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon.push(BusEvent::DaemonShutdown).await; // scripted: emitted after Subscribe
        daemon.close_after_subscribe().await; // scripted: after Subscribe is served

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("all")),
            )
            .await
            .expect("a shutdown mid-follow must end the follow, not hang")
        };

        assert_eq!(code, ExitCode::DaemonUnreachable);
        assert!(
            String::from_utf8(err).unwrap().contains("shutting down"),
            "the shutdown notice is what distinguishes this from the connection simply ending"
        );
    }

    /// Same `close_after_subscribe` usage as the test above, and for the
    /// same reason.
    #[tokio::test]
    async fn a_stream_that_just_ends_reports_no_shutdown_notice() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon.close_after_subscribe().await; // no DaemonShutdown event at all

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("all")),
            )
            .await
            .expect("the connection ending must end the follow, not hang")
        };

        assert_eq!(code, ExitCode::DaemonUnreachable);
        assert!(
            !String::from_utf8(err).unwrap().contains("shutting down"),
            "a notice the daemon never sent must not be invented"
        );
    }

    /// Whole-branch review item 2: `--quiet` (`GlobalArgs::quiet`, threaded
    /// in here as `bleats`' own `quiet` parameter) must actually do
    /// something, and this module's notices are what it was given meaning
    /// against. Same shutdown scenario as
    /// `a_daemon_shutdown_mid_follow_is_announced_before_the_stream_ends`,
    /// with `quiet: true` instead of `false` — the exit code must not move
    /// (the daemon really did go away either way), only the notice text.
    #[tokio::test]
    async fn quiet_suppresses_the_daemon_shutdown_notice_but_not_the_exit_code() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon.push(BusEvent::DaemonShutdown).await;
        daemon.close_after_subscribe().await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, true, &follow_args("all")),
            )
            .await
            .expect("a shutdown mid-follow must end the follow, not hang")
        };

        assert_eq!(
            code,
            ExitCode::DaemonUnreachable,
            "quiet must not change the exit code, only whether the notice prints"
        );
        assert!(
            String::from_utf8(err).unwrap().is_empty(),
            "quiet must suppress the shutdown notice entirely"
        );
    }

    /// The other half of `--quiet`'s contract: it narrows notices only.
    /// `resolved_name`/`write_line` never see `quiet` at all (their call
    /// sites are unconditional in `handle_event`), so this is a
    /// belt-and-braces end-to-end check that a sheep's own line still
    /// reaches `streams.out` under `quiet: true`.
    #[tokio::test]
    async fn quiet_does_not_suppress_a_sheeps_own_line() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon
            .push(BusEvent::LogOut {
                id: 1,
                line: "hello".into(),
            })
            .await;
        daemon.close_after_subscribe().await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, true, &follow_args("all")),
            )
            .await
            .expect("close_after_subscribe ends the follow deterministically, not by hanging");
        }
        let out = String::from_utf8(out).unwrap();
        assert!(
            out.contains("web") && out.contains("hello"),
            "quiet must never touch a sheep's own line: {out}"
        );
    }

    /// Same `close_after_subscribe` reasoning as
    /// `ids_resolve_to_names_from_one_listing_and_unknown_ids_render_bare` —
    /// but unlike that test, this one is **not** scheduler-independent, for
    /// a different reason than the drain arm the amendment retired.
    ///
    /// **Verified, current known limitation**: run 10/10 in isolation under
    /// `#[tokio::test(flavor = "multi_thread")]`, this test fails 10/10 —
    /// `stderr` comes back empty, meaning `overrun_by`'s forced lag never
    /// happens. `overrun_by` pushes `EVENT_CHANNEL_CAPACITY + n` events that
    /// the fake flushes onto the wire in one burst right after `Subscribe`;
    /// a `Lagged` only appears if this test's own `EventStream` falls behind
    /// that burst by more than `EVENT_CHANNEL_CAPACITY` before it drains any
    /// of it. Under the default current-thread runtime that reliably
    /// happens: the connection actor decodes the whole burst in one
    /// uninterrupted turn before this test's task gets scheduled again.
    /// Under `multi_thread`, real parallelism lets this test's receiver keep
    /// pace with the actor as events arrive, so the backlog never crosses
    /// `EVENT_CHANNEL_CAPACITY` and no lag is ever produced. The other six
    /// tests converted alongside this one all pass 10/10 in the same
    /// isolated check — this is `overrun_by`'s own timing dependency, not a
    /// symptom of the retired drain arm, and forcing a deterministic lag
    /// would need a synchronization point `FakeDaemon` does not have today.
    #[tokio::test]
    async fn a_lag_notice_reaches_stderr_and_the_follow_continues() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon.overrun_by(8).await; // forces a Lagged item
        daemon
            .push(BusEvent::LogOut {
                id: 1,
                line: "after".into(),
            })
            .await;
        daemon.close_after_subscribe().await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("all")),
            )
            .await
            .expect("close_after_subscribe ends the follow deterministically, not by hanging");
        }

        let stderr = String::from_utf8(err).unwrap();
        assert!(
            stderr.contains("dropped") || stderr.contains("lagged"),
            "a lag must be told, not swallowed: {stderr}"
        );
        assert!(
            String::from_utf8(out).unwrap().contains("after"),
            "a lag ends the gap, not the follow"
        );
    }

    /// Critical fix (item 1): `BusEvent::Dropped` used to fall into
    /// `handle_event`'s `_ => Ok(())` catch-all and vanish — the daemon's
    /// own outbound queue overflowing is exactly the "a sheep went quiet"
    /// failure mode this module's doc warns against swallowing silently.
    ///
    /// `Dropped` (the daemon's queue) and `Lagged` (this client's own
    /// receiver falling behind) are different causes and must read
    /// differently, so this asserts the daemon-side wording specifically —
    /// `stderr.contains("dropped")` alone would also pass if the `Lagged`
    /// arm's wording were reused by mistake, which is exactly the bug this
    /// test exists to catch.
    ///
    /// Same `close_after_subscribe` reasoning as
    /// `ids_resolve_to_names_from_one_listing_and_unknown_ids_render_bare`.
    #[tokio::test]
    async fn a_dropped_notice_reaches_stderr_worded_for_the_daemon_side_cause() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon.push(BusEvent::Dropped { count: 5 }).await;
        daemon.close_after_subscribe().await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("all")),
            )
            .await
            .expect("close_after_subscribe ends the follow deterministically, not by hanging");
        }

        let stderr = String::from_utf8(err).unwrap();
        assert!(
            stderr.contains("daemon") && stderr.contains('5'),
            "a daemon-side Dropped must not be silently swallowed: {stderr}"
        );
        assert!(
            !stderr.contains("locally"),
            "Dropped is the daemon's queue overflowing, not this client \
             falling behind reading its own socket — reusing the `Lagged` \
             arm's wording would blame the wrong side: {stderr}"
        );
    }

    /// Important fix (item 3): every other test in this module uses
    /// `Format::Table`, so mutating the JSON line shape (renaming a field,
    /// or rendering table rows under `--format json`) left every test green.
    /// Global Constraints pins every command's JSON shape; this is that pin
    /// for `bleats`' own line shape (deferred by the brief to a Task 12
    /// fixture, pinned independently here since item 2 puts that fixture's
    /// shape in doubt).
    ///
    /// Same `close_after_subscribe` reasoning as
    /// `ids_resolve_to_names_from_one_listing_and_unknown_ids_render_bare`.
    #[tokio::test]
    async fn json_format_renders_the_pinned_five_key_line_shape() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon
            .push(BusEvent::LogErr {
                id: 1,
                line: "boom".into(),
            })
            .await;
        daemon.close_after_subscribe().await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Json,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("all")),
            )
            .await
            .expect("close_after_subscribe ends the follow deterministically, not by hanging");
        }
        let out = String::from_utf8(out).unwrap();
        let line = out.lines().next().expect("one JSON line was rendered");
        let json: serde_json::Value = serde_json::from_str(line).unwrap();
        let obj = json.as_object().expect("a bleats JSON line is an object");
        let mut keys: Vec<&str> = obj.keys().map(String::as_str).collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            ["id", "line", "name", "schema_version", "stream"],
            "the bleats JSON line shape is a stability surface: {out}"
        );
        assert_eq!(json["stream"], "err", "the stream this line came from");
    }

    /// A writer that always fails with `BrokenPipe` — `shep bleats | head`
    /// closing the reading end is the normal way this streaming verb ends,
    /// not an error.
    struct BrokenPipeWriter;

    impl io::Write for BrokenPipeWriter {
        fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
            Err(io::Error::from(io::ErrorKind::BrokenPipe))
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// Important fix (item 5): `shep bleats | head` is this verb's normal
    /// case, not an error — `write_outcome` already treats a `BrokenPipe`
    /// write failure as [`ExitCode::Success`], but nothing in this module
    /// exercised that path through an actual write failure.
    ///
    /// `close_after_subscribe` is scripted here too, for consistency with
    /// the rest of this module's follow-mode tests, but the exit code stays
    /// `Success` regardless: the write fails on the very first event, which
    /// returns from `handle_event`'s write-error branch long before the
    /// stream could ever reach end-of-stream.
    #[tokio::test]
    async fn a_broken_pipe_while_writing_a_line_exits_success() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&path).await;
        daemon.reply_to_list(vec![info(1, "web")]);
        daemon
            .push(BusEvent::LogOut {
                id: 1,
                line: "hello".into(),
            })
            .await;
        daemon.close_after_subscribe().await;

        let mut out = BrokenPipeWriter;
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args("all")),
            )
            .await
            .expect("close_after_subscribe ends the follow deterministically, not by hanging")
        };

        assert_eq!(
            code,
            ExitCode::Success,
            "a reader closing the pipe is not a failed command"
        );
    }

    // --- Task 10a: `--no-follow` reads the log files ----------------------
    //
    // None of these subscribe: `--no-follow` never issues `Request::Subscribe`
    // at all, so there is no `daemon.close()`/`close_after_subscribe()` to
    // script and no scheduler dependence to worry about — a bounded file read
    // terminates on its own, which is exactly what `RUN_TIMEOUT` guards.

    /// A `--no-follow` still wired to the bus fails the second assertion; one
    /// wired to neither fails the first. This is the test that tells the two
    /// apart from a `--no-follow` that reads the right files.
    #[tokio::test]
    async fn no_follow_reads_the_files_and_never_the_bus() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let out_path = write_log(dir.path(), "web-out.log", "from-the-file\n");

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep = info(1, "web");
        sheep.out_file = Some(out_path);
        daemon.reply_to_list(vec![sheep]);
        daemon
            .push(BusEvent::LogOut {
                id: 1,
                line: "from-the-bus".into(),
            })
            .await;

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &no_follow_args_out("all")),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own")
        };
        let rendered = String::from_utf8(out).unwrap();

        assert_eq!(code, ExitCode::Success);
        assert!(rendered.contains("from-the-file"));
        assert!(
            !rendered.contains("from-the-bus"),
            "the file path must never consult the bus: {rendered}"
        );
    }

    /// The bug Rin hit: a sheep crashes, `shep bleats <name>` is run after
    /// the fact, and following alone prints an empty screen while the reason
    /// sits in the log file. The backlog is what makes the reason reachable
    /// without having to start the sheep again in a second window.
    #[tokio::test]
    async fn following_prints_the_existing_log_before_it_follows() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let out_path = write_log(
            dir.path(),
            "web-out.log",
            "boot: reading config\nFATAL: port 19999 already in use\n",
        );

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep = info(1, "web");
        sheep.out_file = Some(out_path);
        daemon.reply_to_list(vec![sheep]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            let _ = tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &follow_args_out("all")),
            )
            .await;
        }
        let rendered = String::from_utf8(out).unwrap();
        assert!(
            rendered.contains("FATAL: port 19999 already in use"),
            "a follow must carry the reason a dead sheep died: {rendered}"
        );
    }

    /// `--lines 0` is the escape hatch for someone who genuinely wants only
    /// what arrives next, and it is what the foreground runner passes.
    #[tokio::test]
    async fn lines_zero_follows_without_replaying_anything() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let out_path = write_log(dir.path(), "web-out.log", "OLD-HISTORY\n");

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep = info(1, "web");
        sheep.out_file = Some(out_path);
        daemon.reply_to_list(vec![sheep]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            let _ = tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(
                    &client,
                    &mut streams,
                    false,
                    &BleatsArgs {
                        lines: 0,
                        ..follow_args_out("all")
                    },
                ),
            )
            .await;
        }
        let rendered = String::from_utf8(out).unwrap();
        assert!(
            !rendered.contains("OLD-HISTORY"),
            "--lines 0 must replay nothing: {rendered}"
        );
    }

    /// A `read_to_string`-style implementation prints line 1 and fails this.
    #[tokio::test]
    async fn the_tail_is_bounded_by_lines() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        const CAP: usize = 50;
        let total = CAP + 20;
        let content: String = (1..=total).map(|n| format!("line-{n}\n")).collect();
        let out_path = write_log(dir.path(), "web-out.log", &content);

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep = info(1, "web");
        sheep.out_file = Some(out_path);
        daemon.reply_to_list(vec![sheep]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(
                    &client,
                    &mut streams,
                    false,
                    &BleatsArgs {
                        lines: CAP,
                        ..no_follow_args_out("all")
                    },
                ),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own");
        }
        let rendered = String::from_utf8(out).unwrap();

        assert!(
            !rendered.lines().any(|line| line == "web | line-1"),
            "the first line must fall outside the tail: {rendered}"
        );
        assert!(
            rendered
                .lines()
                .any(|line| line == format!("web | line-{total}")),
            "the last line must be present: {rendered}"
        );
        assert_eq!(
            rendered.lines().count(),
            CAP,
            "exactly CAP lines must reach stdout: {rendered}"
        );
    }

    /// Guards the window and the discard-the-partial-first-line rule
    /// together: an implementation that keeps the partial head emits a
    /// quarter-megabyte fragment and fails this.
    #[tokio::test]
    async fn the_tail_is_bounded_by_bytes_and_never_shows_half_a_line() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let long_line = "x".repeat(usize::try_from(TAIL_WINDOW_BYTES).unwrap() + 1024);
        let content = format!("{long_line}\nshort\n");
        let out_path = write_log(dir.path(), "web-out.log", &content);

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep = info(1, "web");
        sheep.out_file = Some(out_path);
        daemon.reply_to_list(vec![sheep]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &no_follow_args_out("all")),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own");
        }
        let rendered = String::from_utf8(out).unwrap();

        assert_eq!(
            rendered,
            "web | short\n",
            "no fragment of the long line may reach stdout ({} bytes rendered)",
            rendered.len()
        );
    }

    /// `truncated` must report `true` when the byte window is what cut the
    /// tail short, even when the line cap never binds — a sheep logging a
    /// few long, structured lines can fill `TAIL_WINDOW_BYTES` in far fewer
    /// than `limit` lines. Before this test, `read_tail` reported `false`
    /// here, and `whistle`'s `tail_bleats` handed a model exactly that
    /// wrong answer.
    #[test]
    fn read_tail_reports_truncated_on_a_byte_window_cut_alone() {
        let dir = tempfile::tempdir().unwrap();
        let long_line = "x".repeat(usize::try_from(TAIL_WINDOW_BYTES).unwrap() + 1024);
        let content = format!("{long_line}\nshort\n");
        let path = dir.path().join("web-out.log");
        std::fs::write(&path, &content).unwrap();

        let (lines, truncated) = read_tail(&path, 50).unwrap();

        assert_eq!(lines, vec!["short".to_string()]);
        assert!(
            truncated,
            "the file exceeds the byte window, so this tail is not the whole log"
        );
    }

    /// Three ways: `--out` (out lines only), `--err` (err lines only),
    /// neither (out lines, then err lines — this module's own pin on
    /// within-sheep ordering).
    #[tokio::test]
    async fn out_and_err_select_which_file_is_read() {
        async fn run(args: BleatsArgs) -> String {
            let dir = tempfile::tempdir().unwrap();
            let sock = dir.path().join("s.sock");
            let out_path = write_log(dir.path(), "web-out.log", "stdout-line\n");
            let err_path = write_log(dir.path(), "web-err.log", "stderr-line\n");

            let (client, daemon) = fake_client_with_push(&sock).await;
            let mut sheep = info(1, "web");
            sheep.out_file = Some(out_path);
            sheep.err_file = Some(err_path);
            daemon.reply_to_list(vec![sheep]);

            let mut out = Vec::new();
            let mut err = Vec::new();
            {
                let mut streams = Streams {
                    out: &mut out,
                    err: &mut err,
                    style: crate::style::Presentation::BARE,
                    fmt: Format::Table,
                };
                tokio::time::timeout(RUN_TIMEOUT, bleats(&client, &mut streams, false, &args))
                    .await
                    .expect("--no-follow never subscribes, so it must terminate on its own");
            }
            String::from_utf8(out).unwrap()
        }

        let out_only = run(no_follow_args_out("all")).await;
        assert!(out_only.contains("stdout-line") && !out_only.contains("stderr-line"));

        let err_only = run(no_follow_args_err("all")).await;
        assert!(err_only.contains("stderr-line") && !err_only.contains("stdout-line"));

        let both = run(no_follow_args("all")).await;
        let out_pos = both
            .find("stdout-line")
            .expect("the stdout line is present");
        let err_pos = both
            .find("stderr-line")
            .expect("the stderr line is present");
        assert!(
            out_pos < err_pos,
            "out_file must render before err_file within one sheep: {both}"
        );
    }

    /// Scripts the listing in DESCENDING id order, so the cache's `HashMap`
    /// iteration order cannot be what makes ascending output pass.
    #[tokio::test]
    async fn files_are_printed_in_ascending_id_order() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let a_path = write_log(dir.path(), "a-out.log", "line-from-a\n");
        let b_path = write_log(dir.path(), "b-out.log", "line-from-b\n");

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep_a = info(1, "a");
        sheep_a.out_file = Some(a_path);
        let mut sheep_b = info(2, "b");
        sheep_b.out_file = Some(b_path);
        daemon.reply_to_list(vec![sheep_b, sheep_a]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &no_follow_args_out("all")),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own");
        }
        let rendered = String::from_utf8(out).unwrap();

        let a_pos = rendered
            .find("line-from-a")
            .expect("id 1's line is present");
        let b_pos = rendered
            .find("line-from-b")
            .expect("id 2's line is present");
        assert!(
            a_pos < b_pos,
            "ascending id order means id 1 before id 2: {rendered}"
        );
    }

    /// The daemon creates both files at spawn, so a missing one means this
    /// sheep has never run in this `$SHEP_HOME` — not a fault worth a
    /// notice.
    #[tokio::test]
    async fn a_missing_file_is_silent_and_the_rest_still_print() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let real_path = write_log(dir.path(), "web-out.log", "still-here\n");
        let missing_path = dir
            .path()
            .join("never-written.log")
            .to_str()
            .unwrap()
            .to_string();

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut ghost = info(1, "ghost");
        ghost.out_file = Some(missing_path);
        let mut real = info(2, "web");
        real.out_file = Some(real_path);
        daemon.reply_to_list(vec![ghost, real]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &no_follow_args_out("all")),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own")
        };

        assert_eq!(code, ExitCode::Success);
        assert!(String::from_utf8(out).unwrap().contains("still-here"));
        assert!(
            err.is_empty(),
            "a missing file is silent, not a notice: {}",
            String::from_utf8_lossy(&err)
        );
    }

    /// Points `out_file` at a directory, not a `chmod 000` file: opening a
    /// directory succeeds on unix and the read fails `EISDIR`
    /// deterministically, including as root, where a `000` file would still
    /// be readable.
    #[tokio::test]
    async fn an_unreadable_file_is_noticed_and_exits_failure_with_the_rest_still_printed() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let bad_dir = dir.path().join("a-directory");
        std::fs::create_dir(&bad_dir).unwrap();
        let bad_dir = bad_dir.to_str().unwrap().to_string();
        let real_path = write_log(dir.path(), "web-out.log", "still-here\n");

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut bad = info(1, "bad");
        bad.out_file = Some(bad_dir.clone());
        let mut real = info(2, "web");
        real.out_file = Some(real_path);
        daemon.reply_to_list(vec![bad, real]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &no_follow_args_out("all")),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own")
        };

        assert_eq!(code, ExitCode::Failure);
        assert!(
            String::from_utf8(out).unwrap().contains("still-here"),
            "one sheep's unreadable file must not hide the rest of the flock's lines"
        );
        let stderr = String::from_utf8(err).unwrap();
        assert!(
            stderr.contains(&bad_dir),
            "the notice must name the unreadable path: {stderr}"
        );
    }

    /// An implementation that skips a `None` path in silence passes every
    /// other test here and fails this one.
    #[tokio::test]
    async fn a_daemon_that_reported_no_path_is_noticed_not_silently_empty() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep = info(1, "web");
        sheep.out_file = None;
        sheep.err_file = None;
        daemon.reply_to_list(vec![sheep]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Table,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &no_follow_args_out("all")),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own")
        };

        assert_eq!(
            code,
            ExitCode::Success,
            "version skew is not a fault in this run"
        );
        let stderr = String::from_utf8(err).unwrap();
        assert!(
            stderr.contains("log_path_unknown"),
            "a None path must be noticed, not silently empty: {stderr}"
        );
    }

    /// Sits beside `json_format_renders_the_pinned_five_key_line_shape`:
    /// renaming a field of `BleatLine` must now fail both.
    #[tokio::test]
    async fn a_file_sourced_json_line_is_the_same_five_key_shape_as_a_bus_sourced_one() {
        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("s.sock");
        let out_path = write_log(dir.path(), "web-out.log", "hello-from-disk\n");

        let (client, daemon) = fake_client_with_push(&sock).await;
        let mut sheep = info(1, "web");
        sheep.out_file = Some(out_path);
        daemon.reply_to_list(vec![sheep]);

        let mut out = Vec::new();
        let mut err = Vec::new();
        {
            let mut streams = Streams {
                out: &mut out,
                err: &mut err,
                style: crate::style::Presentation::BARE,
                fmt: Format::Json,
            };
            tokio::time::timeout(
                RUN_TIMEOUT,
                bleats(&client, &mut streams, false, &no_follow_args_out("all")),
            )
            .await
            .expect("--no-follow never subscribes, so it must terminate on its own");
        }
        let out = String::from_utf8(out).unwrap();
        let line = out.lines().next().expect("one JSON line was rendered");
        let json: serde_json::Value = serde_json::from_str(line).unwrap();
        let obj = json.as_object().expect("a bleats JSON line is an object");
        let mut keys: Vec<&str> = obj.keys().map(String::as_str).collect();
        keys.sort_unstable();

        assert_eq!(
            keys,
            ["id", "line", "name", "schema_version", "stream"],
            "a file-sourced line must be the same shape as a bus-sourced one: {out}"
        );
        assert_eq!(json["id"], 1);
        assert_eq!(json["name"], "web");
        assert_eq!(json["stream"], "out");
        assert_eq!(json["line"], "hello-from-disk");
        assert_eq!(json["schema_version"], output::SCHEMA_VERSION);
    }
}