mahbot 0.11.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Install and update the product's own build of ffmpeg and ffprobe.
//!
//! The pair is built and published by the product itself in a release stream of its own:
//! prereleases tagged `ffmpeg-v<version>-mahbot.<revision>`. That separate stream keeps
//! the product's updater untouched — it reads `releases/latest` and `version.txt`, which
//! never point at one — while the archives stay downloadable by a plain HTTP client.
//!
//! Nothing about the build is compiled in. At start the stream's listing is read and the
//! newest build it offers for this host is installed unless that is already the copy in
//! use, so a build published after this binary needs nothing from a product release. The
//! newest is the highest (upstream version, build revision) among releases carrying this
//! platform's archive: all six are real builds, and a release missing one is a failed
//! release, never a substitution.
//!
//! Integrity comes from the release, as for the product's other managed binaries: the
//! archive is checked against the release's fetched `SHA256SUMS`. No digest of an
//! artefact is carried by this build, so a checksum file rewritten together with its
//! archive is not detected — the price of that.
//!
//! The build is GPLv3 — upstream ffmpeg with libx264, libx265, libvpx, libopus, zimg,
//! zlib and OpenSSL (SChannel on Windows, the system's own) — so the binaries travel with
//! that licence, the components' notices and a `SOURCE.txt`. A build published before
//! those notices existed installs with the licence it carries rather than not at all.
//!
//! The copy in use is the newest one that runs: a failed install leaves the host with
//! whatever it had, never with nothing. A failure names the failed step and carries no
//! path and no URL, because it is recorded and shown verbatim. Nothing is written outside
//! the product's own configuration directory — no package-manager directory, no `PATH`
//! entry. The operations that run this copy belong to [`super`].

use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;

use semver::Version;

use crate::util::UnwrapPoison;
use crate::util::managed_bin;

/// The tag prefix of this stream, and the marker separating the upstream version from
/// the build revision inside a tag.
const TAG_PREFIX: &str = "ffmpeg-v";
const REVISION_MARKER: &str = "-mahbot.";

/// Test hook: a host answering the way the real pair of hosts does — the listing
/// at `?per_page=&page=`, and each release's files at `{base}/{tag}/{asset}`.
pub(super) const RELEASES_URL_ENV: &str = "MAHBOT_FFMPEG_RELEASES_URL";

/// How long a staged binary may take to print its banner: a local file needing longer is
/// a copy that cannot run.
const VERSION_TIMEOUT: Duration = Duration::from_secs(10);

/// The stream's listing, named the way every failure about it names it.
const LISTING_SUBJECT: &str = "the ffmpeg release listing";

/// The licence the build is distributed under, and where its source is. Both have
/// travelled since the stream's first build, so a release without either is a failed
/// install — shipping the binary alone does not honour its licence.
const LICENCE_AND_SOURCE: [&str; 2] = ["LICENCE.txt", "SOURCE.txt"];

/// The notices of the linked libraries. Every archive the release job publishes carries
/// them, but a build from before they existed carries none, and installing it with the
/// material it has serves a host better than no pair at all.
const COMPONENT_NOTICES: &str = "LICENCES.txt";

/// The two binaries' file names on this platform. Windows decides executability by extension
/// ([`crate::util::is_executable`]), so the suffix is part of the name there and nowhere else.
const fn ffmpeg_file() -> &'static str {
    if cfg!(windows) {
        "ffmpeg.exe"
    } else {
        "ffmpeg"
    }
}

const fn ffprobe_file() -> &'static str {
    if cfg!(windows) {
        "ffprobe.exe"
    } else {
        "ffprobe"
    }
}

/// What a tag — or a directory named after one — spells: the upstream version and the
/// build revision (`ffmpeg-v7.1-mahbot.1` → 7.1 and 1). Anything else reads as `None`.
#[must_use]
fn parse_tag(name: &str) -> Option<(semver::Version, u32)> {
    let rest = name.strip_prefix(TAG_PREFIX)?;
    let (upstream, revision) = rest.split_once(REVISION_MARKER)?;
    Some((
        managed_bin::parse_short_version(upstream)?,
        revision.parse().ok()?,
    ))
}

/// The tag naming its release, and the upstream version its binaries must report — the
/// tag's own, so an archive carrying another FFmpeg cannot pass for it.
struct Build {
    tag: String,
    upstream: Version,
}

/// `ffmpeg-<tag stem>-<os>-<arch>.<ext>`, `zip` on Windows and `tar.gz` elsewhere. The
/// stem comes from the tag, so the archive name and its release cannot disagree.
#[must_use]
fn asset_name(tag: &str, os: &str, arch: &str) -> String {
    let stem = tag.strip_prefix(TAG_PREFIX).unwrap_or(tag);
    let extension = if os == "windows" { "zip" } else { "tar.gz" };
    format!("ffmpeg-{stem}-{os}-{arch}.{extension}")
}

#[derive(Debug)]
pub(crate) struct Binaries {
    pub(crate) ffmpeg: PathBuf,
    pub(crate) ffprobe: PathBuf,
}

/// Test hook: the install root, so a check never writes into the developer's own `~/.mahbot/ffmpeg`.
#[cfg(test)]
pub(crate) const ROOT_ENV: &str = "MAHBOT_FFMPEG_ROOT";

/// One subdirectory per tag inside the product's configuration directory — never the
/// daemon's swept temp root, never a package-manager directory. A test run's root is the test
/// root unless the check named its own: `cargo test` must never install into a live product.
#[cfg_attr(
    test,
    expect(clippy::unnecessary_wraps, reason = "the test root always resolves")
)]
fn root() -> Result<PathBuf, String> {
    #[cfg(test)]
    let dir = std::env::var_os(ROOT_ENV).map_or_else(
        || crate::util::test::test_root().join("ffmpeg"),
        PathBuf::from,
    );
    #[cfg(not(test))]
    let dir = crate::config::default_config_dir()
        .map_err(|_| "the product's configuration directory is unavailable".to_string())?
        .join("ffmpeg");
    Ok(dir)
}

/// The newest usable copy under `root` by (upstream version, build revision). A
/// directory whose name does not parse, or that holds anything but two executable
/// files, is not a copy.
fn chosen(root: &Path) -> Option<(Build, Binaries)> {
    fs::read_dir(root)
        .ok()?
        .flatten()
        .filter_map(|entry| {
            let tag = entry.file_name().into_string().ok()?;
            let rank = parse_tag(&tag)?;
            let binaries = binaries_at(&entry.path())?;
            Some((rank, tag, binaries))
        })
        .max_by(|(left, _, _), (right, _, _)| left.cmp(right))
        .map(|((upstream, _), tag, binaries)| (Build { tag, upstream }, binaries))
}

fn binaries_in(dir: &Path) -> Binaries {
    let bin = dir.join("bin");
    Binaries {
        ffmpeg: bin.join(ffmpeg_file()),
        ffprobe: bin.join(ffprobe_file()),
    }
}

/// The pair inside one tag directory, or `None` when either file is missing or cannot be executed.
fn binaries_at(dir: &Path) -> Option<Binaries> {
    let binaries = binaries_in(dir);
    (crate::util::is_executable(&binaries.ffmpeg) && crate::util::is_executable(&binaries.ffprobe))
        .then_some(binaries)
}

/// The copy already in place, without installing one: a caller that must not download asks here.
pub(crate) fn installed() -> Option<Binaries> {
    chosen(&root().ok()?).map(|(_, binaries)| binaries)
}

/// Holds the one install in flight, so the boot install and a first use never overlap.
static INSTALLING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

static ATTEMPT_FAILURE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

/// Run `attempt` as the one install in flight, so a caller that waited re-reads what is
/// in use instead of downloading what the winner already placed.
async fn installing<T, E>(attempt: impl AsyncFnOnce() -> Result<T, E>) -> Result<T, E> {
    let _queue = INSTALLING.lock().await;
    attempt().await
}

/// The copy a video operation runs: whatever pair is in use, and — when there is none — the newest
/// build the stream offers, installed first.
///
/// A copy in place is used as it stands, with no proof and no network round-trip: it was
/// proved before it was placed and the boot task re-proves it, so a pair damaged since
/// keeps serving video until the next start. Installing is behind [`installing`], so a
/// first use never runs beside the boot task's install and the loser re-checks before
/// downloading. A failed attempt stands for the rest of the process: the next start
/// tries again.
pub(super) async fn ensure_installed() -> Result<Binaries, String> {
    let root = root()?;
    if let Some((_, binaries)) = chosen(&root) {
        return Ok(binaries);
    }
    let tag = installing(async || {
        // The caller that held the lock may have installed a copy while this one waited.
        if let Some((build, _)) = chosen(&root) {
            return Ok(build.tag);
        }
        if let Some(reason) = ATTEMPT_FAILURE.lock().unwrap_poison().clone() {
            return Err(reason);
        }
        let build = newest().await.map_err(recorded)?;
        install(&root, &build).await.map_err(recorded)?;
        Ok(build.tag)
    })
    .await?;
    Ok(binaries_in(&root.join(tag)))
}

#[derive(Debug)]
enum Standing {
    Working(String),
    /// Damaged, half-written, or another build under that name.
    Damaged(String),
    Missing,
}

/// A start that failed: the step that failed, and what the host is left running.
#[derive(Debug)]
struct Failure {
    reason: String,
    standing: Standing,
}

/// The boot task: bring this host to the newest build the stream offers, called once by the binary
/// and never failing the boot.
pub async fn install_on_start() {
    match update().await {
        Ok(None) => tracing::debug!("ffmpeg needs nothing at this start"),
        Ok(Some(tag)) => tracing::info!("ffmpeg {tag} installed"),
        Err(failure) => report_failure(&failure),
    }
}

/// The one WARN line a failed start leaves: what the host is left running, and the step
/// that failed.
fn report_failure(failure: &Failure) {
    let reason = &failure.reason;
    match &failure.standing {
        Standing::Damaged(tag) => tracing::warn!(
            "ffmpeg {tag} is damaged and could not be replaced (retried on the next \
             start): {reason}"
        ),
        Standing::Working(tag) => tracing::warn!(
            "ffmpeg is running {tag}; the newest build is not installed (retried on the \
             next start): {reason}"
        ),
        Standing::Missing => {
            tracing::warn!("ffmpeg is not installed (retried on the next start): {reason}");
        }
    }
}

/// What the host runs now, proved with two local `-version` runs and no network.
async fn standing(root: &Path) -> Standing {
    match chosen(root) {
        Some((in_use, binaries)) if proves_itself(&binaries, &in_use.upstream).await => {
            Standing::Working(in_use.tag)
        }
        Some((in_use, _)) => Standing::Damaged(in_use.tag),
        None => Standing::Missing,
    }
}

/// Install the newest build the stream offers unless the copy in use already is it and
/// still proves itself. `Ok(None)` is nothing to do; `Ok(Some(tag))` names what was installed.
///
/// A stream that cannot be read is not a failure for a host whose copy proves itself: the
/// next start that can read the listing takes whatever newer build it offers.
async fn update() -> Result<Option<String>, Failure> {
    let root = root().map_err(|reason| Failure {
        reason,
        standing: Standing::Missing,
    })?;
    installing(async || {
        let current = standing(&root).await;
        let build = match newest().await {
            Ok(build) => build,
            Err(reason) => {
                return match current {
                    Standing::Working(tag) => {
                        tracing::debug!("keeping ffmpeg {tag}: {reason}");
                        Ok(None)
                    }
                    other => Err(Failure {
                        reason: recorded(reason),
                        standing: other,
                    }),
                };
            }
        };
        if let Standing::Working(tag) = &current
            && tag == &build.tag
        {
            return Ok(None);
        }
        install(&root, &build).await.map_err(|reason| Failure {
            reason: recorded(reason),
            standing: current,
        })?;
        Ok(Some(build.tag))
    })
    .await
}

/// Both binaries run, exit clean and report `upstream` — the check a directory name
/// cannot give, and what replaces a pair damaged after it was placed.
async fn proves_itself(binaries: &Binaries, upstream: &Version) -> bool {
    reports_upstream(&binaries.ffmpeg, upstream).await
        && reports_upstream(&binaries.ffprobe, upstream).await
}

/// Record a failed attempt, so no later operation in this process pays for it again.
fn recorded(reason: String) -> String {
    *ATTEMPT_FAILURE.lock().unwrap_poison() = Some(reason.clone());
    reason
}

/// Forget the one failed attempt this process remembers: a test that points the stream at its own
/// host must not inherit an earlier test's failure.
#[cfg(test)]
pub(super) fn forget_failed_attempt() {
    *ATTEMPT_FAILURE.lock().unwrap_poison() = None;
}

/// The highest (upstream version, build revision) among the releases carrying this
/// platform's archive.
///
/// Every page of the listing is read first: its order is publication, not version, so a
/// repair of an older line is published after the newer line exists. A release without
/// this platform's archive is a failed release, never a substitute.
async fn newest() -> Result<Build, String> {
    let (os, arch) = managed_bin::host_os_arch()?;
    let base = stream_url("https://api.github.com/repos", "releases");
    let mut newest: Option<((Version, u32), String)> = None;
    for page in 1..=managed_bin::LISTING_PAGES {
        let releases = managed_bin::release_page(&base, page, LISTING_SUBJECT)
            .await?
            .ok_or_else(|| {
                format!("{LISTING_SUBJECT} could not be read: it is not a JSON array")
            })?;
        for release in &releases {
            let Some(tag) = release["tag_name"].as_str() else {
                continue;
            };
            let Some(rank) = parse_tag(tag) else {
                continue;
            };
            let asset = asset_name(tag, os, arch);
            let carries_ours = release["assets"]
                .as_array()
                .is_some_and(|assets| assets.iter().any(|a| a["name"].as_str() == Some(&asset)));
            if !carries_ours || newest.as_ref().is_some_and(|(best, _)| best >= &rank) {
                continue;
            }
            newest = Some((rank, tag.to_string()));
        }
        if releases.len() < managed_bin::LISTING_PAGE_SIZE {
            break;
        }
    }
    let ((upstream, _), tag) =
        newest.ok_or_else(|| format!("no ffmpeg build is published for {os}-{arch}"))?;
    Ok(Build { tag, upstream })
}

/// Download, verify, prove and place the pair, then leave that copy as the only one under
/// the root.
///
/// The order makes a failure harmless: this platform's line in the release's checksum file
/// is read before anything is downloaded, the archive is verified as it streams, and the
/// pair is proven to run before the directory is renamed into place.
async fn install(root: &Path, build: &Build) -> Result<(), String> {
    use crate::util::http::{DownloadSizeCheck, download_verified};

    let (os, arch) = managed_bin::host_os_arch()?;
    let tag = &build.tag;
    let asset = asset_name(tag, os, arch);
    let base = stream_url("https://github.com", "releases/download");

    let sums = managed_bin::fetch_sha256_sums(
        &format!("{base}/{tag}/SHA256SUMS"),
        "the release's checksum file",
    )
    .await?;
    let digest = managed_bin::sha256_for(&sums, &asset)
        .ok_or_else(|| "the release carries no checksum for this platform's archive".to_string())?;

    let downloads = root.join("downloads");
    let _ = fs::remove_dir_all(&downloads);
    fs::create_dir_all(&downloads)
        .map_err(|e| format!("the download directory could not be created ({})", e.kind()))?;
    let archive = downloads.join(&asset);
    download_verified(
        managed_bin::download_client()?,
        &format!("{base}/{tag}/{asset}"),
        &archive,
        &digest,
        None,
        DownloadSizeCheck::Exact,
        |_, _| {},
    )
    .await
    .map_err(|e| {
        format!(
            "the ffmpeg release could not be downloaded: {}",
            managed_bin::download_reason(&e)
        )
    })?;

    // On the same filesystem as its destination, so the final rename is a rename. The
    // guard removes it on every failure the `?` below carries out.
    let staging = tempfile::Builder::new()
        .prefix(".staging-")
        .tempdir_in(root)
        .map_err(|e| format!("the staging directory could not be created ({})", e.kind()))?;
    extract_into(&archive, staging.path())?;
    let _ = fs::remove_dir_all(&downloads);

    for (name, tool) in [("ffmpeg", ffmpeg_file()), ("ffprobe", ffprobe_file())] {
        if !reports_upstream(&staging.path().join("bin").join(tool), &build.upstream).await {
            return Err(format!(
                "the downloaded {name} could not run, or does not report ffmpeg {}",
                build.upstream
            ));
        }
    }
    managed_bin::place_staged_tree(staging.path(), &root.join(tag))?;
    prune(root, tag);
    Ok(())
}

/// The repository's `releases/download` for the assets, its API `releases` for the
/// listing, or the test hook's stand-in answering both.
#[cfg_attr(
    test,
    expect(unused_variables, reason = "the test default names no host or path")
)]
fn stream_url(host: &str, path: &str) -> String {
    #[cfg(not(test))]
    let default = format!("{host}/{}/{path}", managed_bin::release_repo());
    // A test run never fetches a release: with no hook set, the base is a host nothing answers
    // on, so an install fails at once with the reason instead of reaching the network.
    #[cfg(test)]
    let default = "http://127.0.0.1:1".to_string();
    std::env::var(RELEASES_URL_ENV).map_or(default, |base| base.trim_end_matches('/').to_string())
}

/// The two binaries under `bin/`, the licence material at the root — the layout [`binaries_at`]
/// reads. The notices are optional: a build from before they existed still installs.
fn extract_into(archive: &Path, staging: &Path) -> Result<(), String> {
    let bin_dir = staging.join("bin");
    fs::create_dir_all(&bin_dir).map_err(|e| {
        format!(
            "the staged copy's directory could not be created ({})",
            e.kind()
        )
    })?;
    let tools = [ffmpeg_file(), ffprobe_file()];
    // The tools come first in `required`, in this order: `extract` returns their paths in
    // the same order.
    let required = tools
        .iter()
        .copied()
        .chain(LICENCE_AND_SOURCE)
        .collect::<Vec<_>>();
    let paths = extract(archive, staging, &required, &[COMPONENT_NOTICES])?;
    for (name, path) in tools.into_iter().zip(&paths) {
        managed_bin::set_executable(path)?;
        fs::rename(path, bin_dir.join(name))
            .map_err(|e| format!("the staged copy could not be arranged ({})", e.kind()))?;
    }
    Ok(())
}

/// Extract `required` and `optional` out of `archive` into `dir`, whichever container this
/// platform's release uses.
fn extract(
    archive: &Path,
    dir: &Path,
    required: &[&str],
    optional: &[&str],
) -> Result<Vec<PathBuf>, String> {
    if archive.extension().and_then(OsStr::to_str) == Some("zip") {
        managed_bin::extract_named_files_zip(archive, dir, required, optional)
    } else {
        managed_bin::extract_named_files_tar_gz(archive, dir, required, optional)
    }
}

/// The whole version a tag names: `7.1.3`, a vendor's `7.1.3-static` too, and a banner
/// spelling only `7.1` is 7.1.0 — what an `ffmpeg-v7.1-…` tag names.
fn banner_version(stdout: &[u8]) -> Option<Version> {
    let text = String::from_utf8_lossy(stdout);
    let line = text.lines().next()?;
    let token = line
        .split_whitespace()
        .skip_while(|word| *word != "version")
        .nth(1)?;
    managed_bin::parse_short_version(token.split_once('-').map_or(token, |(head, _)| head))
}

/// The proof no checksum can give: the file is the expected build and can execute here.
async fn reports_upstream(bin: &Path, upstream: &Version) -> bool {
    let Ok(output) = super::run_tool(bin, &["-version".into()], VERSION_TIMEOUT).await else {
        return false;
    };
    output.success && banner_version(&output.stdout).as_ref() == Some(upstream)
}

/// Every copy but the one just installed — an older one, and a newer one the stream no
/// longer offers or that failed to prove itself, which [`chosen`] would otherwise keep
/// picking — plus every leftover that is not a copy (staging, an aside, the download, a
/// name from another layout).
///
/// Infallible in effect: each removal is best effort, so a file another process holds can
/// never fail an install that already succeeded. On Windows a copy a running operation
/// holds stays until a later start.
fn prune(root: &Path, tag: &str) {
    let Ok(entries) = fs::read_dir(root) else {
        return;
    };
    for entry in entries.flatten() {
        let name = entry.file_name();
        if name == OsStr::new(tag) {
            continue;
        }
        let path = entry.path();
        if path.is_dir() {
            let _ = fs::remove_dir_all(&path);
        } else {
            let _ = fs::remove_file(&path);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write as _;

    #[cfg(unix)]
    use std::{
        collections::HashMap,
        io::Read as _,
        net::{TcpListener, TcpStream},
        sync::{
            Arc, Mutex,
            atomic::{AtomicBool, Ordering},
        },
    };

    use super::*;
    #[cfg(unix)]
    use crate::ffmpeg::ReleasesHook;

    /// The environment lock [`ReleasesHook`] needs, held for the caller's scope: a
    /// `MutexGuard` cannot live across an await point, so it travels inside a struct.
    #[cfg(unix)]
    #[must_use]
    struct EnvHeld {
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    /// Holds the environment lock as long as the returned value lives.
    #[cfg(unix)]
    fn env_held() -> EnvHeld {
        EnvHeld {
            _lock: crate::util::test::env_lock().lock().unwrap_poison(),
        }
    }

    /// A tag directory holding two executable files, as an install leaves it.
    fn install_fake(root: &Path, tag: &str) -> PathBuf {
        let bin = root.join(tag).join("bin");
        fs::create_dir_all(&bin).expect("create tag directory");
        for tool in [ffmpeg_file(), ffprobe_file()] {
            let path = bin.join(tool);
            fs::write(&path, b"BIN").expect("write binary");
            managed_bin::set_executable(&path).expect("make executable");
        }
        root.join(tag)
    }

    /// The build a tag names, for the checks that drive [`install`] and the banner.
    fn build(tag: &str) -> Build {
        let (upstream, _) = parse_tag(tag).expect("a parsable tag");
        Build {
            tag: tag.to_string(),
            upstream,
        }
    }

    #[test]
    fn every_platform_gets_its_own_archive() {
        let tag = "ffmpeg-v7.1-mahbot.2";
        assert_eq!(
            asset_name(tag, "macos", "aarch64"),
            "ffmpeg-7.1-mahbot.2-macos-aarch64.tar.gz"
        );
        assert_eq!(
            asset_name(tag, "macos", "x86_64"),
            "ffmpeg-7.1-mahbot.2-macos-x86_64.tar.gz"
        );
        assert_eq!(
            asset_name(tag, "linux", "aarch64"),
            "ffmpeg-7.1-mahbot.2-linux-aarch64.tar.gz"
        );
        assert_eq!(
            asset_name(tag, "linux", "x86_64"),
            "ffmpeg-7.1-mahbot.2-linux-x86_64.tar.gz"
        );
        assert_eq!(
            asset_name(tag, "windows", "x86_64"),
            "ffmpeg-7.1-mahbot.2-windows-x86_64.zip"
        );
        // Windows on ARM is its own build, never the x64 one.
        assert_eq!(
            asset_name(tag, "windows", "aarch64"),
            "ffmpeg-7.1-mahbot.2-windows-aarch64.zip"
        );
    }

    #[test]
    fn the_newest_copy_on_disk_is_the_one_in_use() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        install_fake(root, "ffmpeg-v6.0-mahbot.1");
        install_fake(root, "ffmpeg-v7.1-mahbot.0");
        install_fake(root, "ffmpeg-v7.2-mahbot.1");
        fs::create_dir_all(root.join(".staging-Kd7x2p")).expect("create staging");
        fs::create_dir(root.join("not-a-tag")).expect("create junk directory");

        // The newest by (upstream version, build revision): a staging directory or a name
        // from another layout is not a copy.
        let (build, binaries) = chosen(root).expect("a copy is in use");
        assert_eq!(build.tag, "ffmpeg-v7.2-mahbot.1");
        assert_eq!(
            binaries.ffmpeg,
            root.join("ffmpeg-v7.2-mahbot.1")
                .join("bin")
                .join(ffmpeg_file())
        );

        // A newer revision of the same upstream wins.
        install_fake(root, "ffmpeg-v7.2-mahbot.2");
        assert_eq!(
            chosen(root).expect("a copy is in use").0.tag,
            "ffmpeg-v7.2-mahbot.2"
        );

        // A tagged directory holding one binary is not a copy.
        let broken = root.join("ffmpeg-v7.2-mahbot.2");
        fs::remove_file(broken.join("bin").join(ffprobe_file())).expect("remove ffprobe");
        assert_eq!(
            chosen(root).expect("a copy is in use").0.tag,
            "ffmpeg-v7.2-mahbot.1"
        );

        // A newer upstream wins over a newer revision of an older one.
        fs::remove_dir_all(root.join("ffmpeg-v7.2-mahbot.1")).expect("remove the newer build");
        assert_eq!(
            chosen(root).expect("a copy is in use").0.tag,
            "ffmpeg-v7.1-mahbot.0"
        );
    }

    #[test]
    fn pruning_leaves_only_the_copy_just_installed() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        for tag in [
            "ffmpeg-v6.0-mahbot.1",
            "ffmpeg-v7.1-mahbot.0",
            "ffmpeg-v7.1-mahbot.2",
        ] {
            install_fake(root, tag);
        }
        fs::create_dir_all(root.join(".staging-Kd7x2p")).expect("create staging");
        fs::create_dir_all(root.join("downloads")).expect("create downloads");

        // A copy newer than the installed one goes too — the stream no longer offers it,
        // or it failed to prove itself, and `chosen` would keep picking it: a download on
        // every start that never converges.
        prune(root, "ffmpeg-v7.1-mahbot.0");
        assert!(
            root.join("ffmpeg-v7.1-mahbot.0").exists(),
            "the installed copy stays"
        );
        for gone in [
            "ffmpeg-v6.0-mahbot.1",
            "ffmpeg-v7.1-mahbot.2",
            ".staging-Kd7x2p",
            "downloads",
        ] {
            assert!(!root.join(gone).exists(), "{gone} is gone");
        }
    }

    #[test]
    fn the_banner_names_the_upstream_version() {
        let tagged = build("ffmpeg-v7.1.3-mahbot.2");
        assert_eq!(
            tagged.upstream,
            Version::new(7, 1, 3),
            "the tag names the version every banner is compared against"
        );
        // Upstream's banner carries the upstream version, never the build revision.
        assert_eq!(
            banner_version(b"ffmpeg version 7.1.3 Copyright (c) 2000-2024 the FFmpeg developers\n"),
            Some(tagged.upstream.clone())
        );
        // A vendor's suffix is not part of the version.
        assert_eq!(
            banner_version(b"ffprobe version 7.1.3-static Copyright (c) 2000-2024\n"),
            Some(tagged.upstream)
        );
        // `major.minor` alone carries no patch.
        assert_eq!(
            banner_version(b"ffmpeg version 7.1 Copyright\n"),
            Some(Version::new(7, 1, 0))
        );
        assert_eq!(banner_version(b"nothing to see\n"), None);
        assert_eq!(banner_version(b""), None);
    }

    /// The entries a release archive carries: the pair under `bin/` inside a vendor
    /// directory, the licence material at the root. The stand-in binaries print the
    /// upstream version the tag names, so the pair is provable the way a real build is.
    fn release_entries(tag: &str) -> Vec<(String, Vec<u8>)> {
        let upstream = parse_tag(tag).expect("a parsable tag").0;
        let script =
            format!("#!/bin/sh\necho 'ffmpeg version {upstream} stand-in build'\n").into_bytes();
        vec![
            (format!("pkg/bin/{}", ffmpeg_file()), script.clone()),
            (format!("pkg/bin/{}", ffprobe_file()), script),
            ("LICENCE.txt".to_string(), b"GPLv3".to_vec()),
            (
                "LICENCES.txt".to_string(),
                b"x264: GPL-2.0-or-later\n".to_vec(),
            ),
            ("SOURCE.txt".to_string(), b"upstream source".to_vec()),
        ]
    }

    fn write_tar_gz(path: &Path, entries: &[(String, Vec<u8>)]) {
        let encoder = flate2::write::GzEncoder::new(
            fs::File::create(path).expect("create archive"),
            flate2::Compression::default(),
        );
        let mut builder = tar::Builder::new(encoder);
        for (name, contents) in entries {
            let mut header = tar::Header::new_gnu();
            header.set_size(contents.len() as u64);
            header.set_mode(0o644);
            header.set_entry_type(tar::EntryType::Regular);
            builder
                .append_data(&mut header, name.as_str(), contents.as_slice())
                .expect("append entry");
        }
        builder
            .into_inner()
            .expect("finish archive")
            .finish()
            .expect("finish gzip");
    }

    fn write_zip(path: &Path, entries: &[(String, Vec<u8>)]) {
        let mut writer = zip::ZipWriter::new(fs::File::create(path).expect("create archive"));
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated);
        for (name, contents) in entries {
            writer
                .start_file(name.as_str(), options)
                .expect("start entry");
            writer.write_all(contents).expect("write entry");
        }
        writer.finish().expect("finish zip");
    }

    /// The staged layout is what the installer reads back: two executable binaries
    /// under `bin/`, the licence material at the root — the notices included, which the
    /// release's archives carry.
    fn assert_staged(archive: &Path, staging: &Path) {
        extract_into(archive, staging).expect("extract the release archive");
        for tool in [ffmpeg_file(), ffprobe_file()] {
            let path = staging.join("bin").join(tool);
            assert!(crate::util::is_executable(&path), "{tool} is executable");
        }
        for licence in LICENCE_AND_SOURCE.into_iter().chain([COMPONENT_NOTICES]) {
            assert!(
                staging.join(licence).is_file(),
                "{licence} is at the archive's root"
            );
        }
        assert_eq!(
            fs::read(staging.join("LICENCE.txt")).expect("read the licence"),
            b"GPLv3" as &[u8]
        );
        assert_eq!(
            fs::read(staging.join("SOURCE.txt")).expect("read the source note"),
            b"upstream source" as &[u8]
        );
    }

    /// Both archive formats the stream publishes — `tar.gz` on macOS and
    /// Linux, `zip` on Windows — land in the same staging layout.
    #[test]
    fn a_release_lands_in_the_staging_layout() {
        let entries = release_entries("ffmpeg-v7.1-mahbot.2");
        let dir = tempfile::tempdir().expect("tempdir");
        let tarball = dir.path().join("pkg.tar.gz");
        write_tar_gz(&tarball, &entries);
        assert_staged(&tarball, &dir.path().join("staging-tar"));
        let archive = dir.path().join("pkg.zip");
        write_zip(&archive, &entries);
        assert_staged(&archive, &dir.path().join("staging-zip"));
    }

    /// The licence material is the one thing a release may not omit: the
    /// licence and source notes are required, while the component notices are
    /// optional — a build from before they existed installs with the material
    /// it carries, since a host with no pair at all is worse served than one
    /// running that build until the next start takes a newer one.
    #[test]
    fn licence_material_rules() {
        let dir = tempfile::tempdir().expect("tempdir");

        let archive = dir.path().join("no-licence.tar.gz");
        let entries: Vec<(String, Vec<u8>)> = release_entries("ffmpeg-v7.1-mahbot.2")
            .into_iter()
            .filter(|(name, _)| !name.starts_with("LICENCE"))
            .collect();
        write_tar_gz(&archive, &entries);
        let reason = extract_into(&archive, &dir.path().join("refused-staging"))
            .expect_err("a release without its licence text is refused");
        assert!(reason.contains("LICENCE.txt"), "{reason}");

        let archive = dir.path().join("no-notices.tar.gz");
        let entries: Vec<(String, Vec<u8>)> = release_entries("ffmpeg-v7.1-mahbot.2")
            .into_iter()
            .filter(|(name, _)| name != COMPONENT_NOTICES)
            .collect();
        write_tar_gz(&archive, &entries);
        let staging = dir.path().join("staging");
        extract_into(&archive, &staging).expect("a build from before the notices installs");
        for licence in LICENCE_AND_SOURCE {
            assert!(staging.join(licence).is_file(), "{licence} is there");
        }
        assert!(
            !staging.join(COMPONENT_NOTICES).exists(),
            "no notices to copy"
        );
        assert!(
            crate::util::is_executable(&staging.join("bin").join(ffmpeg_file())),
            "the pair is staged regardless"
        );
    }

    /// The floors the archives are built against are the product's own, so an archive
    /// that checksums can still start on every machine the product runs on. One fact,
    /// told by both the workflow that builds them and the product's own constants; a
    /// drift offers a file to a system that cannot load it.
    #[test]
    fn the_floors_are_the_product_own() {
        let workflow = fs::read_to_string(
            Path::new(env!("CARGO_MANIFEST_DIR")).join(".github/workflows/ffmpeg-release.yml"),
        )
        .expect("the workflow that builds the archives");
        let (macos, glibc) = (
            crate::self_update::MACOS_FLOOR,
            crate::self_update::GLIBC_FLOOR,
        );
        assert!(
            workflow.contains(&format!("-mmacosx-version-min={}.{}", macos.0, macos.1)),
            "the macOS archives must be built against {}.{}",
            macos.0,
            macos.1
        );
        assert!(
            workflow.contains(&format!("GLIBC_FLOOR: \"{}.{}\"", glibc.0, glibc.1)),
            "the Linux archives must be built against glibc {}.{}",
            glibc.0,
            glibc.1
        );
        assert!(
            workflow.contains("getconf GNU_LIBC_VERSION"),
            "the Linux legs must refuse a base newer than the floor"
        );
    }

    /// This host's archive name for `tag`: the one the installer asks the release for.
    #[cfg(unix)]
    fn host_asset(tag: &str) -> String {
        let (os, arch) =
            managed_bin::host_os_arch().expect("this host is one the product builds for");
        asset_name(tag, os, arch)
    }

    /// A real archive of [`release_entries`], made once and served as bytes, since the
    /// host answers with what it was handed.
    #[cfg(unix)]
    fn archive_bytes(dir: &Path, tag: &str) -> Vec<u8> {
        let archive = dir.join(host_asset(tag));
        write_tar_gz(&archive, &release_entries(tag));
        fs::read(&archive).expect("read the stand-in archive")
    }

    /// One line of a `SHA256SUMS` body.
    #[cfg(unix)]
    fn checksum_line(digest: &str, name: &str) -> String {
        format!("{digest}  {name}\n")
    }

    /// The lowercase hex SHA-256 of `bytes`: what a `SHA256SUMS` line for an archive carries.
    #[cfg(unix)]
    fn sha256_hex(bytes: &[u8]) -> String {
        use sha2::Digest as _;
        crate::util::hex_string(&sha2::Sha256::digest(bytes))
    }

    /// The staging directories a finished or failed attempt may have left under
    /// `root`: the prefix the attempt's own guard gives them.
    #[cfg(unix)]
    fn staging_dirs(root: &Path) -> Vec<String> {
        entries(root)
            .into_iter()
            .filter(|name| name.starts_with(".staging-"))
            .collect()
    }

    /// Every name under `root`, sorted: what an install left behind, a copy or otherwise.
    #[cfg(unix)]
    fn entries(root: &Path) -> Vec<String> {
        let mut names: Vec<String> = fs::read_dir(root)
            .map(|entries| {
                entries
                    .flatten()
                    .filter_map(|entry| entry.file_name().into_string().ok())
                    .collect()
            })
            .unwrap_or_default();
        names.sort();
        names
    }

    /// The releases a stand-in stream offers: each tag and the asset names it carries.
    #[cfg(unix)]
    type Offered = Arc<Mutex<Vec<(String, Vec<String>)>>>;

    /// A stand-in for the release stream: the listing at `?per_page=&page=`, and one
    /// release's files at `{base}/{tag}/SHA256SUMS` and `{base}/{tag}/{asset}`, with a
    /// 404 for anything else. Shaped like `FakeTelegram` in
    /// `channels/telegram_tests.rs` — a non-blocking accept loop polling a stop flag,
    /// one thread and one answer per connection — because the installer is a real HTTP
    /// client and no check may ask the real host.
    #[cfg(unix)]
    struct FakeRelease {
        /// The base [`RELEASES_URL_ENV`] is pointed at.
        base: String,
        /// Every release the stream offers: its tag and the asset names it carries.
        offered: Offered,
        /// The bytes each path answers with, replaced between cases.
        served: Arc<Mutex<HashMap<String, Vec<u8>>>>,
        /// Every path asked for, in arrival order.
        asked: Arc<Mutex<Vec<String>>>,
        /// A listing body to answer with instead of the stream's own.
        listing: Arc<Mutex<Option<Vec<u8>>>>,
        /// Set by `Drop`, so the polling accept loop lets go of the socket.
        stop: Arc<AtomicBool>,
        accept: Option<std::thread::JoinHandle<()>>,
    }

    #[cfg(unix)]
    impl FakeRelease {
        fn start() -> Self {
            let listener = TcpListener::bind("127.0.0.1:0").expect("bind the stand-in host");
            listener
                .set_nonblocking(true)
                .expect("the stand-in host accepts without blocking");
            let port = listener.local_addr().expect("stand-in host address").port();
            let offered = Arc::new(Mutex::new(Vec::new()));
            let served = Arc::new(Mutex::new(HashMap::new()));
            let asked = Arc::new(Mutex::new(Vec::new()));
            let listing = Arc::new(Mutex::new(None));
            let stop = Arc::new(AtomicBool::new(false));
            let accept = std::thread::spawn({
                let offered = Arc::clone(&offered);
                let served = Arc::clone(&served);
                let asked = Arc::clone(&asked);
                let listing = Arc::clone(&listing);
                let stop = Arc::clone(&stop);
                move || {
                    while !stop.load(Ordering::Relaxed) {
                        match listener.accept() {
                            Ok((stream, _)) => {
                                // The accepted socket can inherit the listener's
                                // non-blocking mode (it does on macOS), and a polling reader
                                // would see a half-arrived request.
                                let _ = stream.set_nonblocking(false);
                                let offered = Arc::clone(&offered);
                                let served = Arc::clone(&served);
                                let asked = Arc::clone(&asked);
                                let listing = Arc::clone(&listing);
                                std::thread::spawn(move || {
                                    serve(stream, &offered, &served, &asked, &listing);
                                });
                            }
                            // Polling, so the loop can see `stop`: a blocking accept would
                            // outlive the check that drops the host.
                            Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
                                std::thread::sleep(Duration::from_millis(2));
                            }
                            // A client that went away before being accepted is ordinary.
                            Err(_) => {}
                        }
                    }
                }
            });
            Self {
                base: format!("http://127.0.0.1:{port}"),
                offered,
                served,
                asked,
                listing,
                stop,
                accept: Some(accept),
            }
        }

        /// `sums` is its checksum file, `archive` the file `asset` names. A second call
        /// for the same tag replaces its files and leaves the listing as it was.
        fn offer(&self, tag: &str, asset: &str, sums: &str, archive: &[u8]) {
            let mut offered = self.offered.lock().expect("fake listing");
            if !offered.iter().any(|(name, _)| name == tag) {
                offered.push((tag.to_string(), vec![asset.to_string()]));
            }
            drop(offered);
            self.served.lock().expect("fake release files").extend([
                (format!("/{tag}/SHA256SUMS"), sums.as_bytes().to_vec()),
                (format!("/{tag}/{asset}"), archive.to_vec()),
            ]);
        }

        /// So every attempt in the check asks this host, never the real one.
        fn base(&self) -> &str {
            &self.base
        }

        fn asked(&self) -> Vec<String> {
            self.asked.lock().expect("fake release log").clone()
        }

        /// Answer the listing with `body`, whatever pages are asked for.
        fn listing_is(&self, body: &[u8]) {
            *self.listing.lock().expect("fake listing override") = Some(body.to_vec());
        }
    }

    #[cfg(unix)]
    impl Drop for FakeRelease {
        fn drop(&mut self) {
            self.stop.store(true, Ordering::Relaxed);
            if let Some(accept) = self.accept.take() {
                let _ = accept.join();
            }
        }
    }

    /// Answer one request: the listing, the bytes registered for its path, or a 404.
    #[cfg(unix)]
    fn serve(
        mut stream: TcpStream,
        offered: &Mutex<Vec<(String, Vec<String>)>>,
        served: &Mutex<HashMap<String, Vec<u8>>>,
        asked: &Mutex<Vec<String>>,
        listing: &Mutex<Option<Vec<u8>>>,
    ) {
        let Some(path) = request_path(&mut stream) else {
            return;
        };
        asked.lock().expect("fake release log").push(path.clone());
        let override_body = listing.lock().expect("fake listing override").clone();
        let body = match path.strip_prefix("/?") {
            // The host answers with a body of its own.
            Some(_) if override_body.is_some() => override_body,
            // Page one is the whole stream; a later page is its end.
            Some(query) if query.contains("page=1") => Some(listing_body(offered)),
            Some(_) => Some(b"[]".to_vec()),
            None => served
                .lock()
                .expect("fake release files")
                .get(&path)
                .cloned(),
        };
        let head = match &body {
            Some(bytes) => format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n\
                 Content-Length: {}\r\nConnection: close\r\n\r\n",
                bytes.len()
            ),
            None => "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                .to_string(),
        };
        let _ = stream.write_all(head.as_bytes());
        if let Some(bytes) = body {
            let _ = stream.write_all(&bytes);
        }
    }

    /// In the shape the GitHub API answers with: one entry per offered release, with its
    /// asset names.
    #[cfg(unix)]
    fn listing_body(offered: &Mutex<Vec<(String, Vec<String>)>>) -> Vec<u8> {
        let releases: Vec<serde_json::Value> = offered
            .lock()
            .expect("fake listing")
            .iter()
            .map(|(tag, assets)| {
                serde_json::json!({
                    "tag_name": tag,
                    "assets": assets
                        .iter()
                        .map(|name| serde_json::json!({ "name": name }))
                        .collect::<Vec<_>>(),
                })
            })
            .collect();
        serde_json::Value::Array(releases).to_string().into_bytes()
    }

    /// The request line, read up to the blank line that ends the head; every request is a
    /// bodyless GET.
    #[cfg(unix)]
    fn request_path(stream: &mut TcpStream) -> Option<String> {
        let mut buffer = Vec::new();
        let mut chunk = [0u8; 1024];
        loop {
            let read = stream.read(&mut chunk).ok()?;
            if read == 0 {
                return None;
            }
            buffer.extend_from_slice(&chunk[..read]);
            if buffer.windows(4).any(|window| window == b"\r\n\r\n") {
                break;
            }
        }
        let head = String::from_utf8_lossy(&buffer);
        Some(head.lines().next()?.split_whitespace().nth(1)?.to_string())
    }

    /// A throwaway install root with the check's own override pointing at it while the guard
    /// lives.
    #[cfg(unix)]
    fn temp_root() -> (tempfile::TempDir, crate::util::test::EnvVarGuard, PathBuf) {
        let dir = tempfile::tempdir().expect("temp install root");
        let guard = crate::util::test::set_env_var(ROOT_ENV, dir.path().to_str());
        let root = root().expect("the install root resolves under the temp root");
        (dir, guard, root)
    }

    /// The newest build this host has an archive for is installed, a following start has
    /// nothing to download, and a build published later is picked up by the next start.
    #[cfg(unix)]
    #[tokio::test]
    #[serial_test::serial(ffmpeg_releases)]
    async fn the_boot_installs_the_newest_build_the_stream_offers() {
        let files = tempfile::tempdir().expect("stand-in release files");
        let (_home, _lock, root) = temp_root();
        let host = FakeRelease::start();
        for tag in [
            "ffmpeg-v7.1-mahbot.2",
            "ffmpeg-v7.0-mahbot.9",
            "ffmpeg-v7.1-mahbot.1",
        ] {
            let asset = host_asset(tag);
            let archive = archive_bytes(files.path(), tag);
            let sums = checksum_line(&sha256_hex(&archive), &asset);
            host.offer(tag, &asset, &sums, &archive);
        }
        // Newer than every build above, and carrying no archive for this host.
        host.offer(
            "ffmpeg-v9.0-mahbot.1",
            &asset_name("ffmpeg-v9.0-mahbot.1", "windows", "aarch64"),
            "",
            b"",
        );
        let _hook = ReleasesHook::at(host.base());

        assert_eq!(
            update()
                .await
                .expect("the newest build installs")
                .as_deref(),
            Some("ffmpeg-v7.1-mahbot.2")
        );
        assert_eq!(
            chosen(&root).expect("a copy is in use").0.tag,
            "ffmpeg-v7.1-mahbot.2",
            "the newest build the stream carries for this host is the one in use"
        );
        assert_eq!(
            entries(&root),
            ["ffmpeg-v7.1-mahbot.2"],
            "one copy: nothing older, no download and no staging left"
        );
        for licence in LICENCE_AND_SOURCE.into_iter().chain([COMPONENT_NOTICES]) {
            assert!(
                root.join("ffmpeg-v7.1-mahbot.2").join(licence).is_file(),
                "{licence} travelled with the pair"
            );
        }
        assert_eq!(
            host.asked().first().map(String::as_str),
            Some("/?per_page=100&page=1"),
            "the listing is what the boot starts from"
        );

        // The copy is already the newest: the listing is read and nothing downloaded.
        let asked = host.asked().len();
        assert_eq!(update().await.expect("nothing to do"), None);
        assert_eq!(
            host.asked().len(),
            asked + 1,
            "only the listing is read again"
        );

        // A build published after this product binary was is picked up by a later start, and the
        // build it replaces is pruned.
        let newer = "ffmpeg-v7.1-mahbot.3";
        let asset = host_asset(newer);
        let archive = archive_bytes(files.path(), newer);
        let sums = checksum_line(&sha256_hex(&archive), &asset);
        host.offer(newer, &asset, &sums, &archive);
        assert_eq!(
            update().await.expect("the newer build installs").as_deref(),
            Some(newer)
        );
        assert_eq!(entries(&root), [newer], "the build it replaced is gone");
    }

    /// A copy in place that is not the one to keep is replaced exactly once, so a start
    /// converges on one copy instead of downloading every time: a pair damaged after it was
    /// placed, or a tag that outranks the stream's newest (withdrawn, or no longer provable).
    #[cfg(unix)]
    #[tokio::test]
    #[serial_test::serial(ffmpeg_releases)]
    async fn an_unkept_copy_is_replaced_once() {
        // A truncation or a quarantine leaves exactly this: the directory parses and the
        // files are executable, but one is no longer the build.
        {
            let files = tempfile::tempdir().expect("stand-in release files");
            let (_home, _lock, root) = temp_root();
            let host = FakeRelease::start();
            let tag = "ffmpeg-v7.1-mahbot.2";
            let asset = host_asset(tag);
            let archive = archive_bytes(files.path(), tag);
            let sums = checksum_line(&sha256_hex(&archive), &asset);
            host.offer(tag, &asset, &sums, &archive);
            let _hook = ReleasesHook::at(host.base());
            update().await.expect("the build installs");

            let damaged = root.join(tag).join("bin").join(ffmpeg_file());
            fs::write(
                &damaged,
                b"#!/bin/sh\necho 'ffmpeg version 0.0.0 damaged'\n",
            )
            .expect("damage the copy");
            managed_bin::set_executable(&damaged).expect("keep it executable");

            assert_eq!(
                update()
                    .await
                    .expect("the damaged copy is replaced")
                    .as_deref(),
                Some(tag),
                "the same build is installed again"
            );
            assert_eq!(
                update().await.expect("nothing to do").as_deref(),
                None,
                "the replacement proves itself"
            );
        }

        // A copy whose tag outranks the stream's newest is replaced by the build the stream offers,
        // and removed.
        {
            let files = tempfile::tempdir().expect("stand-in release files");
            let (_home, _lock, root) = temp_root();
            let host = FakeRelease::start();
            let tag = "ffmpeg-v7.1-mahbot.2";
            let asset = host_asset(tag);
            let archive = archive_bytes(files.path(), tag);
            let sums = checksum_line(&sha256_hex(&archive), &asset);
            host.offer(tag, &asset, &sums, &archive);
            let _hook = ReleasesHook::at(host.base());

            install_fake(&root, "ffmpeg-v7.1-mahbot.9");

            assert_eq!(
                update()
                    .await
                    .expect("the build the stream offers installs")
                    .as_deref(),
                Some(tag)
            );
            assert_eq!(
                entries(&root),
                [tag],
                "the copy the stream no longer offers is gone"
            );

            let asked = host.asked().len();
            assert_eq!(
                update().await.expect("nothing to do"),
                None,
                "the following start converges on the one copy"
            );
            assert_eq!(
                host.asked().len(),
                asked + 1,
                "only the listing is read again"
            );
        }
    }

    /// A stream that cannot be read leaves a copy that proves itself alone: nothing is installed,
    /// nothing is reported, and the copy stays in use.
    #[cfg(unix)]
    #[tokio::test]
    #[serial_test::serial(ffmpeg_releases)]
    async fn an_unreadable_stream_leaves_a_proven_copy_alone() {
        let files = tempfile::tempdir().expect("stand-in release files");
        let (_home, _lock, root) = temp_root();
        let host = FakeRelease::start();
        let tag = "ffmpeg-v7.1-mahbot.2";
        let asset = host_asset(tag);
        let archive = archive_bytes(files.path(), tag);
        let sums = checksum_line(&sha256_hex(&archive), &asset);
        host.offer(tag, &asset, &sums, &archive);
        {
            let _hook = ReleasesHook::at(host.base());
            update().await.expect("the build installs");
        }

        let _hook = ReleasesHook::at("http://127.0.0.1:1");
        assert_eq!(
            update()
                .await
                .expect("a copy that proves itself needs no listing"),
            None
        );
        assert_eq!(entries(&root), [tag], "the copy stays in use");
    }

    /// A stream that cannot be reached is never asked about a copy in place.
    #[cfg(unix)]
    #[tokio::test]
    #[serial_test::serial(ffmpeg_releases)]
    async fn a_copy_in_place_is_used_without_asking_the_stream() {
        let (_home, _lock, root) = temp_root();
        install_fake(&root, "ffmpeg-v7.1-mahbot.1");
        let _hook = ReleasesHook::at("http://127.0.0.1:1");

        let binaries = ensure_installed().await.expect("the copy in place is used");
        assert_eq!(
            binaries.ffmpeg,
            root.join("ffmpeg-v7.1-mahbot.1")
                .join("bin")
                .join(ffmpeg_file())
        );
    }

    /// A stream with no archive for this host names the platform (never another
    /// platform's archive); a listing that is not a release array — the API's rate-limit
    /// message, a proxy's answer — is a read failure, never the claim that this platform
    /// has no published build.
    #[cfg(unix)]
    #[tokio::test]
    #[serial_test::serial(ffmpeg_releases)]
    async fn newest_names_why_it_cannot_pick_a_build() {
        let host = FakeRelease::start();
        host.offer(
            "ffmpeg-v7.1-mahbot.2",
            &asset_name("ffmpeg-v7.1-mahbot.2", "windows", "aarch64"),
            "",
            b"",
        );
        {
            let _lock = env_held();
            let _hook = ReleasesHook::at(host.base());
            let Err(reason) = newest().await else {
                panic!("this host has no build in the stream");
            };
            let (os, arch) = managed_bin::host_os_arch().expect("a supported host");
            assert!(
                reason.contains(&format!("no ffmpeg build is published for {os}-{arch}")),
                "{reason}"
            );
        }

        host.listing_is(br#"{"message":"API rate limit exceeded"}"#);
        let _lock = env_held();
        let _hook = ReleasesHook::at(host.base());
        let Err(reason) = newest().await else {
            panic!("a body that is not a release array names no build");
        };
        assert!(
            reason.contains("could not be read: it is not a JSON array"),
            "{reason}"
        );
    }

    /// The whole install path against a host standing in for the release stream: a
    /// release whose checksum file carries this platform's line lands as the copy in
    /// use, and every way a release can lie — no line for this platform's archive, bytes
    /// that are not the declared ones — installs nothing and leaves the working copy in place.
    #[cfg(unix)]
    #[tokio::test]
    #[serial_test::serial(ffmpeg_releases)]
    async fn the_install_checks_the_release_against_its_own_checksums() {
        let dir = tempfile::tempdir().expect("install root");
        let root = dir.path();
        let files = tempfile::tempdir().expect("stand-in release files");
        let tag = "ffmpeg-v7.1-mahbot.2";
        let asset = host_asset(tag);
        let archive = archive_bytes(files.path(), tag);
        let sums = checksum_line(&sha256_hex(&archive), &asset);

        // 1. The checksum file names this platform's archive: the whole path runs, and the
        //    copy it leaves is the tag's own with nothing of the attempt beside it.
        let host = FakeRelease::start();
        host.offer(tag, &asset, &sums, &archive);
        let _lock = env_held();
        let _hook = ReleasesHook::at(host.base());
        install(root, &build(tag))
            .await
            .expect("the release installs");
        assert_eq!(
            host.asked(),
            [format!("/{tag}/SHA256SUMS"), format!("/{tag}/{asset}")],
            "the checksum file and this platform's archive, both under the tag"
        );
        assert_eq!(
            chosen(root).expect("a copy is in use").0.tag,
            tag,
            "the copy in use is the one installed"
        );
        for tool in [ffmpeg_file(), ffprobe_file()] {
            assert!(
                crate::util::is_executable(&root.join(tag).join("bin").join(tool)),
                "{tool} is installed executable"
            );
        }
        assert_eq!(
            entries(root),
            [tag.to_string()],
            "the whole install is one directory: no download and no staging left"
        );

        // 2. No line for this platform's archive: no other platform's is substituted.
        let elsewhere = checksum_line(
            &sha256_hex(&archive),
            &asset_name(tag, "windows", "aarch64"),
        );
        host.offer(tag, &asset, &elsewhere, &archive);
        let reason = install(root, &build(tag))
            .await
            .expect_err("a release without this platform's archive is refused");
        assert!(reason.contains("no checksum for this platform"), "{reason}");
        assert_eq!(
            chosen(root).expect("the installed copy survives").0.tag,
            tag,
            "the copy in use is untouched"
        );
        assert!(
            !root.join("downloads").exists(),
            "nothing was downloaded for a release without this archive"
        );
        assert!(
            staging_dirs(root).is_empty(),
            "nothing was staged for a release without this archive"
        );

        // 3. The declared digest, with bytes that are not the declared ones: the download
        //    is refused and nothing of it is kept.
        let mut altered = archive.clone();
        *altered.last_mut().expect("the archive has bytes") ^= 0xff;
        host.offer(tag, &asset, &sums, &altered);
        let reason = install(root, &build(tag))
            .await
            .expect_err("an archive that does not match its digest is refused");
        assert!(reason.contains("does not match the checksum"), "{reason}");
        assert_eq!(
            chosen(root).expect("the installed copy survives").0.tag,
            tag,
            "the copy in use is untouched"
        );
        assert!(
            !root.join("downloads").join(&asset).exists(),
            "the refused archive is not kept"
        );
        assert!(
            staging_dirs(root).is_empty(),
            "nothing was staged for a rejected download"
        );

        // 4. An unusable copy where the tag belongs — a binary gone — is replaced in a
        //    single swap, so the host is never left without a copy and no half-installed
        //    directory survives.
        host.offer(tag, &asset, &sums, &archive);
        fs::remove_file(root.join(tag).join("bin").join(ffprobe_file()))
            .expect("break the installed copy");
        assert!(
            chosen(root).is_none(),
            "a copy that lost a binary is not a copy"
        );
        install(root, &build(tag))
            .await
            .expect("the release replaces the broken copy");
        for tool in [ffmpeg_file(), ffprobe_file()] {
            assert!(
                crate::util::is_executable(&root.join(tag).join("bin").join(tool)),
                "{tool} is back after the swap"
            );
        }
        for licence in LICENCE_AND_SOURCE {
            assert!(
                root.join(tag).join(licence).is_file(),
                "{licence} survives the swap"
            );
        }
    }
}