Skip to main content

paper/daemon/
auto_update.rs

1//! Daily auto-update to the version the signed remote config approves, through
2//! the install method that owns the binary. Only the daemon runs this.
3
4use crate::cli::uninstall::{current_install_method, InstallMethod};
5use crate::cli::Workspace;
6use crate::core::effective::load_live_remote;
7use crate::core::remote_config::RemoteUpdate;
8use crate::core::update_state::{
9    auto_update_enabled, read_update_state, version_newer, write_update_state, UpdateState,
10};
11use crate::daemon::resource_guard::ResourceGuard;
12use anyhow::{bail, Context, Result};
13use chrono::NaiveDate;
14use std::path::{Path, PathBuf};
15use std::process::Output;
16use std::time::Duration;
17
18const REPO: &str = "kintsugi-tools/paperscope";
19const CURRENT: &str = env!("CARGO_PKG_VERSION");
20const SHADOW_HINT: &str =
21    "restarted on an older binary; another copy may shadow it (see paper doctor)";
22const SHORT: Duration = Duration::from_secs(10 * 60);
23const CARGO_TIMEOUT: Duration = Duration::from_secs(60 * 60);
24
25#[derive(Debug, PartialEq, Eq)]
26pub enum Action {
27    Nothing(&'static str),
28    Install { version: String },
29}
30
31/// Pure decision. Offline, then opted out, then not newer; a failed or
32/// unavailable result for the same approved version today waits until tomorrow.
33pub fn decide(
34    current: &str,
35    approved: Option<&RemoteUpdate>,
36    enabled: bool,
37    offline: bool,
38    last: Option<&UpdateState>,
39    today: NaiveDate,
40) -> Action {
41    if offline {
42        return Action::Nothing("offline");
43    }
44    if !enabled {
45        return Action::Nothing("opted_out");
46    }
47    let Some(approved) = approved.filter(|a| version_newer(&a.version, current)) else {
48        return Action::Nothing("up_to_date");
49    };
50    if let Some(last) = last.filter(|l| l.approved.as_deref() == Some(approved.version.as_str())) {
51        let same_day = chrono::DateTime::parse_from_rfc3339(&last.at)
52            .is_ok_and(|at| at.with_timezone(&chrono::Local).date_naive() == today);
53        match (same_day, last.outcome.as_str()) {
54            (true, "failed") => return Action::Nothing("failed"),
55            (true, "unavailable") => return Action::Nothing("unavailable"),
56            _ => {}
57        }
58    }
59    Action::Install {
60        version: approved.version.clone(),
61    }
62}
63
64fn method_name(method: &InstallMethod) -> &'static str {
65    match method {
66        InstallMethod::Homebrew => "brew",
67        InstallMethod::Npm => "npm",
68        InstallMethod::Cargo => "cargo",
69        InstallMethod::ShellInstaller => "shell",
70        InstallMethod::Unknown => "unknown",
71    }
72}
73
74pub fn manual_command(method: &InstallMethod, version: &str) -> String {
75    match method {
76        InstallMethod::Homebrew => "brew upgrade kintsugi-tools/tap/paper".into(),
77        InstallMethod::Npm => format!("npm install -g paperscope@{version}"),
78        InstallMethod::Cargo => format!("cargo install paperscope --locked --version {version}"),
79        InstallMethod::ShellInstaller => format!(
80            "curl -fsSL https://github.com/{REPO}/releases/download/v{version}/paperscope-installer.sh | sh"
81        ),
82        InstallMethod::Unknown => "paper update".into(),
83    }
84}
85
86/// Runs a program with null stdin; `env` pairs are added to the child.
87#[async_trait::async_trait]
88pub trait Runner: Send + Sync {
89    async fn run(
90        &self,
91        program: &str,
92        args: &[String],
93        env: &[(&str, &str)],
94        timeout: Duration,
95    ) -> Result<Output>;
96}
97
98pub struct TokioRunner;
99
100#[async_trait::async_trait]
101impl Runner for TokioRunner {
102    async fn run(
103        &self,
104        program: &str,
105        args: &[String],
106        env: &[(&str, &str)],
107        timeout: Duration,
108    ) -> Result<Output> {
109        let child = tokio::process::Command::new(program)
110            .args(args)
111            .envs(env.iter().copied())
112            .stdin(std::process::Stdio::null())
113            .stdout(std::process::Stdio::piped())
114            .stderr(std::process::Stdio::piped())
115            .kill_on_drop(true)
116            .spawn()
117            .with_context(|| format!("start {program}"))?;
118        tokio::time::timeout(timeout, child.wait_with_output())
119            .await
120            .map_err(|_| anyhow::anyhow!("{program} timed out after {}s", timeout.as_secs()))?
121            .with_context(|| format!("run {program}"))
122    }
123}
124
125/// Not an error: nothing can be installed right now, retry tomorrow.
126#[derive(Debug)]
127struct Unavailable(String);
128impl std::fmt::Display for Unavailable {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        f.write_str(&self.0)
131    }
132}
133impl std::error::Error for Unavailable {}
134
135fn truncate(s: &str) -> String {
136    s.trim().chars().take(300).collect()
137}
138
139fn output_text(out: &Output) -> String {
140    let err = String::from_utf8_lossy(&out.stderr);
141    let text = if err.trim().is_empty() {
142        String::from_utf8_lossy(&out.stdout)
143    } else {
144        err
145    };
146    truncate(&text)
147}
148
149fn args(list: &[&str]) -> Vec<String> {
150    list.iter().map(|s| s.to_string()).collect()
151}
152
153/// Is `version` published to this method's source yet?
154async fn available(
155    method: &InstallMethod,
156    version: &str,
157    runner: &dyn Runner,
158    client: &reqwest::Client,
159) -> Result<bool> {
160    match method {
161        InstallMethod::Homebrew => {
162            let out = runner
163                .run(
164                    "brew",
165                    &args(&["info", "--json=v2", "kintsugi-tools/tap/paper"]),
166                    &[],
167                    SHORT,
168                )
169                .await?;
170            if !out.status.success() {
171                bail!("brew info failed: {}", output_text(&out));
172            }
173            let json: serde_json::Value = serde_json::from_slice(&out.stdout)?;
174            Ok(json["formulae"][0]["versions"]["stable"].as_str() == Some(version))
175        }
176        InstallMethod::Npm => {
177            let out = runner
178                .run(
179                    "npm",
180                    &args(&["view", &format!("paperscope@{version}"), "version"]),
181                    &[],
182                    SHORT,
183                )
184                .await?;
185            // npm view exits non-zero (E404) for an unpublished version.
186            Ok(out.status.success() && !out.stdout.trim_ascii().is_empty())
187        }
188        InstallMethod::Cargo => {
189            let body = client
190                .get("https://index.crates.io/pa/pe/paperscope")
191                .send()
192                .await?
193                .error_for_status()?
194                .text()
195                .await?;
196            Ok(body.contains(&format!("\"vers\":\"{version}\"")))
197        }
198        InstallMethod::ShellInstaller => {
199            let url = format!("https://github.com/{REPO}/releases/download/v{version}/sha256.sum");
200            Ok(client.head(url).send().await?.status() == reqwest::StatusCode::OK)
201        }
202        InstallMethod::Unknown => Err(Unavailable("install method not recognised".into()).into()),
203    }
204}
205
206/// Poll the resource guard every `every` for up to `max`.
207async fn wait_idle(guard: &ResourceGuard, every: Duration, max: Duration) -> bool {
208    let start = std::time::Instant::now();
209    loop {
210        if !guard.check_now().await {
211            return true;
212        }
213        if start.elapsed() >= max {
214            return false;
215        }
216        tokio::time::sleep(every).await;
217    }
218}
219
220async fn run_checked(
221    runner: &dyn Runner,
222    program: &str,
223    argv: &[String],
224    env: &[(&str, &str)],
225    timeout: Duration,
226) -> Result<()> {
227    let out = runner.run(program, argv, env, timeout).await?;
228    if !out.status.success() {
229        bail!(
230            "{program} exited with {}: {}",
231            out.status,
232            output_text(&out)
233        );
234    }
235    Ok(())
236}
237
238async fn install(
239    method: &InstallMethod,
240    version: &str,
241    exe: &Path,
242    runner: &dyn Runner,
243    client: &reqwest::Client,
244    guard: &ResourceGuard,
245) -> Result<()> {
246    match method {
247        InstallMethod::Homebrew => {
248            run_checked(
249                runner,
250                "brew",
251                &args(&["upgrade", "kintsugi-tools/tap/paper"]),
252                &[],
253                SHORT,
254            )
255            .await
256        }
257        InstallMethod::Npm => {
258            let spec = format!("paperscope@{version}");
259            run_checked(runner, "npm", &args(&["install", "-g", &spec]), &[], SHORT).await
260        }
261        InstallMethod::Cargo => {
262            let have = runner
263                .run("which", &args(&["cargo"]), &[], SHORT)
264                .await
265                .is_ok_and(|o| o.status.success());
266            if !have {
267                return Err(Unavailable("Rust toolchain not found".into()).into());
268            }
269            if !wait_idle(
270                guard,
271                Duration::from_secs(300),
272                Duration::from_secs(6 * 3600),
273            )
274            .await
275            {
276                return Err(Unavailable("machine never idle".into()).into());
277            }
278            let mut argv = args(&["install", "paperscope", "--locked", "--version", version]);
279            let program = if cfg!(unix) {
280                argv.splice(0..0, args(&["-n", "19", "cargo"]));
281                "nice"
282            } else {
283                "cargo"
284            };
285            run_checked(runner, program, &argv, &[], CARGO_TIMEOUT).await
286        }
287        InstallMethod::ShellInstaller => {
288            if cfg!(windows) {
289                bail!("shell-installer updates are not automated on Windows");
290            }
291            install_shell(version, exe, runner, client).await
292        }
293        InstallMethod::Unknown => Err(Unavailable("install method not recognised".into()).into()),
294    }
295}
296
297/// The installer verifies the archive checksums itself.
298async fn install_shell(
299    version: &str,
300    exe: &Path,
301    runner: &dyn Runner,
302    client: &reqwest::Client,
303) -> Result<()> {
304    let url =
305        format!("https://github.com/{REPO}/releases/download/v{version}/paperscope-installer.sh");
306    let script = client
307        .get(url)
308        .send()
309        .await?
310        .error_for_status()?
311        .text()
312        .await
313        .context("download installer")?;
314    let dir = tempfile::tempdir()?;
315    let path = dir.path().join("paperscope-installer.sh");
316    std::fs::write(&path, script)?;
317    std::fs::copy(exe, old_path(exe)).context("keep the current binary as .old")?;
318    let script_arg = [path.to_string_lossy().into_owned()];
319    run_checked(
320        runner,
321        "sh",
322        &script_arg,
323        &[("PAPER_NO_AUTOSTART", "1")],
324        SHORT,
325    )
326    .await
327}
328
329fn old_path(exe: &Path) -> PathBuf {
330    let mut s = exe.as_os_str().to_owned();
331    s.push(".old");
332    s.into()
333}
334
335struct Ctx<'a> {
336    dir: &'a Path,
337    method: &'a InstallMethod,
338    current: &'a str,
339    exe: &'a Path,
340    enabled: bool,
341    offline: bool,
342    today: NaiveDate,
343    runner: &'a dyn Runner,
344    client: &'a reqwest::Client,
345    guard: &'a ResourceGuard,
346    restart: &'a (dyn Fn() -> Result<()> + Sync),
347}
348
349fn record(
350    ctx: &Ctx<'_>,
351    outcome: &str,
352    approved: Option<&str>,
353    manual_command: Option<String>,
354    detail: Option<String>,
355) {
356    let state = UpdateState {
357        outcome: outcome.into(),
358        approved: approved.map(String::from),
359        method: method_name(ctx.method).into(),
360        manual_command,
361        detail,
362        at: chrono::Utc::now().to_rfc3339(),
363    };
364    if let Err(e) = write_update_state(ctx.dir, &state) {
365        tracing::warn!("could not write update.state: {e}");
366    }
367}
368
369/// Record `unavailable` for an `Unavailable` error, `failed` for anything else.
370fn record_error(ctx: &Ctx<'_>, version: &str, e: &anyhow::Error) {
371    let manual = Some(manual_command(ctx.method, version));
372    match e.downcast_ref::<Unavailable>() {
373        Some(u) => record(ctx, "unavailable", Some(version), manual, Some(u.0.clone())),
374        None => {
375            let detail = truncate(&format!("{e:#}"));
376            tracing::warn!("auto-update to {version} failed: {detail}");
377            record(ctx, "failed", Some(version), manual, Some(detail));
378        }
379    }
380}
381
382async fn run_with(ctx: &Ctx<'_>, approved: Option<&RemoteUpdate>) {
383    let last = read_update_state(ctx.dir);
384    let version = match decide(
385        ctx.current,
386        approved,
387        ctx.enabled,
388        ctx.offline,
389        last.as_ref(),
390        ctx.today,
391    ) {
392        Action::Install { version } => version,
393        Action::Nothing(outcome) => {
394            // A same-day failure and the "updated" notice stay as they are.
395            let keep = matches!(outcome, "failed" | "unavailable")
396                || (outcome == "up_to_date"
397                    && last.as_ref().is_some_and(|l| l.outcome == "updated"));
398            if !keep {
399                record(
400                    ctx,
401                    outcome,
402                    approved.map(|a| a.version.as_str()),
403                    None,
404                    None,
405                );
406            }
407            return;
408        }
409    };
410    match available(ctx.method, &version, ctx.runner, ctx.client).await {
411        Ok(true) => {}
412        Ok(false) => {
413            let detail = format!("{version} is not published for this install method yet");
414            let manual = Some(manual_command(ctx.method, &version));
415            return record(ctx, "unavailable", Some(&version), manual, Some(detail));
416        }
417        Err(e) => return record_error(ctx, &version, &e),
418    }
419    if let Err(e) = install(
420        ctx.method, &version, ctx.exe, ctx.runner, ctx.client, ctx.guard,
421    )
422    .await
423    {
424        return record_error(ctx, &version, &e);
425    }
426    record(
427        ctx,
428        "updated",
429        Some(&version),
430        None,
431        Some("restarting".into()),
432    );
433    // Last action: the service manager may kill this very process.
434    if let Err(e) = (ctx.restart)() {
435        let e = anyhow::anyhow!("update installed but restart failed: {e:#}");
436        record_error(ctx, &version, &e);
437    }
438}
439
440/// Settle a "restarting" state left by the previous process.
441fn check_restart(dir: &Path, current: &str, exe: &Path) {
442    let Some(mut state) = read_update_state(dir)
443        .filter(|s| s.outcome == "updated" && s.detail.as_deref() == Some("restarting"))
444    else {
445        return;
446    };
447    let old = old_path(exe);
448    if state.approved.as_deref() == Some(current) {
449        state.detail = None;
450        let _ = std::fs::remove_file(&old);
451    } else {
452        state.outcome = "failed".into();
453        state.detail = Some(SHADOW_HINT.into());
454        if state.method == "shell" && old.exists() {
455            let _ = std::fs::rename(&old, exe);
456        }
457    }
458    state.at = chrono::Utc::now().to_rfc3339();
459    let _ = write_update_state(dir, &state);
460}
461
462/// Once at daemon startup, before the daily loop.
463pub(super) fn check_after_restart() {
464    if let Ok(exe) = std::env::current_exe() {
465        check_restart(&crate::core::paths::Paths::new().base_dir(), CURRENT, &exe);
466    }
467}
468
469/// Daily entry point.
470pub(super) async fn run(workspace: &Workspace) {
471    let Ok(exe) = std::env::current_exe() else {
472        return;
473    };
474    let today = chrono::Local::now().date_naive();
475    let approved = load_live_remote(today).and_then(|r| r.update);
476    let Ok(client) = reqwest::Client::builder()
477        .user_agent(concat!("paper/", env!("CARGO_PKG_VERSION")))
478        .timeout(Duration::from_secs(30))
479        .build()
480    else {
481        return;
482    };
483    let dir = workspace.paths.base_dir();
484    let method = current_install_method();
485    let ctx = Ctx {
486        dir: &dir,
487        method: &method,
488        current: CURRENT,
489        exe: &exe,
490        enabled: auto_update_enabled(&workspace.config),
491        offline: crate::bootstrap::is_offline(),
492        today,
493        runner: &TokioRunner,
494        client: &client,
495        guard: &ResourceGuard::new(),
496        restart: &crate::cli::daemon::restart_service,
497    };
498    run_with(&ctx, approved.as_ref()).await;
499}
500
501#[cfg(all(test, unix))]
502mod tests {
503    use super::*;
504    use std::os::unix::process::ExitStatusExt;
505    use std::sync::Mutex;
506
507    /// Replies by `(program, first arg or "*")`: (exit code, stdout, stderr).
508    type Reply = (&'static str, &'static str, i32, &'static str, &'static str);
509    struct Fake {
510        replies: Vec<Reply>,
511        calls: Mutex<Vec<String>>,
512    }
513    impl Fake {
514        fn new(replies: Vec<Reply>) -> Self {
515            Fake {
516                replies,
517                calls: Mutex::new(vec![]),
518            }
519        }
520        fn count(&self) -> usize {
521            self.calls.lock().unwrap().len()
522        }
523    }
524    #[async_trait::async_trait]
525    impl Runner for Fake {
526        async fn run(
527            &self,
528            program: &str,
529            argv: &[String],
530            _env: &[(&str, &str)],
531            _t: Duration,
532        ) -> Result<Output> {
533            self.calls
534                .lock()
535                .unwrap()
536                .push(format!("{program} {}", argv.join(" ")));
537            let first = argv.first().map_or("", String::as_str);
538            let (_, _, code, out, err) = self
539                .replies
540                .iter()
541                .find(|r| r.0 == program && (r.1 == "*" || r.1 == first))
542                .copied()
543                .unwrap_or((program, "*", 127, "", "not scripted"));
544            Ok(Output {
545                status: std::process::ExitStatus::from_raw(code << 8),
546                stdout: out.as_bytes().to_vec(),
547                stderr: err.as_bytes().to_vec(),
548            })
549        }
550    }
551
552    fn today() -> NaiveDate {
553        chrono::Local::now().date_naive()
554    }
555    fn upd(v: &str) -> RemoteUpdate {
556        RemoteUpdate {
557            version: v.into(),
558            notes: None,
559        }
560    }
561    fn state(outcome: &str, approved: &str, at: String) -> UpdateState {
562        UpdateState {
563            outcome: outcome.into(),
564            approved: Some(approved.into()),
565            method: "npm".into(),
566            manual_command: None,
567            detail: None,
568            at,
569        }
570    }
571
572    struct Rig {
573        dir: tempfile::TempDir,
574        guard: ResourceGuard,
575        client: reqwest::Client,
576        restarts: Mutex<u32>,
577    }
578    impl Rig {
579        fn new() -> Self {
580            Rig {
581                dir: tempfile::tempdir().unwrap(),
582                guard: ResourceGuard::new(),
583                client: reqwest::Client::new(),
584                restarts: Mutex::new(0),
585            }
586        }
587        async fn go(&self, runner: &Fake, restart_ok: bool) {
588            let exe = self.dir.path().join("paper");
589            let restart = || -> Result<()> {
590                *self.restarts.lock().unwrap() += 1;
591                if restart_ok {
592                    Ok(())
593                } else {
594                    bail!("no service")
595                }
596            };
597            let ctx = Ctx {
598                dir: self.dir.path(),
599                method: &InstallMethod::Npm,
600                current: "0.4.1",
601                exe: &exe,
602                enabled: true,
603                offline: false,
604                today: today(),
605                runner,
606                client: &self.client,
607                guard: &self.guard,
608                restart: &restart,
609            };
610            run_with(&ctx, Some(&upd("0.4.2"))).await;
611        }
612        fn st(&self) -> UpdateState {
613            read_update_state(self.dir.path()).unwrap()
614        }
615    }
616
617    #[test]
618    fn decide_never_downgrades_or_reinstalls() {
619        for approved in ["0.4.1", "0.4.0", "0.3.9"] {
620            assert_eq!(
621                decide("0.4.1", Some(&upd(approved)), true, false, None, today()),
622                Action::Nothing("up_to_date")
623            );
624        }
625        assert_eq!(
626            decide("0.4.1", None, true, false, None, today()),
627            Action::Nothing("up_to_date")
628        );
629        let a = upd("0.4.2");
630        let install = Action::Install {
631            version: "0.4.2".into(),
632        };
633        assert_eq!(
634            decide("0.4.1", Some(&a), true, false, None, today()),
635            install
636        );
637        // Yesterday's failure retries; today's does not; another version does.
638        let now = chrono::Utc::now().to_rfc3339();
639        let old = (chrono::Utc::now() - chrono::Duration::days(2)).to_rfc3339();
640        let d = |s: UpdateState| decide("0.4.1", Some(&a), true, false, Some(&s), today());
641        assert_eq!(d(state("failed", "0.4.2", old)), install);
642        assert_eq!(
643            d(state("failed", "0.4.2", now.clone())),
644            Action::Nothing("failed")
645        );
646        assert_eq!(
647            d(state("unavailable", "0.4.2", now.clone())),
648            Action::Nothing("unavailable")
649        );
650        assert_eq!(d(state("failed", "0.4.0", now)), install);
651    }
652
653    #[test]
654    fn decide_respects_offline_and_opt_out() {
655        let a = upd("0.4.2");
656        let d = |enabled, offline| decide("0.4.1", Some(&a), enabled, offline, None, today());
657        assert_eq!(d(true, true), Action::Nothing("offline"));
658        assert_eq!(d(false, false), Action::Nothing("opted_out"));
659        assert_eq!(d(false, true), Action::Nothing("offline"));
660    }
661
662    #[test]
663    fn manual_commands_per_method() {
664        let m = |method| manual_command(&method, "1.2.3");
665        assert_eq!(
666            m(InstallMethod::Homebrew),
667            "brew upgrade kintsugi-tools/tap/paper"
668        );
669        assert_eq!(m(InstallMethod::Npm), "npm install -g paperscope@1.2.3");
670        assert_eq!(
671            m(InstallMethod::Cargo),
672            "cargo install paperscope --locked --version 1.2.3"
673        );
674        assert_eq!(
675            m(InstallMethod::ShellInstaller),
676            "curl -fsSL https://github.com/kintsugi-tools/paperscope/releases/download/v1.2.3/paperscope-installer.sh | sh"
677        );
678        assert_eq!(m(InstallMethod::Unknown), "paper update");
679    }
680
681    #[tokio::test]
682    async fn failed_command_records_manual_command_and_does_not_retry_today() {
683        let rig = Rig::new();
684        let fake = Fake::new(vec![
685            ("npm", "view", 0, "0.4.2\n", ""),
686            ("npm", "install", 243, "", "EACCES: permission denied"),
687        ]);
688        rig.go(&fake, true).await;
689        let st = rig.st();
690        assert_eq!(st.outcome, "failed");
691        assert_eq!(
692            st.manual_command.as_deref(),
693            Some("npm install -g paperscope@0.4.2")
694        );
695        assert!(st.detail.unwrap().contains("EACCES"));
696        assert_eq!(*rig.restarts.lock().unwrap(), 0);
697        let calls = fake.count();
698        rig.go(&fake, true).await;
699        assert_eq!(fake.count(), calls, "no retry today");
700        assert_eq!(rig.st().outcome, "failed");
701    }
702
703    #[tokio::test]
704    async fn cargo_without_toolchain_is_unavailable_not_failed() {
705        let rig = Rig::new();
706        let fake = Fake::new(vec![("which", "*", 1, "", "")]);
707        let exe = rig.dir.path().join("paper");
708        let err = install(
709            &InstallMethod::Cargo,
710            "0.4.2",
711            &exe,
712            &fake,
713            &rig.client,
714            &rig.guard,
715        )
716        .await
717        .unwrap_err();
718        assert_eq!(
719            err.downcast_ref::<Unavailable>().unwrap().0,
720            "Rust toolchain not found"
721        );
722        assert_eq!(fake.count(), 1, "cargo itself never ran");
723    }
724
725    #[tokio::test]
726    async fn unpublished_version_is_unavailable() {
727        let rig = Rig::new();
728        let fake = Fake::new(vec![("npm", "view", 1, "", "E404 not found")]);
729        rig.go(&fake, true).await;
730        let st = rig.st();
731        assert_eq!(st.outcome, "unavailable");
732        assert_eq!(st.approved.as_deref(), Some("0.4.2"));
733        assert_eq!(fake.count(), 1, "only the availability probe ran");
734        assert_eq!(*rig.restarts.lock().unwrap(), 0);
735    }
736
737    fn npm_ok() -> Fake {
738        Fake::new(vec![("npm", "*", 0, "0.4.2\n", "")])
739    }
740
741    #[tokio::test]
742    async fn successful_install_records_restarting_then_updated_on_matching_start() {
743        let rig = Rig::new();
744        rig.go(&npm_ok(), true).await;
745        let st = rig.st();
746        assert_eq!(
747            (st.outcome.as_str(), st.detail.as_deref()),
748            ("updated", Some("restarting"))
749        );
750        assert_eq!(*rig.restarts.lock().unwrap(), 1);
751        let exe = rig.dir.path().join("paper");
752        std::fs::write(old_path(&exe), "old").unwrap();
753        check_restart(rig.dir.path(), "0.4.2", &exe);
754        let st = rig.st();
755        assert_eq!((st.outcome.as_str(), st.detail), ("updated", None));
756        assert!(!old_path(&exe).exists());
757    }
758
759    #[tokio::test]
760    async fn restart_failure_records_failed_with_manual_command() {
761        let rig = Rig::new();
762        rig.go(&npm_ok(), false).await;
763        let st = rig.st();
764        assert_eq!(st.outcome, "failed");
765        assert!(st.manual_command.is_some());
766    }
767
768    #[tokio::test]
769    async fn post_restart_version_mismatch_is_reported_once() {
770        let rig = Rig::new();
771        rig.go(&npm_ok(), true).await;
772        let exe = rig.dir.path().join("paper");
773        check_restart(rig.dir.path(), "0.4.1", &exe);
774        let st = rig.st();
775        assert_eq!(st.outcome, "failed");
776        assert_eq!(st.detail.as_deref(), Some(SHADOW_HINT));
777        check_restart(rig.dir.path(), "0.4.1", &exe);
778        assert_eq!(rig.st(), st, "second start leaves it alone");
779    }
780}