runner-manager 0.4.41

Local-first autoscaling manager for ephemeral GitHub Actions self-hosted runners, with a CLI and a Ratatui TUI.
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
// owner: f1-cli-auth-host-status
//
// ----------------------------------------------------------------------------
// `update` IS DRIVEN AGAINST A REAL COPY OF THE BINARY, REPLACING ITSELF.
// ----------------------------------------------------------------------------
// Every other suite here runs `Command::cargo_bin("runner-manager")`, which is
// `target/debug/runner-manager` -- a path this command classifies as a build in
// a checkout and refuses to touch, correctly and by design. So the happy path
// cannot be reached that way at all.
//
// What these tests do instead is copy the built binary into a temporary
// directory and run THAT, which is exactly the layout `install.sh` produces and
// is therefore the real thing rather than a stand-in for it. The copy then
// replaces its own file while it is running, on whichever operating system this
// leg of the matrix is -- which is the one property of this command that cannot
// be checked by reading it.
//
// The release it updates to is `common::build_release`, a3's synthetic release:
// five archives laid out the way the published ones are, with a `SHA256SUMS`
// generated by the same `release.sh` subcommand the release workflow calls. The
// assets are read from a directory rather than over HTTP, which is the same
// affordance `install.sh` has for an air-gapped mirror -- so no test here needs
// a network, and the digest check still runs against the document beside them.

mod common;

use std::path::{Path, PathBuf};
use std::process::Command;

use common::{FixtureRelease, build_release, substitute_payload};

/// The product's own mapping, transcribed by hand.
///
/// Deliberately a second copy rather than a call into the binary: this is the
/// oracle that says which archive this host is supposed to ask for, and one
/// derived from the answer under test would agree with whatever that answer is.
fn host_target() -> (&'static str, &'static str) {
    match (std::env::consts::OS, std::env::consts::ARCH) {
        ("windows", "x86_64") => ("x86_64-pc-windows-msvc", "runner-manager.exe"),
        ("macos", "aarch64") => ("aarch64-apple-darwin", "runner-manager"),
        ("macos", "x86_64") => ("x86_64-apple-darwin", "runner-manager"),
        ("linux", "x86_64") => ("x86_64-unknown-linux-gnu", "runner-manager"),
        ("linux", "aarch64") => ("aarch64-unknown-linux-gnu", "runner-manager"),
        (os, arch) => panic!(
            "this suite has no published archive for {os}/{arch}. If the project starts \
             publishing one, add it here and to `host_target` in `cli/update.rs`."
        ),
    }
}

/// This build's version, which is what `update` compares the release against.
const RUNNING: &str = env!("CARGO_PKG_VERSION");

/// `RUNNING` with its patch raised, so the fixture release is unambiguously
/// newer whatever version the workspace is on this week.
fn one_release_newer() -> String {
    let mut parts = RUNNING.split('.');
    let major: u64 = parts.next().expect("a major").parse().expect("a number");
    let minor: u64 = parts.next().expect("a minor").parse().expect("a number");
    let patch: u64 = parts.next().expect("a patch").parse().expect("a number");
    format!("{major}.{minor}.{}", patch + 1)
}

/// Run `command`, retrying briefly past `ETXTBSY`.
///
/// # Why a retry rather than a fix at the copy
///
/// Every test here copies the built binary into its own temporary `bin/` and
/// then executes it. On Linux, `execve` fails with `ETXTBSY` ("Text file busy")
/// while **any** file descriptor anywhere in the process still holds that file
/// open for writing — and the writer does not have to be this test. `cargo
/// test` runs the tests of one binary as threads of a single process, several
/// `Installed::new` calls overlap, and a `posix_spawn` issued by thread A
/// inherits the write descriptor thread B is at that instant using to copy
/// *its* binary. Closing our own file, which `fs::copy` already does before it
/// returns, cannot prevent that: the descriptor that blocks us belongs to
/// another test.
///
/// So the race is inherent to the shape of the suite rather than to any one
/// test, and the window is the microseconds between another thread's `copy` and
/// its `spawn`. A bounded retry closes it without serialising the suite behind a
/// mutex or giving every test its own process.
///
/// The retry is deliberately narrow: only `ETXTBSY`, only for about a second,
/// and any other spawn failure still panics with the original message. A blanket
/// "retry the spawn" would hide a binary that genuinely cannot run, which is a
/// thing these tests exist to catch.
fn spawn_past_etxtbsy(command: &mut Command) -> std::process::Output {
    // 50 * 20ms. Long enough for a concurrent copy to finish by orders of
    // magnitude, short enough that a real failure is not a slow failure.
    const ATTEMPTS: u32 = 50;
    const BACKOFF: std::time::Duration = std::time::Duration::from_millis(20);

    for _ in 0..ATTEMPTS {
        match command.output() {
            Ok(output) => return output,
            Err(error) if error.raw_os_error() == Some(TEXT_FILE_BUSY) => {
                std::thread::sleep(BACKOFF);
            }
            Err(error) => panic!("the copied binary must run: {error:?}"),
        }
    }

    panic!(
        "the copied binary was still reported busy after {:?}; that is far longer than a \
         concurrent copy in this suite can hold a write descriptor, so it is a real failure \
         rather than the race this retry exists for",
        ATTEMPTS * BACKOFF
    );
}

/// `ETXTBSY`. Zero on platforms that do not raise it, which never matches a
/// real `raw_os_error` and so leaves the retry inert on Windows and macOS.
#[cfg(target_os = "linux")]
const TEXT_FILE_BUSY: i32 = 26;
#[cfg(not(target_os = "linux"))]
const TEXT_FILE_BUSY: i32 = 0;

/// An installed copy of the binary, in the layout `install.sh` produces.
struct Installed {
    /// Held so the directory outlives the test.
    _root: tempfile::TempDir,
    /// The binary an operator would have on their PATH.
    binary: PathBuf,
    /// `--data-dir` for every invocation.
    data: PathBuf,
}

impl Installed {
    /// Copies the built binary into a temporary `bin/` and returns it.
    fn new() -> Self {
        Self::under(&["bin"])
    }

    /// The layout `npm install --global --prefix <root>/prefix` writes (npm 12):
    /// the wrapper package, with the platform package nested inside it.
    fn npm_global() -> Self {
        let platform = match std::env::consts::OS {
            "windows" => "runner-manager-win32-x64",
            "macos" => "runner-manager-darwin-arm64",
            _ => "runner-manager-linux-x64",
        };
        let lib: &[&str] = if cfg!(windows) { &[] } else { &["lib"] };
        let mut components = vec!["prefix"];
        components.extend_from_slice(lib);
        components.extend_from_slice(&[
            "node_modules",
            "@ivan-murzak",
            "runner-manager",
            "node_modules",
            "@ivan-murzak",
            platform,
            "bin",
        ]);
        Self::under(&components)
    }

    /// The prefix [`Installed::npm_global`] lives in, as `update` names it.
    fn npm_prefix(&self) -> String {
        operator_path(&self._root.path().join("prefix"))
    }

    /// Copies the built binary into `<temporary root>/<components>/`.
    fn under(components: &[&str]) -> Self {
        let root = tempfile::tempdir().expect("a temporary directory");
        let bin = components
            .iter()
            .fold(root.path().to_path_buf(), |path, component| {
                path.join(component)
            });
        std::fs::create_dir_all(&bin).expect("the install directory");
        let binary = bin.join(format!("runner-manager{}", std::env::consts::EXE_SUFFIX));
        std::fs::copy(env!("CARGO_BIN_EXE_runner-manager"), &binary)
            .expect("copying the built binary into place");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755))
                .expect("making the copy executable");
        }
        let data = root.path().join("data");
        std::fs::create_dir_all(&data).expect("the data directory");
        Self {
            _root: root,
            binary,
            data,
        }
    }

    /// Runs the copied binary with the release assets pointed at `assets`.
    fn update(&self, assets: &Path, arguments: &[&str]) -> Outcome {
        self.update_with_path(assets, arguments, None)
    }

    /// [`Installed::update`], with `PATH` replaced when `path` is given.
    fn update_with_path(
        &self,
        assets: &Path,
        arguments: &[&str],
        path: Option<&std::ffi::OsStr>,
    ) -> Outcome {
        let mut command = Command::new(&self.binary);
        if let Some(path) = path {
            command.env("PATH", path);
        }
        // The developer's own exported variables must not change what this
        // measures, exactly as `support::runner_manager` argues.
        for variable in [
            "RUNNER_MANAGER_DATA_DIR",
            "RUNNER_MANAGER_GITHUB_BASE_URL",
            "RUST_LOG",
        ] {
            command.env_remove(variable);
        }
        command
            .env("RUNNER_MANAGER_UPDATE_BASE_URL", assets)
            .arg("--data-dir")
            .arg(&self.data)
            .arg("update")
            .args(arguments);
        let output = spawn_past_etxtbsy(&mut command);
        Outcome {
            code: output.status.code().unwrap_or(-1),
            stdout: String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n"),
            stderr: String::from_utf8_lossy(&output.stderr).replace("\r\n", "\n"),
        }
    }

    fn bytes(&self) -> Vec<u8> {
        std::fs::read(&self.binary).expect("the installed binary must be readable")
    }
}

struct Outcome {
    code: i32,
    stdout: String,
    stderr: String,
}

impl Outcome {
    fn both(&self) -> String {
        format!("{}{}", self.stdout, self.stderr)
    }
}

/// The bytes the fixture release carries for this host.
fn payload_of(release: &FixtureRelease) -> Vec<u8> {
    let (target, binary) = host_target();
    std::fs::read(release.staged(target).join(binary)).expect("the fixture payload")
}

// ---------------------------------------------------------------------------

/// The whole point of the command: a newer release replaces the binary that is
/// running, and says so.
#[test]
fn a_newer_release_replaces_the_running_binary() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();
    let before = installed.bytes();

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(
        outcome.code,
        0,
        "update must succeed; output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome.stdout.contains(&format!(
            "Installed runner-manager {} to",
            one_release_newer()
        )),
        "update must name the version it installed; output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome.stdout.contains("SHA-256 OK:"),
        "update must report the digest it checked; output was:\n{}",
        outcome.both()
    );

    let after = installed.bytes();
    assert_ne!(before, after, "the binary on disk must have been replaced");
    assert_eq!(
        after,
        payload_of(&release),
        "the installed file must be the binary the release archive carried"
    );
    #[cfg(windows)]
    assert_eq!(
        std::fs::read(
            installed
                .binary
                .with_file_name("runner-manager-supervisor.exe")
        )
        .expect("the update must install the no-console companion"),
        std::fs::read(
            release
                .staged("x86_64-pc-windows-msvc")
                .join("runner-manager-supervisor.exe")
        )
        .expect("fixture supervisor"),
        "a standalone update must leave the companion needed by service install"
    );
}

/// A release that is not newer changes nothing, and says nothing was done.
///
/// A `update` that reinstalled the same version on every run would restart the
/// service every time it was called -- the daemon watches this file -- which
/// turns a harmless habit into an interrupted job.
#[test]
fn the_same_version_is_not_reinstalled() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), RUNNING);
    let installed = Installed::new();
    let before = installed.bytes();

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(
        outcome.code,
        0,
        "being up to date is not a failure; output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome
            .stdout
            .contains("is the newest release. Nothing to do."),
        "output was:\n{}",
        outcome.both()
    );
    assert_eq!(installed.bytes(), before, "nothing may be written");
}

/// The published archive is verified before it is installed, and a substituted
/// one is refused with the binary in place untouched.
///
/// `substitute_payload` rebuilds a well-formed archive whose contents are not
/// the ones the digest was published for, which is the threat
/// `07-security.md` names -- an artifact tampered with in transit. Nothing but
/// the SHA-256 comparison can tell.
#[test]
fn a_substituted_archive_is_refused_and_nothing_is_installed() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let (target, _) = host_target();
    substitute_payload(&release, target);

    let installed = Installed::new();
    let before = installed.bytes();

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(
        outcome.code,
        20,
        "a digest mismatch is `unusable_response`; output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome.stderr.contains("CHECKSUM MISMATCH"),
        "the refusal must say what happened; output was:\n{}",
        outcome.both()
    );
    assert_eq!(
        installed.bytes(),
        before,
        "a refused update must leave the binary that was working in place"
    );
}

/// `--check` reports the available version and writes nothing.
#[test]
fn check_reports_the_new_version_and_changes_nothing() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();
    let before = installed.bytes();

    let outcome = installed.update(&release.assets, &["--check"]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome.stdout.contains(&format!(
            "published                 {}",
            one_release_newer()
        )),
        "output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome
            .stdout
            .contains("Nothing has been changed, because --check was given."),
        "output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome
            .stdout
            .contains("Install it with: runner-manager update"),
        "an updatable copy must be told the command that does it; output was:\n{}",
        outcome.both()
    );
    assert_eq!(installed.bytes(), before, "nothing may be written");
}

/// The report names the channel and the file, because "which of my three
/// installs did this update" is the first question an operator asks.
#[test]
fn the_report_names_the_channel_and_the_file_it_would_replace() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();

    let outcome = installed.update(&release.assets, &["--check"]);
    assert!(
        outcome
            .stdout
            .contains("installed by              release archive ("),
        "output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome
            .stdout
            .contains(&format!("installed                 {RUNNING}")),
        "output was:\n{}",
        outcome.both()
    );
}

/// A build in a checkout is refused, and refused with its own exit code so a
/// script can tell it from a failed download.
///
/// This one runs the binary cargo built, in place, which is exactly the layout
/// being refused.
#[test]
fn a_build_in_a_checkout_is_refused() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let data = tempfile::tempdir().expect("a temporary directory");

    let output = Command::new(env!("CARGO_BIN_EXE_runner-manager"))
        .env_remove("RUNNER_MANAGER_DATA_DIR")
        .env("RUNNER_MANAGER_UPDATE_BASE_URL", &release.assets)
        .arg("--data-dir")
        .arg(data.path())
        .arg("update")
        .output()
        .expect("the binary must run");
    let stderr = String::from_utf8_lossy(&output.stderr).replace("\r\n", "\n");

    assert_eq!(
        output.status.code(),
        Some(22),
        "a checkout build is `update_unsupported`; stderr was:\n{stderr}"
    );
    assert!(
        stderr.contains("build in a checkout"),
        "stderr was:\n{stderr}"
    );
    assert!(
        stderr.contains("cargo build --release"),
        "the refusal must name what to run instead; stderr was:\n{stderr}"
    );
}

/// `--check` on a copy that cannot be updated must not end by recommending the
/// command that would refuse.
#[test]
fn check_says_when_this_copy_could_not_be_updated() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let data = tempfile::tempdir().expect("a temporary directory");

    let output = Command::new(env!("CARGO_BIN_EXE_runner-manager"))
        .env_remove("RUNNER_MANAGER_DATA_DIR")
        .env("RUNNER_MANAGER_UPDATE_BASE_URL", &release.assets)
        .arg("--data-dir")
        .arg(data.path())
        .arg("update")
        .arg("--check")
        .output()
        .expect("the binary must run");
    let stdout = String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n");

    assert_eq!(output.status.code(), Some(0), "stdout was:\n{stdout}");
    assert!(
        stdout.contains("`runner-manager update` would refuse here:"),
        "stdout was:\n{stdout}"
    );
    assert!(
        !stdout.contains("Install it with: runner-manager update"),
        "a dry run must not recommend a command that refuses; stdout was:\n{stdout}"
    );
}

#[test]
fn force_check_does_not_recommend_overwriting_a_checkout_build() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), RUNNING);
    let data = tempfile::tempdir().expect("a temporary directory");
    let output = Command::new(env!("CARGO_BIN_EXE_runner-manager"))
        .env_remove("RUNNER_MANAGER_DATA_DIR")
        .env("RUNNER_MANAGER_UPDATE_BASE_URL", &release.assets)
        .arg("--data-dir")
        .arg(data.path())
        .args(["update", "--check", "--force"])
        .output()
        .expect("the binary must run");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(output.status.code(), Some(0), "{stdout}");
    assert!(stdout.contains("would refuse here"), "{stdout}");
    assert!(!stdout.contains("would back up and stage"), "{stdout}");
}

/// The override that redirects where a replacement executable comes from
/// accepts only this machine.
///
/// This is the security property of the whole seam: an http(s) origin that is
/// not loopback would make an exported variable a remote-code-execution
/// primitive aimed at whoever runs `update` next.
#[test]
fn an_http_asset_source_that_is_not_this_machine_is_refused() {
    let data = tempfile::tempdir().expect("a temporary directory");
    let output = Command::new(env!("CARGO_BIN_EXE_runner-manager"))
        .env_remove("RUNNER_MANAGER_DATA_DIR")
        .env(
            "RUNNER_MANAGER_UPDATE_BASE_URL",
            "https://releases.example.com/download",
        )
        .arg("--data-dir")
        .arg(data.path())
        .arg("update")
        .arg("--check")
        .output()
        .expect("the binary must run");
    let stderr = String::from_utf8_lossy(&output.stderr).replace("\r\n", "\n");

    assert_eq!(
        output.status.code(),
        Some(9),
        "an untrusted origin is `invalid_argument`; stderr was:\n{stderr}"
    );
    assert!(
        stderr.contains("which is not this machine"),
        "stderr was:\n{stderr}"
    );
}

/// A release that publishes no archive for this host is a different failure
/// from a release that could not be read, and must not be reported as one.
#[test]
fn a_release_without_this_platform_says_so() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let (target, _) = host_target();

    // Drop every line naming this host's archive, leaving the other four.
    let sums = std::fs::read_to_string(release.sums()).expect("the fixture SHA256SUMS");
    let kept: Vec<&str> = sums.lines().filter(|line| !line.contains(target)).collect();
    std::fs::write(release.sums(), format!("{}\n", kept.join("\n"))).expect("the trimmed sums");

    let installed = Installed::new();
    let outcome = installed.update(&release.assets, &["--check"]);
    assert_eq!(
        outcome.code,
        15,
        "a missing platform is `unsupported_host`; output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome.stderr.contains("publishes no archive for"),
        "output was:\n{}",
        outcome.both()
    );
}

// ---------------------------------------------------------------------------
// What the update means for the service
// ---------------------------------------------------------------------------

/// An install record in the shape `service install` writes, transcribed by hand.
///
/// ----------------------------------------------------------------------------
/// WRITTEN OUT RATHER THAN BUILT FROM `InstallRecord`, ON PURPOSE.
/// ----------------------------------------------------------------------------
/// `crates/app` has no library target, so `tests/` sees dev-dependencies only
/// and cannot reach `runner-manager-platform` -- but even where it could, a
/// fixture serialised from the very struct `update` deserialises would agree
/// with whatever that struct says, which is the one thing a fixture must not
/// do. This is an independent statement of the file `service install` leaves in
/// `config/`, and a schema change that stops `update` reporting the hand-over
/// must fail here rather than pass quietly. Same reasoning as the hand-copied
/// command list in `cli_command_surface.rs`.
fn write_install_record(data: &Path, source_binary: Option<&Path>) {
    write_install_record_for(
        data,
        source_binary,
        &data.join("state").join("bin").join("runner-manager"),
    );
}

/// [`write_install_record`], with the service's private copy at `binary`.
fn write_install_record_for(data: &Path, source_binary: Option<&Path>, binary: &Path) {
    let config = data.join("config");
    std::fs::create_dir_all(&config).expect("the config directory");
    let source_line = match source_binary {
        Some(path) => format!("source_binary = {}\n", toml_path(path)),
        None => String::new(),
    };
    let record = format!(
        "schema_version = 1\n\
         service_name = \"com.example.runner-manager\"\n\
         manager = \"launchd\"\n\
         start_mode = \"boot\"\n\
         account = \"root\"\n\
         binary = {binary}\n\
         {source_line}\
         arguments = [\"daemon\", \"run\"]\n\
         restart_delay_secs = 5\n\
         restart_reset_secs = 60\n\
         log_file = {log}\n\
         starts_on_demand = false\n\
         definition_path = \"/Library/LaunchDaemons/com.example.runner-manager.plist\"\n\
         installed_at = \"2026-09-01T00:00:00Z\"\n\
         installed_by_version = \"0.0.1\"\n\
         \n\
         [directories]\n\
         config = {config_dir}\n\
         state = {state}\n\
         runtime = {runtime}\n\
         logs = {logs}\n",
        binary = toml_path(binary),
        log = toml_path(&data.join("logs").join("runner-manager")),
        config_dir = toml_path(&config),
        state = toml_path(&data.join("state")),
        runtime = toml_path(&data.join("runtime")),
        logs = toml_path(&data.join("logs")),
    );
    std::fs::write(config.join("service.toml"), record).expect("the install record");
}

/// A path as a TOML string. Windows separators are escapes in a basic string,
/// so the literal form is the one that survives them.
fn toml_path(path: &Path) -> String {
    format!("'{}'", path.display())
}

/// A path the way `update` prints one: canonical (the copy's own path is
/// canonicalised, which resolves `/var` to `/private/var` on macOS and a short
/// `RUNNER~1` name on Windows), without Windows' `\\?\` prefix.
fn operator_path(path: &Path) -> String {
    let canonical = std::fs::canonicalize(path).expect("an existing path");
    let rendered = canonical.display().to_string();
    rendered
        .strip_prefix(r"\\?\")
        .map_or(rendered.clone(), str::to_owned)
}

/// A script named `name` in `directory` that answers like a program would.
/// A `.cmd` on Windows, which is how npm itself ships there; a shell script
/// elsewhere.
fn write_script(directory: &Path, name: &str, windows_body: &str, unix_body: &str) -> PathBuf {
    std::fs::create_dir_all(directory).expect("the script directory");
    if cfg!(windows) {
        let script = directory.join(format!("{name}.cmd"));
        std::fs::write(&script, format!("@echo off\r\n{windows_body}\r\n")).expect("the script");
        script
    } else {
        let script = directory.join(name);
        std::fs::write(&script, format!("#!/bin/sh\n{unix_body}\n")).expect("the script");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
                .expect("making the script executable");
        }
        script
    }
}

/// `directory` ahead of this process's own `PATH`.
fn path_with_first(directory: &Path) -> std::ffi::OsString {
    let inherited = std::env::var_os("PATH").unwrap_or_default();
    std::env::join_paths(
        std::iter::once(directory.to_path_buf()).chain(std::env::split_paths(&inherited)),
    )
    .expect("a joinable PATH")
}

/// ANASTASIIA: an npm copy was refused with "npm is not on this PATH" while
/// `npm.cmd` sat in `C:\Program Files\nodejs\` -- `Command::new("npm")` only
/// looks for `npm.exe`. The npm here is likewise only `npm.cmd` on Windows, and
/// it must be told the prefix that holds this copy, not left to install into
/// the invoking account's own prefix.
#[test]
fn an_npm_copy_is_updated_by_the_npm_on_path_in_its_own_prefix() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let newer = one_release_newer();
    let release = build_release(fixtures.path(), &newer);
    let installed = Installed::npm_global();
    let tools = fixtures.path().join("tools");
    let recorded = tools.join("npm-arguments.txt");
    write_script(
        &tools,
        "npm",
        "for %%a in (%*) do >>\"%~dp0npm-arguments.txt\" echo %%~a",
        "for a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$(dirname \"$0\")/npm-arguments.txt\"; done",
    );

    let outcome = installed.update_with_path(&release.assets, &[], Some(&path_with_first(&tools)));
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    let arguments = std::fs::read_to_string(&recorded)
        .unwrap_or_else(|error| panic!("npm was never run ({error}):\n{}", outcome.both()));
    let arguments: Vec<&str> = arguments.lines().map(str::trim).collect();
    let package = format!("@ivan-murzak/runner-manager@{newer}");
    assert_eq!(
        arguments,
        [
            "install",
            "--global",
            "--prefix",
            installed.npm_prefix().as_str(),
            package.as_str()
        ],
        "output was:\n{}",
        outcome.both()
    );
    // The stand-in npm changed nothing, and the copy that was meant to be
    // updated is run to say so rather than trusting npm's exit status.
    assert!(
        outcome.stdout.contains(&format!("still reports {RUNNING}")),
        "output was:\n{}",
        outcome.both()
    );
}

fn modified(path: &Path) -> std::time::SystemTime {
    std::fs::metadata(path)
        .and_then(|metadata| metadata.modified())
        .expect("a modification time")
}

/// ANASTASIIA: npm had installed the newest release by hand, the service still
/// ran the old build, and `update` said "Nothing to do". The service watches
/// this copy, so `update` marks it changed and the daemon's own job-safe drain
/// does the rest; the copy marked is the one running this very command. No
/// service manager here runs this record's daemon, so the report says it swaps
/// when it starts rather than claiming a swap in progress.
#[test]
fn an_older_service_behind_the_newest_release_is_swapped_not_nothing_to_do() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), RUNNING);
    let installed = Installed::new();
    let service = write_script(
        &installed.data.join("state").join("bin"),
        "runner-manager",
        "echo runner-manager 0.0.1",
        "echo runner-manager 0.0.1",
    );
    write_install_record_for(&installed.data, Some(&installed.binary), &service);
    let long_ago =
        std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000_000);
    let mark_long_ago = || {
        std::fs::File::options()
            .write(true)
            .open(&installed.binary)
            .and_then(|file| file.set_modified(long_ago))
            .expect("an old modification time");
    };

    mark_long_ago();
    let checked = installed.update(&release.assets, &["--check"]);
    assert_eq!(checked.code, 0, "output was:\n{}", checked.both());
    assert!(
        checked.stdout.contains("still runs 0.0.1"),
        "{}",
        checked.both()
    );
    assert!(
        checked.stdout.contains("swaps to") && checked.stdout.contains("as soon as it starts"),
        "{}",
        checked.both()
    );
    assert!(
        !checked.stdout.contains("Nothing to do"),
        "{}",
        checked.both()
    );
    assert_eq!(
        modified(&installed.binary),
        long_ago,
        "--check changed the copy"
    );

    let before = installed.bytes();
    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome.stdout.contains("still runs 0.0.1"),
        "{}",
        outcome.both()
    );
    assert!(
        outcome
            .stdout
            .contains(&format!("swaps to {RUNNING} as soon as it starts")),
        "{}",
        outcome.both()
    );
    assert!(!outcome.stdout.contains("warning"), "{}", outcome.both());
    assert!(
        modified(&installed.binary) > long_ago,
        "the copy the daemon watches was not marked changed:\n{}",
        outcome.both()
    );
    assert_eq!(
        installed.bytes(),
        before,
        "the copy's bytes must not change"
    );
}

/// The same, with the service registered from another copy: only
/// `update --force` can hand this one over without interrupting a job, and
/// neither file is touched.
#[test]
fn an_older_service_from_another_copy_is_told_to_hand_over_with_force() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), RUNNING);
    let installed = Installed::new();
    let service = write_script(
        &installed.data.join("state").join("bin"),
        "runner-manager",
        "echo runner-manager 0.0.1",
        "echo runner-manager 0.0.1",
    );
    let elsewhere = installed.data.join("another").join("runner-manager");
    write_install_record_for(&installed.data, Some(&elsewhere), &service);
    let before = modified(&installed.binary);

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome.stdout.contains("still runs 0.0.1"),
        "{}",
        outcome.both()
    );
    assert!(
        outcome.stdout.contains("runner-manager update --force"),
        "{}",
        outcome.both()
    );
    assert_eq!(modified(&installed.binary), before);
}

/// The step an operator upgrading by hand forgets: the service runs a copy, so
/// the hand-over happens by itself and takes as long as the jobs in flight.
#[test]
fn a_service_running_a_copy_is_told_it_will_hand_over_by_itself() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();
    write_install_record(&installed.data, Some(&installed.binary));

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome
            .stdout
            .contains("The service runs its own copy of this binary."),
        "output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome.stdout.contains("Nothing else is needed."),
        "output was:\n{}",
        outcome.both()
    );
}

/// A registration made before the service ran a copy of its own names the
/// binary directly, and that layout cannot pick the new version up by itself.
#[test]
fn a_registration_with_no_recorded_source_is_told_to_reinstall() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();
    write_install_record(&installed.data, None);

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome.stdout.contains("names a binary directly"),
        "output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome.stdout.contains("runner-manager service install"),
        "the report must name the command that fixes it; output was:\n{}",
        outcome.both()
    );
}

/// A host with two copies of this program: the service was installed from one
/// of them and `update` was run from the other. Saying "it will hand over" here
/// would be false, and it is the case an operator is least likely to spot.
#[test]
fn a_service_installed_from_another_binary_is_named_rather_than_assumed() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();
    let elsewhere = installed.data.join("another").join("runner-manager");
    write_install_record(&installed.data, Some(&elsewhere));

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome.stdout.contains("The service was installed from"),
        "output was:\n{}",
        outcome.both()
    );
    assert!(
        outcome.stdout.contains(&elsewhere.display().to_string()),
        "the report must name the other binary; output was:\n{}",
        outcome.both()
    );
}

/// A forced dry run must not promise an unbounded drain when its service record
/// does not belong to a live registration. Neither binary may change.
#[test]
fn force_check_refuses_an_unmatched_service_and_preserves_both_files() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), RUNNING);
    let installed = Installed::new();
    let source = installed.data.join("another").join("runner-manager");
    std::fs::create_dir_all(source.parent().unwrap()).unwrap();
    std::fs::write(&source, b"operator source").unwrap();
    write_install_record(&installed.data, Some(&source));
    let before = installed.bytes();

    let outcome = installed.update(&release.assets, &["--check", "--force"]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome.stdout.contains("would refuse here"),
        "{}",
        outcome.both()
    );
    assert!(
        !outcome.stdout.contains("Install it with:"),
        "{}",
        outcome.both()
    );
    assert_eq!(installed.bytes(), before);
    assert_eq!(std::fs::read(source).unwrap(), b"operator source");
}

/// A forged record in a data-dir cannot borrow the real machine's service
/// registration to overwrite its own arbitrary source path.
#[test]
fn force_refuses_a_record_without_its_matching_live_service() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), RUNNING);
    let installed = Installed::new();
    let source = installed.data.join("another").join("runner-manager");
    std::fs::create_dir_all(source.parent().unwrap()).unwrap();
    std::fs::write(&source, b"unrelated source").unwrap();
    write_install_record(&installed.data, Some(&source));

    let outcome = installed.update(&release.assets, &["--force"]);
    assert_ne!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        outcome.stderr.contains("registration") || outcome.stderr.contains("service"),
        "output was:\n{}",
        outcome.both()
    );
    assert_eq!(std::fs::read(source).unwrap(), b"unrelated source");
}

#[test]
fn force_refuses_before_updating_cli_when_service_cannot_be_drained() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();
    let source = installed.data.join("another").join("runner-manager");
    std::fs::create_dir_all(source.parent().unwrap()).unwrap();
    std::fs::write(&source, b"unrelated source").unwrap();
    write_install_record(&installed.data, Some(&source));
    let before = installed.bytes();

    let outcome = installed.update(&release.assets, &["--force"]);
    assert_ne!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert_eq!(installed.bytes(), before, "CLI must not be half-updated");
    assert_eq!(std::fs::read(source).unwrap(), b"unrelated source");
}

/// A host with no service at all gets no paragraph about one.
#[test]
fn a_host_with_no_service_is_told_nothing_about_one() {
    let fixtures = tempfile::tempdir().expect("a temporary directory");
    let release = build_release(fixtures.path(), &one_release_newer());
    let installed = Installed::new();

    let outcome = installed.update(&release.assets, &[]);
    assert_eq!(outcome.code, 0, "output was:\n{}", outcome.both());
    assert!(
        !outcome.stdout.contains("The service"),
        "output was:\n{}",
        outcome.both()
    );
}