Skip to main content

windows_headless/
commands.rs

1//! Command implementations behind the thin CLI in `main.rs`.
2//!
3//! Each `cmd_*` takes plain params (no clap types) so the logic is callable
4//! from tests and other frontends. Cache-dir and arch defaults live here.
5//!
6//! Stream rule: stdout carries primary data only (`gen` XML, `report`
7//! table, `guest exec` output). All status, progress, prompts, warnings,
8//! and ready lines go to stderr — the CLI stays pipe-safe.
9use anyhow::{Context, Result};
10use std::path::{Path, PathBuf};
11use std::time::Duration;
12
13use crate::ipc::{MON_SOCK_NAME, QMP_SOCK_NAME, SERIAL_LOG_NAME, vm_endpoint};
14use crate::qemu::{
15    Display, HeadlessVmBuilder, PROVEN_SSH_HOST, PROVEN_SSH_PORT, PROVEN_VNC_PASSWORD,
16    WindowsVersion, qmp_alive, vnc_url,
17};
18use crate::storage::DiskManager;
19use crate::timeouts;
20use crate::unattend::{Architecture, VmConfig, auto_detect_platform};
21use crate::vision::{
22    SampleOutcome, SamplingProfile, ScreenSampler, ScreenState, describe, fmt_bytes, fmt_secs,
23    is_error_state, take_screenshot,
24};
25
26/// Disk partitioning script laid onto the installer USB (`setup/part.txt`).
27const PART_TXT: &str = include_str!("../setup/part.txt");
28
29/// Guest arch: explicit `--arch` wins, else the host arch (HVF/KVM require
30/// host == guest, so the default is almost always right).
31pub fn resolve_arch(a: Option<Architecture>) -> Architecture {
32    a.unwrap_or_else(|| auto_detect_platform().0)
33}
34
35/// Scratch dir that deletes itself on drop (all exit paths except SIGKILL).
36/// `create` purges any stale contents first (previous kill's leftovers).
37pub struct ScratchDir(PathBuf);
38
39impl ScratchDir {
40    pub fn create(dir: &Path) -> Result<Self> {
41        if dir.exists() {
42            eprintln!("purging stale scratch {}", dir.display());
43            std::fs::remove_dir_all(dir)?;
44        }
45        std::fs::create_dir_all(dir)?;
46        Ok(Self(dir.to_path_buf()))
47    }
48}
49
50impl Drop for ScratchDir {
51    fn drop(&mut self) {
52        if let Err(e) = std::fs::remove_dir_all(&self.0) {
53            eprintln!(
54                "warning: scratch cleanup failed ({}): {e:#}",
55                self.0.display()
56            );
57        }
58    }
59}
60
61/// Default VM dir: project cache `vms/win11` (created, never evicted —
62/// disk images are tens of GB), or `./win11-vm` without the downloader
63/// feature (no cache-manager available).
64#[cfg(feature = "downloader")]
65pub fn default_vm_dir() -> Result<PathBuf> {
66    let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_VM_DIR")?;
67    Ok(root.ensure_group(crate::paths::VM_GROUP)?)
68}
69
70#[cfg(not(feature = "downloader"))]
71pub fn default_vm_dir() -> Result<PathBuf> {
72    Ok(PathBuf::from(crate::paths::FALLBACK_VM_DIR))
73}
74
75/// Default USB installer image: project cache `media/winusb.dmg`
76/// (created, never evicted — 10 GB, slow to rebuild), or `./winusb.dmg`
77/// without the downloader feature. `$WINDOWS_HEADLESS_MEDIA_DIR` overrides
78/// the cache base, mirroring the ISO cache.
79#[cfg(feature = "downloader")]
80pub fn default_media_image() -> Result<PathBuf> {
81    let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_MEDIA_DIR")?;
82    Ok(root
83        .ensure_group(crate::paths::MEDIA_GROUP)?
84        .join(crate::paths::WINUSB_IMAGE))
85}
86
87#[cfg(not(feature = "downloader"))]
88pub fn default_media_image() -> Result<PathBuf> {
89    Ok(PathBuf::from(crate::paths::FALLBACK_WINUSB_IMAGE))
90}
91
92/// Expand a leading `~` (shells don't expand it inside quotes, so
93/// `'~/Downloads/x.iso'` arrives literally — observed live as a bare
94/// ENOENT with no filename). `~` and `~/...` only; other users untouched.
95fn expand_tilde(p: PathBuf) -> PathBuf {
96    let s = p.to_string_lossy();
97    if let Some(rest) = s.strip_prefix("~/").or_else(|| (s == "~").then_some(""))
98        && let Ok(home) = std::env::var("HOME")
99    {
100        return PathBuf::from(home).join(rest);
101    }
102    p
103}
104
105/// Fail fast when the Windows ISO is absent, naming the path we actually
106/// resolved instead of guessing at a cause. The `~` hint is emitted only
107/// when a literal `~` survived [`expand_tilde`] — i.e. `HOME` was unset (or
108/// the path is `~otheruser/...`), which is the only way a `~` reaches here
109/// from either an unquoted or a quoted argument.
110fn require_win_iso(path: &Path) -> Result<()> {
111    if path.is_file() {
112        return Ok(());
113    }
114    let shown = path.display();
115    let raw = path.to_string_lossy();
116    if raw == "~" || raw.starts_with("~/") {
117        anyhow::bail!("Windows ISO not found: {shown} (`~` not expanded — is $HOME set?)");
118    }
119    if raw.starts_with('~') {
120        anyhow::bail!("Windows ISO not found: {shown} (`~otheruser` paths are not expanded)");
121    }
122    anyhow::bail!("Windows ISO not found: {shown}");
123}
124
125fn stage_local_dir(base: &Path, prefix: &str, out: &mut Vec<(String, Vec<u8>)>) -> Result<()> {
126    fn walk(base: &Path, rel: &str, prefix: &str, out: &mut Vec<(String, Vec<u8>)>) -> Result<()> {
127        let dir = if rel.is_empty() {
128            base.to_path_buf()
129        } else {
130            base.join(rel)
131        };
132        for e in std::fs::read_dir(&dir)? {
133            let e = e?;
134            let name = e.file_name().to_string_lossy().into_owned();
135            let rp = if rel.is_empty() {
136                name.clone()
137            } else {
138                format!("{rel}/{name}")
139            };
140            if e.file_type()?.is_dir() {
141                walk(base, &rp, prefix, out)?;
142            } else {
143                out.push((format!("{prefix}/{rp}"), std::fs::read(e.path())?));
144            }
145        }
146        Ok(())
147    }
148    walk(base, "", prefix, out)
149}
150
151// ---------------------------------------------------------------------------
152// gen
153// ---------------------------------------------------------------------------
154
155pub struct GenArgs {
156    pub username: String,
157    pub password: String,
158    pub locale: String,
159    pub autologon: bool,
160    pub unattend_dir: Option<PathBuf>,
161    pub arch: Option<Architecture>,
162}
163
164pub fn cmd_gen(a: GenArgs) -> Result<()> {
165    let cfg = VmConfig {
166        username: a.username,
167        password: a.password,
168        locale: a.locale,
169        auto_logon: a.autologon,
170        arch: resolve_arch(a.arch),
171        ..VmConfig::default()
172    };
173    let xml = cfg.generate_unattend_xml();
174    if let Some(dir) = a.unattend_dir {
175        let f = DiskManager::ensure_unattend_dir(&dir, &xml)?;
176        eprintln!("wrote {}", f.display());
177    } else {
178        println!("{xml}");
179    }
180    Ok(())
181}
182
183// ---------------------------------------------------------------------------
184// build-media
185// ---------------------------------------------------------------------------
186
187pub struct BuildMediaArgs {
188    pub win_iso: PathBuf,
189    pub arch: Option<Architecture>,
190    pub virtio_iso: Option<PathBuf>,
191    pub drivers_dir: Option<PathBuf>,
192    pub openssh_zip: Option<PathBuf>,
193    pub out: Option<PathBuf>,
194    pub wimlib_bin: Option<PathBuf>,
195    pub username: String,
196    pub password: String,
197    pub locale: String,
198    /// Rebuild even when the output image + sidecar already exist.
199    pub force: bool,
200}
201
202/// The `build` pipeline: `setup` (fetch deps) + `build-media` (USB image).
203/// One command, one artifact. Requires the downloader feature (fetching is
204/// the whole point); the hidden `build-media` stays for no-fetch flows.
205#[cfg(feature = "downloader")]
206pub struct BuildArgs {
207    pub win_iso: PathBuf,
208    pub arch: Option<Architecture>,
209    pub username: String,
210    pub password: String,
211    pub locale: String,
212    pub out: Option<PathBuf>,
213    pub force: bool,
214}
215
216#[cfg(feature = "downloader")]
217pub async fn cmd_build(a: BuildArgs) -> Result<PathBuf> {
218    // The ISO is the one input `setup` cannot fetch, so check it BEFORE the
219    // downloads: a bad path must fail in milliseconds, not after gigabytes.
220    require_win_iso(&expand_tilde(a.win_iso.clone()))?;
221    cmd_setup(None, a.arch).await?;
222    // Resolve the media path here (same rule as build-media) so callers
223    // chaining into `install` know which image came out.
224    let out = a.out.map(expand_tilde).unwrap_or(default_media_image()?);
225    cmd_build_media(BuildMediaArgs {
226        win_iso: a.win_iso,
227        arch: a.arch,
228        virtio_iso: None,
229        drivers_dir: None,
230        openssh_zip: None,
231        out: Some(out.clone()),
232        wimlib_bin: None,
233        username: a.username,
234        password: a.password,
235        locale: a.locale,
236        force: a.force,
237    })
238    .await?;
239    Ok(out)
240}
241
242pub async fn cmd_build_media(a: BuildMediaArgs) -> Result<()> {
243    use crate::media::{
244        MediaSpec, build_installer_media, extract_iso_file_to_disk, extract_virtio_netkvm,
245        list_iso_tree, split_wim,
246    };
247    let arch = resolve_arch(a.arch);
248    let out = a.out.map(expand_tilde).unwrap_or(default_media_image()?);
249    let win_iso = expand_tilde(a.win_iso);
250    // Freshness skip: output + sidecar both present means a completed
251    // build (sidecar is written last). `--force` rebuilds regardless.
252    // Stale inputs with a fresh output are the user's explicit choice.
253    if !a.force && out.is_file() && crate::provenance::Provenance::sidecar_path(&out).is_file() {
254        eprintln!(
255            "already built: {} (sidecar present; --force to rebuild)",
256            out.display()
257        );
258        return Ok(());
259    }
260
261    // ISO first, honest error, before any state changes: a missing input
262    // must not invalidate a good sidecar or stage the driver archives.
263    require_win_iso(&win_iso)?;
264
265    // Invalidate first: a crashed/failed build must never leave a previous
266    // sidecar next to a partial image, or the next run skips as "fresh"
267    // over garbage (observed live: unusable image reported fresh).
268    crate::provenance::Provenance::invalidate(&out);
269
270    // Vendored wimlib: explicit --wimlib-bin wins, else the pinned tree
271    // from `fetch-wimlib` (same pattern as `run`). Keep the tag alongside
272    // for the provenance sidecar.
273    let (wimlib_tag, wimlib_bin) = match a.wimlib_bin {
274        Some(b) => ("explicit --wimlib-bin".to_string(), b),
275        None => {
276            #[cfg(feature = "downloader")]
277            {
278                let w = crate::qemu_portable::pinned_cached_wimlib()?;
279                eprintln!("using pinned portable wimlib {}", w.version);
280                (w.version.clone(), w.wimlib_bin())
281            }
282            #[cfg(not(feature = "downloader"))]
283            {
284                ("PATH".to_string(), PathBuf::from("wimlib-imagex"))
285            }
286        }
287    };
288    eprintln!("building installer media from {} ...", win_iso.display());
289    // Driver inputs default to the ISO cache (`setup` fetches them):
290    // explicit flags win, else `<iso-cache>/virtio-win.iso` and the
291    // per-arch OpenSSH zip. Missing files bail with the fix
292    // (`setup`), not a bare NotFound.
293    #[cfg(feature = "downloader")]
294    let iso_cache = crate::downloader::iso_cache_dir()?;
295    let openssh_zip = match a.openssh_zip.map(expand_tilde) {
296        Some(p) => p,
297        None => {
298            #[cfg(feature = "downloader")]
299            {
300                let p = iso_cache.join(arch.openssh_zip_name());
301                if !p.exists() {
302                    anyhow::bail!(
303                        "{} missing (run `setup` first, or pass --openssh-zip)",
304                        p.display()
305                    );
306                }
307                eprintln!("using cached {}", p.display());
308                p
309            }
310            #[cfg(not(feature = "downloader"))]
311            {
312                anyhow::bail!("pass --openssh-zip <zip>");
313            }
314        }
315    };
316    let xml = VmConfig {
317        username: a.username.clone(),
318        password: a.password.clone(),
319        locale: a.locale.clone(),
320        arch,
321        ..VmConfig::default()
322    }
323    .generate_unattend_xml();
324    // Drivers: explicit tree wins; else extract NetKVM from the
325    // virtio ISO in-crate (pure Rust, no host tools). Remember which
326    // ISO was used for the provenance sidecar (`None` = --drivers-dir).
327    let mut virtio_used: Option<PathBuf> = None;
328    let mut staged = vec![
329        (crate::paths::UNATTEND_XML.to_string(), xml.into_bytes()),
330        (
331            crate::paths::PART_TXT_PATH.to_string(),
332            PART_TXT.as_bytes().to_vec(),
333        ),
334        (
335            format!("{}/{}", crate::paths::TOOLS_DIR, arch.openssh_zip_name()),
336            std::fs::read(&openssh_zip)?,
337        ),
338    ];
339    match (
340        a.drivers_dir.map(expand_tilde),
341        a.virtio_iso.map(expand_tilde),
342    ) {
343        (Some(dir), _) => stage_local_dir(&dir, crate::paths::DRIVERS_STAGE_DIR, &mut staged)?,
344        (None, Some(iso)) => {
345            staged.extend(extract_virtio_netkvm(&iso, arch)?);
346            virtio_used = Some(iso);
347        }
348        (None, None) => {
349            #[cfg(feature = "downloader")]
350            {
351                let p = iso_cache.join(crate::paths::VIRTIO_ISO);
352                if !p.exists() {
353                    anyhow::bail!(
354                        "{} missing (run `setup` first, or pass --virtio-iso/--drivers-dir)",
355                        p.display()
356                    );
357                }
358                eprintln!("using cached {}", p.display());
359                staged.extend(extract_virtio_netkvm(&p, arch)?);
360                virtio_used = Some(p);
361            }
362            #[cfg(not(feature = "downloader"))]
363            {
364                anyhow::bail!("pass --virtio-iso <iso> or --drivers-dir <tree>");
365            }
366        }
367    }
368    // install.wim must reach wimlib as a file: stream it straight to
369    // scratch on disk (7 GB). The old `read_iso_tree` + `fs::write` path
370    // held the whole WIM in RAM first; the streaming extractor also
371    // tolerates the UDF variants hadris-udf rejects with
372    // `invalid Information Control Block` (isomage first, hadris fallback).
373    eprintln!("extracting install.wim (several minutes) ...");
374    // Deterministic scratch under the project cache (not $TMPDIR):
375    // a previous killed/failed run leaves it behind, so purge-then-
376    // reuse. The Drop guard removes it on every exit path — success,
377    // `?` early-return, panic unwind — so only SIGKILL can orphan it
378    // (and the next run's purge collects that too). Peak ~14 GB
379    // (install.wim + SWM parts); $TMPDIR orphans used to accumulate
380    // one full set per aborted run.
381    #[cfg(feature = "downloader")]
382    let scratch_root = crate::downloader::iso_cache_dir()?
383        .parent()
384        .map(|p| p.join("scratch"))
385        .unwrap_or_else(std::env::temp_dir);
386    #[cfg(not(feature = "downloader"))]
387    let scratch_root: PathBuf = std::env::temp_dir();
388    let scratch = scratch_root.join("build-media");
389    let _scratch_guard = ScratchDir::create(&scratch)?;
390    let wim_path = scratch.join("install.wim");
391    extract_iso_file_to_disk(&win_iso, "sources/install.wim", &wim_path).map_err(|e| {
392        let size = std::fs::metadata(&win_iso).map(|m| m.len()).unwrap_or(0);
393        anyhow::anyhow!(
394            "extract sources/install.wim from {} (ISO {} bytes): {e:#}\n\
395             hint: verify the ISO is a complete, untruncated download \
396             (compare its size/hash against your Microsoft download source, \
397             then re-download or re-copy it if it differs)",
398            win_iso.display(),
399            size
400        )
401    })?;
402    let wim_len = std::fs::metadata(&wim_path).map(|m| m.len()).unwrap_or(0);
403    eprintln!("media: install.wim extracted ({} bytes)", wim_len);
404    eprintln!("splitting install.wim with {} ...", wimlib_bin.display());
405    let swm_prefix = scratch.join("install.swm");
406    let swm_parts = split_wim(&wimlib_bin, &wim_path, &swm_prefix)?;
407    // Provenance while install.wim still exists (wimlib info query),
408    // sidecar written after the image build succeeds below.
409    #[cfg(feature = "downloader")]
410    let qemu_tag = crate::qemu_portable::pinned_cached()
411        .map(|q| q.version)
412        .unwrap_or_else(|_| "none cached".to_string());
413    #[cfg(not(feature = "downloader"))]
414    let qemu_tag = "unknown (no downloader feature)".to_string();
415    let provenance = crate::provenance::Provenance::gather(
416        &win_iso,
417        &wimlib_bin,
418        &wim_path,
419        arch,
420        &qemu_tag,
421        &wimlib_tag,
422        virtio_used.as_deref(),
423        &a.username,
424        &a.locale,
425    )?;
426    std::fs::remove_file(&wim_path)?;
427    // List ISO tree paths without reading content — files are streamed
428    // one at a time during image build (peak ~600 MB vs ~6 GB).
429    let subtree_skip: (String, Vec<String>) = ("sources".into(), ["install.wim".into()].into());
430    let iso_paths = list_iso_tree(
431        &win_iso,
432        &["efi".into(), "boot".into()],
433        &[],
434        Some(&subtree_skip),
435    )?;
436    let spec = MediaSpec {
437        iso: win_iso.clone(),
438        out: out.clone(),
439        size_bytes: 10 * 1024 * 1024 * 1024,
440        label: "WINSETUP".to_string(),
441        iso_paths,
442        staged,
443        swm_parts,
444    };
445    build_installer_media(&spec)?;
446    eprintln!("wrote {}", out.display());
447    provenance.write_sidecar(&out)?;
448    Ok(())
449}
450
451// ---------------------------------------------------------------------------
452// run
453// ---------------------------------------------------------------------------
454
455pub struct RunArgs {
456    pub disk: Option<String>,
457    pub ssh_port: u16,
458    pub display: crate::qemu::Display,
459    /// Guest RAM in MB (parsed from Docker syntax by clap `value_parser`).
460    pub memory: u32,
461    /// Guest vCPUs (`--cpus`; `--smp` is an alias).
462    pub cpus: u32,
463    /// New-disk size in GB (install path only; parsed from Docker syntax).
464    pub disk_size: u32,
465    pub vm_dir: Option<PathBuf>,
466    pub qemu_dir: Option<PathBuf>,
467    pub username: String,
468    pub password: String,
469    pub shell: bool,
470    /// Opt into the experimental live snapshot resume (`savevm` state):
471    /// instant boot when it works. Default off — golden rewind always works.
472    pub live: bool,
473    /// Windows ISO: when the disk is missing, run the install chain
474    /// (setup + build-media + install) instead of bailing.
475    pub win_iso: Option<PathBuf>,
476    /// Budget for that install's SSH wait, in seconds (`run` passes it
477    /// straight through; only reached when `--win-iso` installs).
478    pub install_timeout_secs: u64,
479    /// Screendump cadence during the boot wait in seconds (0 = disabled);
480    /// frames land in `<vm-dir>/screenshots/`.
481    pub screenshots_every_secs: u64,
482    /// In-memory screen-classification cadence in seconds: `Some(0)` =
483    /// disabled, `None` = profile default from the accelerator (10s
484    /// hardware, 30s TCG). Screendump + nearest-exemplar match with no
485    /// disk write.
486    pub classify_every_secs: Option<u64>,
487}
488
489/// Install params for the `run --win-iso` chain (missing disk): everything
490/// the user sized carries through, nothing silently resets to defaults.
491/// Split out so a test pins the passthrough (the screenshot cadence was
492/// once hardcoded to 60 here while `run` advertised the flag).
493fn run_chain_install_params(a: &RunArgs, iso: PathBuf) -> InstallParams {
494    InstallParams {
495        usb_image: None,
496        win_iso: Some(iso),
497        screenshots_every_secs: a.screenshots_every_secs,
498        classify_every_secs: a.classify_every_secs,
499        username: a.username.clone(),
500        password: a.password.clone(),
501        recovery: false,
502        auto_updates: false,
503        install_timeout_secs: a.install_timeout_secs,
504        memory_mb: a.memory,
505        cpus: a.cpus,
506        disk_size_gb: a.disk_size,
507        display: a.display.clone(),
508    }
509}
510
511pub async fn cmd_run(a: RunArgs) -> Result<()> {
512    let vm_dir = match a.vm_dir.clone() {
513        Some(d) => d,
514        None => default_vm_dir()?,
515    };
516    // Already running? Attach instead of booting: the qcow2 write lock
517    // would reject a second QEMU with a cryptic error. A live SSH banner
518    // is the ground truth (pidfile alone may be stale).
519    if banner_once(a.ssh_port).await.is_some() {
520        eprintln!(
521            "already running — ssh -p {} <username>@{PROVEN_SSH_HOST}",
522            a.ssh_port
523        );
524        if a.shell {
525            crate::ssh::interactive_shell(PROVEN_SSH_HOST, a.ssh_port, &a.username, &a.password)
526                .await?;
527        }
528        return Ok(());
529    }
530    let _ = std::fs::remove_file(vm_dir.join(crate::paths::QEMU_PIDFILE));
531    let disk = a.disk.clone().unwrap_or_else(|| {
532        vm_dir
533            .join(crate::paths::DISK_IMAGE)
534            .to_string_lossy()
535            .into_owned()
536    });
537    // A fresh `qemu-img create` shell is ~200 KB; anything under 1 GB holds
538    // no OS (a real install is tens of GB). Treat shells as missing so an
539    // interrupted install re-installs instead of booting into UEFI Shell
540    // forever (observed live: "guest: Shell>", zero SSH, eternal poll).
541    const MIN_VIABLE_DISK: u64 = 1024 * 1024 * 1024;
542    let disk_viable = std::fs::metadata(&disk)
543        .map(|m| m.len() >= MIN_VIABLE_DISK)
544        .unwrap_or(false);
545    if !disk_viable {
546        match a.win_iso.clone().map(expand_tilde) {
547            // Chain: install the disk, then fall through to boot it below.
548            // Uses the core only — no shell, no Ctrl-C wait mid-chain. The
549            // installer VM is torn down immediately so this command blocks
550            // exactly once (in the shared tail after boot), then drops into
551            // the guest shell. Explicit `--win-iso` only — never silent.
552            Some(iso) => {
553                eprintln!(
554                    "disk {disk} missing — installing from {} (new {}G disk, {} MB RAM, {} vCPUs) ...",
555                    iso.display(),
556                    a.disk_size,
557                    a.memory,
558                    a.cpus,
559                );
560                let mut session = install_to_ready(run_chain_install_params(&a, iso)).await?;
561                finish_install_capture(&mut session).await;
562                prove_landed_shell(PROVEN_SSH_PORT, &a.username, &a.password).await?;
563                let target = session.vm_dir.join(crate::paths::DISK_IMAGE);
564                let target_s = target.to_string_lossy().into_owned();
565                shutdown_guest_clean(PROVEN_SSH_HOST, PROVEN_SSH_PORT, &a.username, &a.password)
566                    .await?;
567                session.child.kill().await?;
568                snapshot_golden(&session.img_bin, &target_s).await?;
569            }
570            None => anyhow::bail!(
571                "disk {disk} does not exist (run `install` first, pass --disk <image>, or pass --win-iso to install it now)"
572            ),
573        }
574    }
575    // Stale serial from a previous session: drop it before the spawn.
576    // QEMU's chardev truncates on open, but the baseline below must be 0
577    // *without racing OVMF's first line* (reading after spawn often found
578    // the first `BdsDxe: starting` already written and swallowed the
579    // "guest booted" narration); an old file would also skew a pre-spawn
580    // read.
581    let _ = std::fs::remove_file(crate::ipc::vm_endpoint(
582        &vm_dir,
583        crate::ipc::SERIAL_LOG_NAME,
584    ));
585    let mut b = HeadlessVmBuilder::new(WindowsVersion::Win11)
586        .ssh_port(a.ssh_port)
587        .display(a.display.clone())
588        .memory_mb(a.memory)
589        .smp_cores(a.cpus)
590        .workdir(vm_dir);
591    match a.qemu_dir {
592        Some(d) => b = b.qemu_dir(d),
593        None => {
594            #[cfg(feature = "downloader")]
595            {
596                let q = crate::qemu_portable::pinned_cached()?;
597                eprintln!("using pinned portable QEMU {}", q.version);
598                b = b.qemu_dir(q.root);
599            }
600        }
601    }
602    // Golden rewind: a verified landed state rolls the disk past any
603    // dirty stop — Recovery can never appear on a rewound base. Applied
604    // (`snapshot -a`) rather than `-loadvm`: loadvm restores device state
605    // too, and QEMU refuses it with a writable pflash drive attached.
606    // Runs after qemu_dir resolution so the same portable qemu-img that
607    // wrote the snapshot applies it. Skipped under --live with a live
608    // snapshot present: the live state carries the disk, so rewinding
609    // first is pure waste (and costs a multi-GB copy for nothing).
610    let live_armed = a.live && live_sidecar(&disk).is_file();
611    if live_armed {
612        // Live resume prep, all pre-boot: the state file, VARS backup, and
613        // sidecar must all exist (a partial save resumes nothing); VARS is
614        // restored over the live file (raw pflash is outside every
615        // snapshot); the save-time overlay is consumed (its post-save
616        // writes are superseded by the rewind-to-save-point semantics).
617        let vm_dir_pb = b.workdir.clone();
618        let (state, vars_backup, overlay) = live_paths(&vm_dir_pb);
619        for p in [&state, &vars_backup] {
620            if !p.is_file() {
621                anyhow::bail!(
622                    "live sidecar present but {} is missing (partial save?) — delete {} and re-take with `snapshot --live`",
623                    p.display(),
624                    live_sidecar(&disk).display()
625                );
626            }
627        }
628        std::fs::copy(&vars_backup, vm_dir_pb.join(crate::paths::VARS_FILE))?;
629        if overlay.is_file() {
630            let _ = std::fs::remove_file(&overlay);
631            eprintln!("consuming save-time overlay (post-save writes superseded) ...");
632        }
633        eprintln!("resuming live state (RAM streams in over -incoming, no boot) ...");
634        b = b.incoming(migrate_read_uri(&state));
635    } else {
636        // Orphaned overlay without a live resume: its writes are
637        // unreachable once the base boots alone — drop it out loud rather
638        // than hoarding a dead file.
639        let workdir = b.workdir.clone();
640        let (_, _, overlay) = live_paths(&workdir);
641        if overlay.is_file() {
642            let _ = std::fs::remove_file(&overlay);
643            eprintln!(
644                "dropping orphaned live overlay {} (plain boot cannot reach it) ...",
645                overlay.file_name().unwrap_or_default().to_string_lossy()
646            );
647        }
648        if golden_sidecar(&disk).is_file() {
649            let img_bin = img_bin_for(&b.qemu_dir);
650            eprintln!("rewinding to golden snapshot (landed state) ...");
651            let st = tokio::process::Command::new(&img_bin)
652                .args(["snapshot", "-a", crate::timeouts::GOLDEN_TAG, &disk])
653                .status()
654                .await?;
655            if !st.success() {
656                anyhow::bail!(
657                    "golden sidecar present but snapshot apply failed — disk left untouched, refusing to boot a half-state (delete {} to boot normally)",
658                    golden_sidecar(&disk).display()
659                );
660            }
661        }
662    }
663    eprintln!(
664        "booting {disk} ({} MB RAM, {} vCPUs, display {})",
665        a.memory,
666        a.cpus,
667        a.display.as_arg()
668    );
669    eprintln!(
670        "waiting for SSH on {PROVEN_SSH_HOST}:{} (up to {} min) ...",
671        a.ssh_port,
672        timeouts::BOOT_SSH_DEADLINE.as_secs() / 60
673    );
674    // Stale serial from a previous session was dropped pre-spawn so the
675    // baseline below is 0 (never a post-spawn read racing OVMF's line).
676    let mut vm = b.boot_existing(&disk).await?;
677    // One monitor session for the whole boot: VNC handshake plus the stall
678    // watchdog below share it (single-client transports forbid overlap).
679    // Same retrying handshake as install (live-but-slow QEMU refuses early
680    // connects).
681    let mon = crate::ipc::Monitor::connect_retry(
682        &vm.builder.monitor_socket,
683        timeouts::MONITOR_CONNECT_SECS,
684        || vm.child.try_wait().map(|o| o.is_none()).unwrap_or(false),
685    )
686    .await?;
687    if a.display.is_vnc() {
688        mon.command(&vnc_password_command()).await?;
689        let url = vnc_url(&a.display.as_arg()).unwrap_or_else(|| a.display.as_arg());
690        eprintln!("VNC {url} (password {PROVEN_VNC_PASSWORD})");
691    }
692    // Opt-in live resume is fully pre-boot now (state streams in over
693    // `-incoming`, VARS + disk restored above): by the time the monitor is
694    // up the guest is already continuing, so SSH should answer in seconds.
695    if a.live {
696        let phase_start = std::time::Instant::now();
697        eprintln!("live state streaming in (2-3 GB over -incoming; watch it land) ...");
698        let deadline =
699            std::time::Instant::now() + Duration::from_secs(timeouts::MIGRATION_BUDGET_SECS);
700        loop {
701            let mut qmp = vm.qmp().await?;
702            match qmp.query_migrate_status().await?.as_str() {
703                "completed" => break,
704                "failed" | "cancelled" | "cancelling" => {
705                    anyhow::bail!(
706                        "incoming migration failed — state file may be truncated; re-take with `snapshot --live`"
707                    );
708                }
709                status => {
710                    if std::time::Instant::now() > deadline {
711                        anyhow::bail!(
712                            "incoming migration still '{status}' after {} s — state file unreadable or stream stalled; plain `run` (golden rewind) stays the default that works",
713                            timeouts::MIGRATION_BUDGET_SECS
714                        );
715                    }
716                    eprintln!("... incoming migration '{status}' ...");
717                    tokio::time::sleep(Duration::from_secs(timeouts::MIGRATION_POLL_SECS)).await;
718                }
719            }
720        }
721        eprintln!(
722            "live state loaded in {} s — guest resuming ...",
723            phase_start.elapsed().as_secs()
724        );
725        // Mirror of the save-side guard: a completed incoming stream can
726        // still leave the destination paused (login screen up, nothing
727        // executing — SSH can never answer). Verify running, resume if not.
728        // Then a stop/cont round-trip regardless: HVF may not re-arm
729        // halted-vCPU timers on the incoming path (frozen lock-screen
730        // clock, static frames), and the cycle re-arms them.
731        {
732            let mut qmp = vm.qmp().await?;
733            match qmp.query_vm_status().await?.as_str() {
734                "running" => eprintln!("guest executing after restore."),
735                stalled => {
736                    eprintln!("guest {stalled} after restore — resuming ...");
737                    qmp.resume_vm().await?;
738                }
739            }
740            eprintln!("re-arming guest timers (stop/cont cycle) ...");
741            qmp.pause_vm().await?;
742            tokio::time::sleep(Duration::from_secs(2)).await;
743            qmp.resume_vm().await?;
744            eprintln!(
745                "restore overhead total: {} s (stream + re-arm) — SSH settle next ...",
746                phase_start.elapsed().as_secs()
747            );
748        }
749        // The restored virtio-net rings point at the OLD slirp backend
750        // (gone with the saving QEMU): packets blackhole while Windows
751        // believes nothing changed — healthy desktop, dead SSH (observed).
752        // A link flap forces DHCP + NLA + the listener to re-run against
753        // the fresh backend. The NIC's device name comes from `info
754        // network` (auto-assigned, never guessed); best-effort throughout.
755        let nic = mon
756            .command("info network")
757            .await
758            .ok()
759            .and_then(|info| find_nic_name(&info).map(str::to_string))
760            .unwrap_or_else(|| "n1".to_string());
761        for (state, cmd) in [
762            ("down", format!("set_link {nic} off")),
763            ("up", format!("set_link {nic} on")),
764        ] {
765            if let Err(e) = mon.command(&cmd).await {
766                eprintln!("warning: link flap {state} failed ({e:#}); continuing without it ...");
767                break;
768            }
769            if state == "down" {
770                tokio::time::sleep(Duration::from_secs(3)).await;
771            }
772        }
773        // Classify the wire before the blind wait: refused means the guest
774        // stack is alive with nothing listening (sshd died in restore);
775        // timeout means packets blackhole (NIC/backend mismatch). The fix
776        // differs completely, so say which.
777        match classify_port(a.ssh_port).await {
778            PortState::Open => eprintln!(
779                "port {} accepts TCP — waiting for the SSH banner ...",
780                a.ssh_port
781            ),
782            PortState::Refused => eprintln!(
783                "port {} REFUSED (guest stack alive, sshd not listening — service did not survive restore)",
784                a.ssh_port
785            ),
786            PortState::Timeout => eprintln!(
787                "port {} connect timeout (packets blackholed — NIC/backend mismatch despite flap)",
788                a.ssh_port
789            ),
790        }
791        eprintln!("link flapped — waiting for SSH to re-bind ...");
792    }
793    if !a.live {
794        eprintln!("QEMU launched; guest is booting ...");
795    }
796    let pidfile = vm.builder.pidfile();
797    let start = std::time::Instant::now();
798    // One shots dir for the whole wait: periodic boot frames land here and
799    // every failure path captures its final frame into it too.
800    let shots_dir = screenshots_dir(&vm.builder.workdir);
801    let disk = vm.builder.workdir.join(crate::paths::DISK_IMAGE);
802    // Cadence policy resolves after accelerator detection: an explicit
803    // flag wins, else TCG earns 3x spacing on classification.
804    let profile = SamplingProfile::resolve(
805        a.screenshots_every_secs,
806        a.classify_every_secs,
807        auto_detect_platform().1,
808    );
809    if !profile.save_every.is_zero() {
810        eprintln!(
811            "Saving a boot screenshot every {}s → {}",
812            profile.save_every.as_secs(),
813            shots_dir.display()
814        );
815    }
816    if !profile.classify_every.is_zero() {
817        eprintln!(
818            "Classifying the boot screen every {}s (in memory, no file)",
819            profile.classify_every.as_secs()
820        );
821    }
822    // VNC coordinates for failure reports (None for gtk/cocoa/none — the
823    // frame + serial line still say what happened).
824    let vnc = a
825        .display
826        .is_vnc()
827        .then(|| vnc_url(&a.display.as_arg()).unwrap_or_else(|| a.display.as_arg()));
828    // Single tick authority: the profile's interval drives; save,
829    // classify, and narration each gate on their own due-check inside.
830    // All-zero cadences still need the SSH wait + stall watchdog, so fall
831    // back to the SSH poll interval (sampling simply never fires).
832    let tick_interval = profile.tick().unwrap_or(timeouts::SSH_POLL_INTERVAL);
833    let mut ticker = tokio::time::interval(tick_interval);
834    ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
835    // Skip the immediate first tick so the first status line comes
836    // after a full interval of actual waiting, not at launch.
837    ticker.tick().await;
838    // Stall sensor + screen state, reunited per tick: serial-silent deaths
839    // would otherwise poll SSH blindly.
840    let mon = std::sync::Arc::new(mon);
841    let mut activity = ActivityMonitor::new();
842    let mut sampler = ScreenSampler::new(std::sync::Arc::clone(&mon), shots_dir.clone());
843    // Reboot awareness below the screenshot layer: OVMF's per-boot handoff
844    // line in the serial file, so "the guest bounced" is announced even
845    // while the screen looks like nothing happened. Baseline 0 (the stale
846    // file was removed pre-spawn) — never a post-spawn read, which races
847    // OVMF's first line.
848    let mut boots_seen = 0u64;
849    // Narration due-check state: the "... still waiting" pulse on the
850    // profile's rhythm, never a second ticker.
851    let mut last_narrate = start;
852    tokio::select! {
853        r = vm.wait_for_ssh(timeouts::BOOT_SSH_DEADLINE) => {
854            // Time's up: the serial is silent through a Windows boot, so
855            // the screen + serial tail are the only evidence of *where*
856            // boot died (black handoff vs a parked Windows prompt —
857            // neither is guessable from the timeout alone). Attach both
858            // instead of dropping the frame on the floor.
859            if let Err(e) = r {
860                let report =
861                    boot_failure_report(&mon, &vm.builder.serial_log, &shots_dir, &vnc).await;
862                anyhow::bail!("{e:#}\n{report}");
863            }
864        }
865        cause = async {
866            loop {
867                ticker.tick().await;
868                // Dead-screen watchdog: a fatal serial signature means the
869                // boot already failed — return it as the cause instead of
870                // polling on.
871                check_boot_failure(&vm.builder.serial_log)?;
872                // Reboot narration (first boot or a bounce): serial truth,
873                // independent of what the screenshots look like.
874                let boots = boot_count(&vm.builder.serial_log);
875                if let Some(note) = boot_note(boots_seen, boots) {
876                    eprintln!("{note}");
877                }
878                boots_seen = boots;
879                // Sample first: the stall check below needs fresh counters.
880                activity.sample(&mon, Some(disk.as_path())).await;
881                // One sampler tick, then the reporter line. Save and
882                // classify gate inside; narration gates below.
883                sampler.poll(&profile).await;
884                // Stall watchdog, conditioned on screen state: frozen disk
885                // I/O during valid progress (Setup applying, OOBE) is a
886                // slow host, never a stuck guest — progress states answer
887                // only to the outer SSH deadline. Bail propagates out of
888                // the select arm below.
889                activity.check_stall(sampler.state(), true)?;
890                report_sample("boot", &sampler, &activity);
891                // Narrate the boot on the profile pulse only: last serial
892                // line says what the guest is doing (recovery, Boot Manager,
893                // Setup pass...). The ticker may run faster for
894                // classification; this line must not turn into spam.
895                if last_narrate.elapsed() < profile.narrate_every {
896                    continue;
897                }
898                last_narrate = std::time::Instant::now();
899                let doing = last_serial_line(&vm.builder.serial_log);
900                if doing.is_empty() {
901                    eprintln!(
902                        "... still waiting for SSH ({}s elapsed)",
903                        start.elapsed().as_secs()
904                    );
905                } else {
906                    eprintln!(
907                        "... still waiting for SSH ({}s elapsed) — guest: {doing}",
908                        start.elapsed().as_secs()
909                    );
910                }
911            }
912            #[allow(unreachable_code)]
913            Ok::<(), anyhow::Error>(())
914        } => {
915            // The loop only ever ends by erroring (its Ok arm is
916            // unreachable): carry the cause, then the evidence block —
917            // final frame with path + screen classification, last serial
918            // line, VNC coordinates — so the failure reads without VNC.
919            let cause =
920                cause.map_or_else(|e| format!("{e:#}"), |_| "guest failed to boot".to_string());
921            let report =
922                boot_failure_report(&mon, &vm.builder.serial_log, &shots_dir, &vnc).await;
923            eprintln!("stopping dead guest...");
924            vm.kill().await?;
925            let _ = std::fs::remove_file(pidfile);
926            anyhow::bail!("{cause}\n{report}");
927        }
928        _ = shutdown_signal() => {
929            eprintln!("interrupted during boot; stopping guest...");
930            if let Err(e) = vm.kill().await {
931                eprintln!("warning: kill failed: {e:#}");
932            }
933            let _ = std::fs::remove_file(pidfile);
934            return Ok(());
935        }
936    }
937    eprintln!(
938        "ready — ssh -p {} <user>@{PROVEN_SSH_HOST} (you will be prompted for credentials)",
939        a.ssh_port,
940    );
941    // Cooked mode, SIGINT/SIGTERM via shutdown_signal — the term-wm way.
942    // Raw mode was tried here (Ctrl-C as byte 0x03): under a multiplexer
943    // the byte path proved unreliable while kernel signals always land.
944    // Echo-trash during the wait is cosmetic; a non-exiting shutdown is
945    // functional. Never trade the latter for the former again.
946    // Ctrl-C means kill, immediately. No ACPI grace period by explicit
947    // user decision: a forgotten snapshot is the user's fault, and a
948    // 90-second wait that reads as a hang is worse than a dirty bit that
949    // chkdsk replays. The overlay/golden design absorbs the risk.
950    // A second branch watches the child: `snapshot` from another terminal
951    // quits this QEMU out from under us — exit with the news instead of
952    // parking at the Ctrl-C prompt on a dead VM.
953    tokio::select! {
954        r = shell_then_wait(
955            a.shell,
956            PROVEN_SSH_HOST,
957            a.ssh_port,
958            &a.username,
959            &a.password,
960            "press Ctrl-C to stop the VM (immediate kill, no graceful wait)...",
961        ) => {
962            r?;
963            eprintln!("killing guest...");
964            if let Err(e) = vm.kill().await {
965                eprintln!("warning: kill failed: {e:#}");
966            }
967        }
968        s = vm.child.wait() => {
969            match s {
970                Ok(status) => eprintln!("VM exited underneath us (status {status}) — e.g. `snapshot` from another terminal. Exiting ..."),
971                Err(e) => eprintln!("VM wait failed ({e:#}) — exiting ..."),
972            }
973        }
974    }
975    let _ = std::fs::remove_file(pidfile);
976    eprintln!("stopped");
977    Ok(())
978}
979
980// ---------------------------------------------------------------------------
981// install
982// ---------------------------------------------------------------------------
983
984/// Sidecar next to the disk proving a golden snapshot lives inside it.
985/// Written only after a verified landing; removed when an install starts,
986/// so a stale sidecar can never bless a half-written disk.
987pub fn golden_sidecar(disk: &str) -> PathBuf {
988    PathBuf::from(format!("{disk}.golden"))
989}
990
991/// Sidecar for the experimental live snapshot (`--live`): migrated RAM +
992/// device state plus VARS backup, kept strictly separate from golden so a
993/// failed live experiment can never confuse the rewind path.
994pub fn live_sidecar(disk: &str) -> PathBuf {
995    PathBuf::from(format!("{disk}.golden-live"))
996}
997
998/// NIC device name from HMP `info network` (first `type=nic` entry):
999/// auto-assigned by QEMU, never guessed — the flap must name the device,
1000/// not the netdev.
1001fn find_nic_name(info: &str) -> Option<&str> {
1002    info.lines().find_map(|l| {
1003        let l = l.trim();
1004        let (name, rest) = l.split_once(':')?;
1005        if rest.contains("type=nic") {
1006            Some(name.trim())
1007        } else {
1008            None
1009        }
1010    })
1011}
1012
1013/// One-shot TCP classification for the SSH port: does the restored guest
1014/// accept, refuse, or swallow SYNs? Decides between "sshd died" and
1015/// "packets blackholed" without a VNC session.
1016enum PortState {
1017    Open,
1018    Refused,
1019    Timeout,
1020}
1021
1022async fn classify_port(port: u16) -> PortState {
1023    match tokio::time::timeout(
1024        Duration::from_secs(5),
1025        tokio::net::TcpStream::connect((PROVEN_SSH_HOST, port)),
1026    )
1027    .await
1028    {
1029        Ok(Ok(_)) => PortState::Open,
1030        Ok(Err(_)) => PortState::Refused,
1031        Err(_) => PortState::Timeout,
1032    }
1033}
1034/// Shell-quote a path for QEMU `exec:` migration URIs (single-quote with
1035/// embedded quotes escaped — cache paths routinely contain spaces).
1036fn shell_quote(path: &Path) -> String {
1037    format!("'{}'", path.to_string_lossy().replace('\'', "'\\''"))
1038}
1039
1040/// Migration-write URI for `snapshot --live` (`migrate` streams the guest
1041/// out through `cat` into the state file).
1042pub fn migrate_write_uri(state: &Path) -> String {
1043    format!("exec:cat > {}", shell_quote(state))
1044}
1045
1046/// Migration-read URI for `run --live` (`-incoming` streams the state file
1047/// back into a fresh QEMU).
1048pub fn migrate_read_uri(state: &Path) -> String {
1049    format!("exec:cat {}", shell_quote(state))
1050}
1051
1052/// Live-snapshot companions inside the VM dir.
1053fn live_paths(vm_dir: &Path) -> (PathBuf, PathBuf, PathBuf) {
1054    (
1055        vm_dir.join(crate::paths::LIVE_STATE_FILE),
1056        vm_dir.join(crate::paths::LIVE_VARS_BACKUP),
1057        vm_dir.join(crate::paths::LIVE_OVERLAY),
1058    )
1059}
1060
1061/// Remove all live-snapshot remnants (announced): a new install or rewind
1062/// voids them — resuming post-save writes against a rewound base would
1063/// boot a half-state.
1064fn clear_live_state(vm_dir: &Path) {
1065    let disk = vm_dir
1066        .join(crate::paths::DISK_IMAGE)
1067        .to_string_lossy()
1068        .into_owned();
1069    let (state, vars, overlay) = live_paths(vm_dir);
1070    for p in [live_sidecar(&disk), state, vars, overlay] {
1071        if p.is_file() {
1072            let _ = std::fs::remove_file(&p);
1073            eprintln!(
1074                "dropping stale live snapshot file {} ...",
1075                p.file_name().unwrap_or_default().to_string_lossy()
1076            );
1077        }
1078    }
1079}
1080
1081/// Portable `qemu-img` for `qemu_dir` (resolved tree) or PATH fallback.
1082fn img_bin_for(qemu_dir: &Option<PathBuf>) -> PathBuf {
1083    match qemu_dir {
1084        Some(d) => d
1085            .join(crate::paths::PORTABLE_BIN_DIR)
1086            .join(crate::paths::QEMU_IMG_NAME),
1087        None => PathBuf::from(crate::paths::QEMU_IMG_NAME),
1088    }
1089}
1090
1091/// Prove the landed shell, deterministically: banner up, readiness probe
1092/// passing, and a real exec returning the right user. No clocks, no
1093/// windows — each check is present-tense evidence, and the snapshot below
1094/// is voided the moment the banner drops, so no prediction is needed.
1095async fn prove_landed_shell(port: u16, user: &str, password: &str) -> Result<()> {
1096    if banner_once(port).await.is_none() {
1097        anyhow::bail!("no SSH banner at snapshot time");
1098    }
1099    if !crate::ssh::probe_setup_done(PROVEN_SSH_HOST, port, user, password)
1100        .await
1101        .is_ok_and(|g| g.is_ready())
1102    {
1103        anyhow::bail!("guest not READY at snapshot time");
1104    }
1105    // LITERAL shell landing: a pty shell answering back, the exact path
1106    // a user login takes — not a banner read, not an exec probe.
1107    crate::ssh::prove_interactive_shell(PROVEN_SSH_HOST, port, user, password).await?;
1108    eprintln!("shell proven (prompt answered), saving golden ...");
1109    Ok(())
1110}
1111
1112/// Watch the golden snapshot's premise: any banner loss after snapshotting
1113/// means the guest bounced (the extra reboot the first banner never shows),
1114/// so the sidecar is deleted on the spot. Returns when voided. Safe
1115/// direction only: losing golden just means the next boot is normal.
1116async fn watch_golden_void(port: u16, disk: String) {
1117    loop {
1118        tokio::time::sleep(Duration::from_secs(15)).await;
1119        if banner_once(port).await.is_none() {
1120            let _ = std::fs::remove_file(golden_sidecar(&disk));
1121            eprintln!("guest bounced after golden — snapshot voided, next boot is normal ...");
1122            return;
1123        }
1124    }
1125}
1126
1127/// Clean guest shutdown ahead of a golden snapshot: `Stop-Computer` over
1128/// SSH, then wait for the banner to die (halted). Golden must capture a
1129/// clean bit — a QMP-quit power cut here would bake the dirty flag into
1130/// every future rewind. Loud failure instead of a dirty snapshot: the
1131/// caller reports, nothing is captured.
1132async fn shutdown_guest_clean(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
1133    eprintln!(
1134        "shutting guest down cleanly for snapshot (up to {} s) ...",
1135        timeouts::GUEST_SHUTDOWN_SECS
1136    );
1137    // Best-effort issue: if the guest is already dying, the banner wait
1138    // below still does the real gating.
1139    let _ = crate::ssh::ssh_exec(
1140        host,
1141        port,
1142        user,
1143        pass,
1144        "powershell -NoProfile -Command \"Stop-Computer -Force\"",
1145    )
1146    .await;
1147    let deadline = std::time::Instant::now() + Duration::from_secs(timeouts::GUEST_SHUTDOWN_SECS);
1148    // Two consecutive misses: a single loopback blip must not pass for a
1149    // halt with the guest still running (snapshotting that disk would
1150    // bless torn writes).
1151    let mut misses = 0u32;
1152    loop {
1153        if banner_once(port).await.is_none() {
1154            misses += 1;
1155            if misses >= 2 {
1156                eprintln!("guest halted.");
1157                return Ok(());
1158            }
1159        } else {
1160            misses = 0;
1161        }
1162        if std::time::Instant::now() > deadline {
1163            anyhow::bail!(
1164                "guest did not halt within {} s — refusing a dirty snapshot (stop it and retry)",
1165                timeouts::GUEST_SHUTDOWN_SECS
1166            );
1167        }
1168        tokio::time::sleep(Duration::from_secs(5)).await;
1169    }
1170}
1171
1172/// Disk-only golden snapshot of the landed state + sidecar. QEMU must
1173/// already be stopped (this runs post-kill): offline `qemu-img snapshot`
1174/// sidesteps live device state entirely — boots rewind with `snapshot -a`
1175/// and enumerate devices fresh, so pflash never blocks anything.
1176async fn snapshot_golden(img_bin: &Path, disk: &str) -> Result<()> {
1177    // Best-effort delete first: re-snapshotting over an existing tag must
1178    // not fail. Stderr nulled: deleting a nonexistent tag is the normal
1179    // first-snapshot case, not an error worth printing.
1180    use std::process::Stdio;
1181    let _ = tokio::process::Command::new(img_bin)
1182        .args(["snapshot", "-d", timeouts::GOLDEN_TAG, disk])
1183        .stderr(Stdio::null())
1184        .status()
1185        .await;
1186    let st = tokio::process::Command::new(img_bin)
1187        .args(["snapshot", "-c", timeouts::GOLDEN_TAG, disk])
1188        .status()
1189        .await?;
1190    if !st.success() {
1191        anyhow::bail!("qemu-img snapshot failed");
1192    }
1193    std::fs::write(
1194        golden_sidecar(disk),
1195        format!("{}\n", crate::provenance::now_epoch()),
1196    )?;
1197    eprintln!("golden snapshot saved — next boots resume in seconds.");
1198    Ok(())
1199}
1200
1201/// Live installer session: QEMU still running after the OS reports ready.
1202/// The caller owns the tail (capture a final frame, optionally offer a
1203/// shell, wait for Ctrl-C, kill) via the shared helpers below — `cmd_install`
1204/// supervises it, `cmd_run --win-iso` tears it down immediately and boots
1205/// the disk instead. One core, no pasted tails.
1206pub struct InstallSession {
1207    pub child: tokio::process::Child,
1208    pub mon: std::sync::Arc<crate::ipc::Monitor>,
1209    pub vm_dir: PathBuf,
1210    pub screenshots: Option<tokio::task::JoinHandle<()>>,
1211    /// `qemu-img` binary used for this install (for the post-kill golden
1212    /// snapshot — the session outlives the paths that found it).
1213    pub img_bin: PathBuf,
1214}
1215
1216/// Shared middle of the run/install tails (defined once, called twice):
1217/// optional guest shell, then block for Ctrl-C/SIGTERM. Killing stays with
1218/// the caller (run owns a `HeadlessVm` + pidfile, install owns a raw
1219/// `Child`), so this helper only covers the identical part.
1220async fn shell_then_wait(
1221    shell: bool,
1222    host: &str,
1223    port: u16,
1224    username: &str,
1225    password: &str,
1226    prompt: &str,
1227) -> Result<()> {
1228    if shell {
1229        crate::ssh::interactive_shell(host, port, username, password).await?;
1230        // The guest prompt never terminates its line — without this, the
1231        // wait prompt below lands mid-prompt (`C:\...>press Ctrl-C ...`).
1232        eprintln!();
1233    }
1234    eprintln!("{prompt}");
1235    shutdown_signal().await;
1236    Ok(())
1237}
1238
1239/// Shared installer capture step (defined once): stop the time-lapse, keep
1240/// one final desktop frame as evidence. Called by both the standalone
1241/// `install` tail and the `run --win-iso` chain teardown.
1242async fn finish_install_capture(session: &mut InstallSession) {
1243    if let Some(h) = session.screenshots.take() {
1244        h.abort();
1245    }
1246    // Final frame after victory: the desktop as proven, not mid-install.
1247    if let Some((p, s, m)) = take_screenshot(&session.mon, &screenshots_dir(&session.vm_dir)).await
1248    {
1249        eprintln!(
1250            "final frame: {} ({})",
1251            p.file_name().unwrap_or_default().to_string_lossy(),
1252            describe(s, m)
1253        );
1254    }
1255}
1256
1257/// Inputs for the install-time QEMU argv (pure constructor below): every
1258/// runtime-resolved path plus the user sizing, so tests can assert the
1259/// flags reach QEMU without spawning anything.
1260pub(crate) struct InstallQemuArgv<'a> {
1261    pub machine: &'a str,
1262    pub accel: &'a str,
1263    pub cpu: &'a str,
1264    pub memory_mb: u32,
1265    pub cpus: u32,
1266    pub display: Display,
1267    pub code_tpl: &'a Path,
1268    pub vars_fd: &'a Path,
1269    pub serial_log: &'a str,
1270    pub mon_sock: &'a str,
1271    pub qmp_sock: &'a str,
1272    pub usb_image: &'a Path,
1273    pub target: &'a str,
1274    pub arch: Architecture,
1275}
1276
1277/// `qemu-img create` args (binary excluded): carries the user disk size.
1278/// `-q` silences the `Formatting ...` line (our own banner says it).
1279pub(crate) fn qemu_img_create_args(target: &str, disk_size_gb: u32) -> Vec<String> {
1280    vec![
1281        "create".into(),
1282        "-q".into(),
1283        "-f".into(),
1284        "qcow2".into(),
1285        target.into(),
1286        format!("{disk_size_gb}G"),
1287    ]
1288}
1289
1290/// Installer QEMU argv (binary excluded): `-m`/`-smp` carry the user sizing.
1291pub(crate) fn install_qemu_argv(s: &InstallQemuArgv) -> Vec<String> {
1292    let mut argv = vec![
1293        "-M".into(),
1294        s.machine.to_string(),
1295        "-accel".into(),
1296        s.accel.to_string(),
1297        "-cpu".into(),
1298        s.cpu.to_string(),
1299        "-m".into(),
1300        s.memory_mb.to_string(),
1301        "-smp".into(),
1302        s.cpus.to_string(),
1303        "-drive".into(),
1304        format!(
1305            "if=pflash,format=raw,file={},readonly=on",
1306            s.code_tpl.display()
1307        ),
1308        "-drive".into(),
1309        format!("if=pflash,format=raw,file={}", s.vars_fd.display()),
1310        "-display".into(),
1311        s.display.to_string(),
1312        "-serial".into(),
1313        format!("file:{}", s.serial_log),
1314        "-drive".into(),
1315        format!(
1316            "file={},format=raw,if=none,id=usbstick",
1317            s.usb_image.display()
1318        ),
1319        "-netdev".into(),
1320        format!("user,id=n1,hostfwd=tcp::{}-:22", PROVEN_SSH_PORT),
1321        "-device".into(),
1322        "virtio-net-pci,netdev=n1".into(),
1323        "-monitor".into(),
1324        crate::ipc::qemu_arg(s.mon_sock),
1325        "-qmp".into(),
1326        crate::ipc::qemu_arg(s.qmp_sock),
1327    ];
1328    // xHCI first: neither q35 nor virt ships a USB bus, so usb-storage and
1329    // the ARM64 input devices below would be bus-less without it.
1330    argv.push("-device".into());
1331    argv.push("qemu-xhci,id=xhci".into());
1332    // ARM64 virt ships with NO input/display devices of its own:
1333    // USB keyboard (send-key needs it) + USB tablet (VNC
1334    // pointer needs it), and ramfb as the one framebuffer (single
1335    // console: VNC and screendump keep working after Windows takes
1336    // over, unlike virtio-gpu). x86/pc has PS/2 + VGA by default.
1337    if s.arch == Architecture::Arm64 {
1338        argv.push("-device".into());
1339        argv.push("usb-kbd".into());
1340        argv.push("-device".into());
1341        argv.push("usb-tablet".into());
1342        argv.push("-device".into());
1343        argv.push("ramfb".into());
1344    }
1345    // Removable USB media (never ide-hd). Two separate things decide
1346    // whether Setup finds its media and where it installs — they were
1347    // conflated here before, and both were verified live:
1348    //   * partition type (media.rs): WinPE letters a Microsoft Basic Data
1349    //     FAT32 volume, but mounts an ESP — or any GUID it won't letter —
1350    //     Hidden with no drive letter, so Setup never sees
1351    //     sources/install.swm and parks at "Install driver to show hardware";
1352    //   * enumeration order: USB storage lands behind the NVMe (Disk 0 =
1353    //     the target), while ide-hd came first (Disk 0 = the 10 GB media),
1354    //     and the unattend installs to Disk 0.
1355    argv.push("-device".into());
1356    argv.push("usb-storage,drive=usbstick,removable=true,bootindex=1".into());
1357    argv.push("-drive".into());
1358    argv.push(format!("file={},format=qcow2,if=none,id=tgt", s.target));
1359    argv.push("-device".into());
1360    argv.push("nvme,drive=tgt,serial=nvme1,bootindex=0".into());
1361    argv
1362}
1363
1364/// One orchestrator for all install stages: grouping the params in a
1365/// struct beats counting them in a lint attribute.
1366pub struct InstallParams {
1367    pub usb_image: Option<PathBuf>,
1368    pub win_iso: Option<PathBuf>,
1369    pub screenshots_every_secs: u64,
1370    pub classify_every_secs: Option<u64>,
1371    pub username: String,
1372    pub password: String,
1373    pub recovery: bool,
1374    pub auto_updates: bool,
1375    pub install_timeout_secs: u64,
1376    pub memory_mb: u32,
1377    pub cpus: u32,
1378    pub disk_size_gb: u32,
1379    pub display: crate::qemu::Display,
1380}
1381
1382/// Proven NVMe+USB unattended install: installer USB + NVMe target,
1383/// answer file, probe-gated SSH wait. Both platforms present the media
1384/// as removable USB storage (bootindex 1) behind xHCI and the target as
1385/// NVMe (bootindex 0): that is the topology the macOS run proved, and
1386/// Linux now shares it (its old IDE-HD branch enumerated the 10 GB media
1387/// first, as Disk 0, while the unattend installs to Disk 0).
1388///
1389/// Core only: leaves the installer QEMU running and returns it. No shell,
1390/// no Ctrl-C wait, no kill — the caller picks the tail via
1391/// `shell_then_wait` + `finish_install_capture`.
1392///
1393/// Run from the repo root (USB media must already exist).
1394async fn install_to_ready(p: InstallParams) -> Result<InstallSession> {
1395    // Sockets, serial log, SSH port and VNC settings match what `run`
1396    // boots: every endpoint is scoped to this VM dir (never /tmp —
1397    // world-writable-sticky, symlink squatting, cross-VM collisions).
1398    let (arch, _) = auto_detect_platform();
1399
1400    let vm_dir = default_vm_dir()?;
1401    let mon_sock = vm_endpoint(&vm_dir, MON_SOCK_NAME);
1402    let qmp_sock = vm_endpoint(&vm_dir, QMP_SOCK_NAME);
1403    let serial_log = vm_endpoint(&vm_dir, SERIAL_LOG_NAME);
1404    // Install into the same disk `run` boots by default, so plain `run`
1405    // starts what this installed (no --disk needed).
1406    let target = vm_dir.join(crate::paths::DISK_IMAGE);
1407    let target_s = target.to_string_lossy().into_owned();
1408    // One NVRAM file shared with `run`. The install refreshes it from the
1409    // template (a reused VARS carries stale boot entries that shadow the
1410    // installer's ISO — BlInitializeLibrary 0xc00000bb), then keeps it
1411    // across Setup's own reboots; `run` never refreshes it, so the guest's
1412    // firmware state survives its boots.
1413    let vars_fd = vm_dir.join(crate::paths::VARS_FILE);
1414    let run_log = vm_dir.join(crate::paths::INSTALL_LOG);
1415    let usb_image = p.usb_image.unwrap_or(default_media_image()?);
1416    if !usb_image.is_file() {
1417        match p.win_iso {
1418            // Chain: fetch deps + build the USB image, then install from it.
1419            // Explicit `--win-iso` only — never silent (setup downloads).
1420            #[cfg(feature = "downloader")]
1421            Some(iso) => {
1422                // The ISO is the one input `setup` cannot fetch: check it
1423                // BEFORE the downloads, so a bad path fails in milliseconds
1424                // instead of after gigabytes of tools.
1425                require_win_iso(&expand_tilde(iso.clone()))?;
1426                eprintln!(
1427                    "USB installer media missing — building it from {} (one-time; downloads tools, then builds a ~7 GB image) ...",
1428                    iso.display()
1429                );
1430                cmd_setup(None, None).await?;
1431                cmd_build_media(BuildMediaArgs {
1432                    win_iso: iso,
1433                    arch: None,
1434                    virtio_iso: None,
1435                    drivers_dir: None,
1436                    openssh_zip: None,
1437                    out: Some(usb_image.clone()),
1438                    wimlib_bin: None,
1439                    username: p.username.clone(),
1440                    password: p.password.clone(),
1441                    locale: "en-US".to_string(),
1442                    // Chain runs only when the image is absent — nothing to force.
1443                    force: false,
1444                })
1445                .await?;
1446            }
1447            #[cfg(not(feature = "downloader"))]
1448            Some(_) => anyhow::bail!("--win-iso chaining needs the downloader feature"),
1449            None => anyhow::bail!(
1450                "USB installer image {} missing — build it with `build-media --win-iso <iso>`, pass --usb-image <image>, or pass --win-iso to build it now",
1451                usb_image.display()
1452            ),
1453        }
1454    }
1455
1456    // Portable QEMU tree: the pinned release under the downloader
1457    // feature, else the pinned version dir under `./.cache/qemu-portable`.
1458    #[cfg(feature = "downloader")]
1459    let qdir = crate::qemu_portable::pinned_cached()?.root;
1460    #[cfg(not(feature = "downloader"))]
1461    let qdir = {
1462        // pins + paths (not qemu_portable): that module is downloader-gated.
1463        // The tag is the cache dir name, verbatim — no mangling.
1464        use crate::paths::{FALLBACK_QEMU_CACHE, PORTABLE_BIN_DIR, QEMU_IMG_NAME, QEMU_INNER};
1465        use crate::pins::QEMU_PORTABLE_TAG;
1466        let dir = std::env::current_dir()?
1467            .join(FALLBACK_QEMU_CACHE)
1468            .join(QEMU_PORTABLE_TAG)
1469            .join(QEMU_INNER);
1470        anyhow::ensure!(
1471            dir.join(PORTABLE_BIN_DIR).join(QEMU_IMG_NAME).is_file(),
1472            "pinned portable QEMU {QEMU_PORTABLE_TAG} not cached in {} (no downloader feature to fetch it)",
1473            dir.display()
1474        );
1475        dir
1476    };
1477    let sys_bin = qdir.join(format!("bin/{}", arch.qemu_binary()));
1478    let img_bin = qdir
1479        .join(crate::paths::PORTABLE_BIN_DIR)
1480        .join(crate::paths::QEMU_IMG_NAME);
1481    let share = qdir.join("share/qemu");
1482    let (code_names, vars_names) = arch.firmware_names();
1483    let code_tpl = code_names
1484        .iter()
1485        .map(|n| share.join(n))
1486        .find(|p| p.is_file());
1487    let vars_tpl = vars_names
1488        .iter()
1489        .map(|n| share.join(n))
1490        .find(|p| p.is_file());
1491    let (code_tpl, vars_tpl) = match (code_tpl, vars_tpl) {
1492        (Some(c), Some(v)) => (c, v),
1493        _ => anyhow::bail!("no UEFI firmware for {arch:?} in {}", share.display()),
1494    };
1495    for p in [&sys_bin, &img_bin] {
1496        if !p.exists() {
1497            anyhow::bail!("missing required file: {}", p.display());
1498        }
1499    }
1500    // CODE runs straight from the portable tree (readonly, same bytes —
1501    // no scratch copy). VARS is refreshed per install from the template:
1502    // a zeroed NVRAM file breaks OVMF initialisation (BlInitializeLibrary
1503    // 0xc00000bb) because the firmware needs the template's runtime
1504    // services data to present correct UEFI protocols to the Boot Manager.
1505    let _ = std::fs::remove_file(&vars_fd);
1506    std::fs::copy(&vars_tpl, &vars_fd).with_context(|| {
1507        format!(
1508            "copy VARS template {} -> {}",
1509            vars_tpl.display(),
1510            vars_fd.display()
1511        )
1512    })?;
1513    let _ = std::fs::remove_file(&target);
1514    // A new install voids any golden snapshot (sidecar dies with the
1515    // disk it blessed — a stale sidecar must never bless new bytes).
1516    let _ = std::fs::remove_file(golden_sidecar(&target_s));
1517    // ...and any live snapshot (its base, RAM, and VARS all predate this
1518    // disk — resuming them would boot a half-state).
1519    if let Some(parent) = std::path::Path::new(&target_s).parent() {
1520        clear_live_state(parent);
1521    }
1522    eprintln!(
1523        "installing Windows to {target_s} (new {}G disk, {} MB RAM, {} vCPUs) ...",
1524        p.disk_size_gb, p.memory_mb, p.cpus
1525    );
1526    let st = tokio::process::Command::new(&img_bin)
1527        .args(qemu_img_create_args(&target_s, p.disk_size_gb))
1528        .status()
1529        .await?;
1530    if !st.success() {
1531        anyhow::bail!("qemu-img create failed");
1532    }
1533    for s in [&mon_sock, &qmp_sock] {
1534        crate::ipc::stale_remove(s);
1535    }
1536    let out = std::fs::File::create(&run_log)?;
1537    eprintln!("QEMU output log: {}", run_log.display());
1538    // Same probe as `run`/boot argv (unattend::resolve_accel): Linux
1539    // without usable /dev/kvm (OrbStack, containers) falls back to tcg
1540    // instead of dying on `-accel kvm`. CPU follows the accel: `host`
1541    // passthrough on hardware accel, `max` under TCG (the `virt` default
1542    // is too old for Windows 11 ARM64).
1543    let (_, accel) = auto_detect_platform();
1544    let cpu = if accel == "tcg" { "max" } else { "host" };
1545    // (No extra warning here: resolve_accel already warned via tracing.)
1546    let machine = crate::qemu::machine_for(arch);
1547    let mut child = tokio::process::Command::new(&sys_bin);
1548    child.args(install_qemu_argv(&InstallQemuArgv {
1549        machine,
1550        accel,
1551        cpu,
1552        memory_mb: p.memory_mb,
1553        cpus: p.cpus,
1554        display: p.display.clone(),
1555        code_tpl: &code_tpl,
1556        vars_fd: &vars_fd,
1557        serial_log: &serial_log,
1558        mon_sock: &mon_sock,
1559        qmp_sock: &qmp_sock,
1560        usb_image: &usb_image,
1561        target: &target_s,
1562        arch,
1563    }));
1564    child
1565        .stdin(std::process::Stdio::null())
1566        .stdout(out.try_clone()?)
1567        .stderr(out)
1568        .kill_on_drop(true);
1569    // Own process group (Unix): same tty-SIGINT rationale as qemu.rs spawn —
1570    // the installer's Ctrl-C must reach only the CLI, never QEMU directly.
1571    // Windows: CREATE_NEW_PROCESS_GROUP, same rationale (see qemu.rs).
1572    #[cfg(unix)]
1573    {
1574        child.process_group(0);
1575    }
1576    #[cfg(windows)]
1577    {
1578        use std::os::windows::process::CommandExt;
1579        /// Win32 `CREATE_NEW_PROCESS_GROUP` (no winapi dep for one flag).
1580        const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;
1581        child.as_std_mut().creation_flags(CREATE_NEW_PROCESS_GROUP);
1582    }
1583    let mut child = child.spawn()?;
1584    let child_pid = child.id();
1585    eprintln!(
1586        "QEMU started (pid {child_pid:?}); waiting for the monitor (up to {}s) ...",
1587        timeouts::MONITOR_CONNECT_SECS
1588    );
1589    // Retry the REAL handshake, never a probe connect: QEMU's listen
1590    // backlog is a single slot and a probe occupies it, refusing the real
1591    // handshake with ECONNREFUSED on a live QEMU (observed). Retry while
1592    // the child lives, bail on death — never on a live child, or
1593    // kill_on_drop destroys the evidence (the old 3 s bail did exactly
1594    // that to slow hvf starters).
1595    let mon =
1596        match crate::ipc::Monitor::connect_retry(&mon_sock, timeouts::MONITOR_CONNECT_SECS, || {
1597            child.try_wait().map(|o| o.is_none()).unwrap_or(false)
1598        })
1599        .await
1600        {
1601            Ok(m) => m,
1602            Err(e) => {
1603                let status = child
1604                    .try_wait()
1605                    .map(|o| {
1606                        o.map(|s| s.to_string())
1607                            .unwrap_or_else(|| "still alive".into())
1608                    })
1609                    .unwrap_or_else(|e| format!("status unknown ({e:#})"));
1610                let _ = child.kill().await;
1611                anyhow::bail!(
1612                    "QEMU (pid {child_pid:?}, status {status}): {e:#}; check {}",
1613                    run_log.display()
1614                );
1615            }
1616        };
1617    // VNC-only step (same guard as the boot path): cocoa/gtk/sdl have
1618    // no VNC server to password-protect.
1619    if p.display.is_vnc() {
1620        mon.command(&vnc_password_command()).await?;
1621    }
1622    let mon = std::sync::Arc::new(mon);
1623    let url = vnc_url(&p.display.as_arg()).unwrap_or_else(|| p.display.as_arg());
1624    if p.display.is_vnc() {
1625        eprintln!(
1626            "Windows installer is running — watch it at {url} (VNC password: {PROVEN_VNC_PASSWORD})."
1627        );
1628    } else {
1629        eprintln!("Windows installer is running on the {url} display.");
1630    }
1631
1632    if accel == "tcg" {
1633        eprintln!(
1634            "This takes a while (much longer under TCG emulation); SSH answers when Setup finishes."
1635        );
1636    } else {
1637        eprintln!("This takes a while; SSH answers when Setup finishes.");
1638    }
1639    // Cadence policy resolves after accel detection (same `accel` the
1640    // install argv above used — post any KVM→TCG fallback): an explicit
1641    // flag wins, else TCG earns 3x spacing on classification.
1642    let profile = SamplingProfile::resolve(p.screenshots_every_secs, p.classify_every_secs, accel);
1643    let screenshots = if !profile.save_every.is_zero() || !profile.classify_every.is_zero() {
1644        let dir = screenshots_dir(&vm_dir);
1645        if !profile.save_every.is_zero() {
1646            eprintln!(
1647                "Saving an installer screenshot every {}s until then → {}",
1648                profile.save_every.as_secs(),
1649                dir.display()
1650            );
1651        }
1652        if !profile.classify_every.is_zero() {
1653            eprintln!(
1654                "Classifying the installer screen every {}s (in memory, no file)",
1655                profile.classify_every.as_secs()
1656            );
1657        }
1658        spawn_sampler(
1659            std::sync::Arc::clone(&mon),
1660            dir,
1661            vm_dir.join(crate::paths::DISK_IMAGE),
1662            profile,
1663            "installer",
1664        )
1665    } else {
1666        None
1667    };
1668    let shots_dir = screenshots_dir(&vm_dir);
1669    let scope = GuestScope {
1670        mon: std::sync::Arc::clone(&mon),
1671        shots_dir,
1672        serial_log: serial_log.clone(),
1673        vnc: p.display.is_vnc().then(|| url.clone()),
1674    };
1675    tokio::select! {
1676        r = wait_install_ready(
1677            PROVEN_SSH_PORT,
1678            // A progressing install, not a parked one: the wait's own
1679            // no-I/O watchdog (`timeouts::IDLE_BAIL_SECS`) already fails
1680            // fast on a guest that stops moving, so this only bounds how
1681            // long a *slow* host may keep applying the image (hours on a
1682            // ~1 MB/s machine).
1683            Duration::from_secs(p.install_timeout_secs),
1684            &p.username,
1685            &p.password,
1686            p.recovery,
1687            p.auto_updates,
1688            &scope,
1689        ) => {
1690            let banner = match r {
1691                Ok(b) => b,
1692                Err(e) => {
1693                    // Same evidence block as `run`'s failure arms: final
1694                    // frame + serial tail + VNC, attached to the cause
1695                    // (banner timeout, fatal signature, stall watchdog).
1696                    let report = boot_failure_report(
1697                        &scope.mon,
1698                        &scope.serial_log,
1699                        &scope.shots_dir,
1700                        &scope.vnc,
1701                    )
1702                    .await;
1703                    anyhow::bail!("{e:#}\n{report}");
1704                }
1705            };
1706            // Committed proof: one tested-isos.jsonl line from the image's
1707            // sidecar, plus a README table refresh when the markers exist.
1708            // Best-effort throughout — images built before sidecars existed
1709            // still install fine, they just leave no record. (The probe
1710            // already authenticated as `p.username`, so the CLI value is
1711            // authoritative for the ready line.)
1712            match crate::provenance::TestRecord::load_sidecar(&usb_image) {
1713                Ok(prov) => {
1714                    match crate::provenance::TestRecord::append(prov, &banner) {
1715                        Ok(_) => {
1716                            use crate::provenance::TestRecord;
1717                            let readme = PathBuf::from(README_FILE);
1718                            if readme.is_file() {
1719                                let log = PathBuf::from(TestRecord::LOG);
1720                                if let Err(e) = cmd_report(ReportArgs { log, readme: Some(readme) }) {
1721                                    eprintln!("warning: README table refresh failed: {e:#}");
1722                                }
1723                            }
1724                        }
1725                        Err(e) => eprintln!("warning: test record append failed: {e:#}"),
1726                    }
1727                }
1728                Err(e) => eprintln!("warning: no sidecar, skipping test record: {e:#}"),
1729            }
1730            eprintln!(
1731                "ready — ssh -p {} <user>@{PROVEN_SSH_HOST} (credentials not shown)",
1732                PROVEN_SSH_PORT
1733            );
1734        }
1735        _ = shutdown_signal() => {
1736            eprintln!("interrupted; stopping guest...");
1737            if let Some(h) = &screenshots {
1738                h.abort();
1739            }
1740            child.kill().await?;
1741            // Interrupt is NOT success: bail so callers (`run --win-iso`)
1742            // stop the chain instead of booting a half-installed disk.
1743            anyhow::bail!("interrupted during install; disk left half-written (rerun to start over)");
1744        }
1745    }
1746    Ok(InstallSession {
1747        child,
1748        mon,
1749        vm_dir,
1750        screenshots,
1751        img_bin,
1752    })
1753}
1754
1755/// Snapshot the running guest's disk as the new golden state (`docker
1756/// commit`): proves the shell, stops QEMU, snapshots offline, and writes
1757/// the sidecar. The guest must be up (boot it with `run` first); QEMU is
1758/// left stopped afterward, so boot again to resume the new golden.
1759/// With `live`: QMP `savevm` on the running guest instead (no shutdown —
1760/// instant-boot state, experimental; the writable pflash drive may veto
1761/// it, in which case nothing is written and the guest keeps running).
1762pub async fn cmd_snapshot(
1763    vm_dir: Option<PathBuf>,
1764    qemu_dir: Option<PathBuf>,
1765    username: String,
1766    password: String,
1767    ssh_port: u16,
1768    live: bool,
1769) -> Result<()> {
1770    let vm_dir = match vm_dir {
1771        Some(d) => d,
1772        None => default_vm_dir()?,
1773    };
1774    let disk = vm_dir
1775        .join(crate::paths::DISK_IMAGE)
1776        .to_string_lossy()
1777        .into_owned();
1778    if !std::path::Path::new(&disk).is_file() {
1779        anyhow::bail!("no disk at {disk} (install first)");
1780    }
1781    // The guest must be running: a snapshot of a stopped disk proves
1782    // nothing about the shell.
1783    if banner_once(ssh_port).await.is_none() {
1784        anyhow::bail!(
1785            "no SSH banner on {PROVEN_SSH_HOST}:{ssh_port} (boot the guest with `run` first)"
1786        );
1787    }
1788    prove_landed_shell(ssh_port, &username, &password).await?;
1789    if live {
1790        // Live path: pivot an overlay (atomic — the base freezes at this
1791        // instant, post-save writes land in the overlay), then migrate
1792        // RAM + devices to the state file (migration transfers pflash
1793        // content, so the savevm veto does not apply), then back up VARS
1794        // (raw pflash lives outside every snapshot). Guest keeps running
1795        // throughout; crash-consistent like a power cut at the pivot.
1796        let (state, vars_backup, overlay) = live_paths(&vm_dir);
1797        // Fresh pivot each save: a leftover overlay would fail the pivot
1798        // and poison the consistency story.
1799        for p in [&state, &vars_backup, &overlay] {
1800            let _ = std::fs::remove_file(p);
1801        }
1802        let qmp_sock = crate::ipc::vm_endpoint(&vm_dir, crate::ipc::QMP_SOCK_NAME);
1803        let mut qmp = crate::qmp::QmpClient::connect(&qmp_sock).await?;
1804        eprintln!("pivoting live overlay (freezing base) ...");
1805        qmp.live_overlay("tgt", &overlay.to_string_lossy())
1806            .await
1807            .map_err(|e| anyhow::anyhow!("live overlay pivot refused ({e:#}) — guest untouched"))?;
1808        eprintln!("migrating guest state to file (brief stun) ...");
1809        qmp.migrate_to_file(&state).await.map_err(|e| {
1810            anyhow::anyhow!(
1811                "live migration refused ({e:#}) — guest still running on the overlay; delete {} to unwind",
1812                overlay.display()
1813            )
1814        })?;
1815        let deadline =
1816            std::time::Instant::now() + Duration::from_secs(timeouts::MIGRATION_BUDGET_SECS);
1817        loop {
1818            let status = qmp.query_migrate_status().await?;
1819            if status == "completed" {
1820                break;
1821            }
1822            if status == "failed" || status == "cancelled" {
1823                anyhow::bail!(
1824                    "live migration {status} — guest still running on the overlay; delete {} to unwind",
1825                    overlay.display()
1826                );
1827            }
1828            if std::time::Instant::now() > deadline {
1829                anyhow::bail!(
1830                    "live migration still '{status}' after {} s — guest still running on the overlay; delete {} to unwind",
1831                    timeouts::MIGRATION_BUDGET_SECS,
1832                    overlay.display()
1833                );
1834            }
1835            tokio::time::sleep(Duration::from_secs(timeouts::MIGRATION_POLL_SECS)).await;
1836        }
1837        std::fs::copy(vm_dir.join(crate::paths::VARS_FILE), &vars_backup)?;
1838        // Post-migration liveness: a completed job can still leave the VM
1839        // paused (observed: guest "locked up" after a clean save). Verify
1840        // running, resume if paused — never hand back a frozen guest.
1841        match qmp.query_vm_status().await?.as_str() {
1842            "running" => {}
1843            stalled => {
1844                eprintln!("guest {stalled} after migration — resuming ...");
1845                qmp.resume_vm().await?;
1846            }
1847        }
1848        std::fs::write(
1849            live_sidecar(&disk),
1850            format!("{}\n", crate::provenance::now_epoch()),
1851        )?;
1852        eprintln!("live snapshot saved — `run --live` resumes it instantly; guest still running.");
1853        return Ok(());
1854    }
1855    let img_bin = match qemu_dir {
1856        Some(d) => d
1857            .join(crate::paths::PORTABLE_BIN_DIR)
1858            .join(crate::paths::QEMU_IMG_NAME),
1859        None => {
1860            #[cfg(feature = "downloader")]
1861            {
1862                let q = crate::qemu_portable::pinned_cached()?;
1863                q.root
1864                    .join(crate::paths::PORTABLE_BIN_DIR)
1865                    .join(crate::paths::QEMU_IMG_NAME)
1866            }
1867            #[cfg(not(feature = "downloader"))]
1868            {
1869                PathBuf::from(crate::paths::QEMU_IMG_NAME)
1870            }
1871        }
1872    };
1873    // Clean halt first (guest-initiated, so the bit is clean), then QMP
1874    // quit reaps a halted QEMU, then the offline snapshot. A power-cut
1875    // snapshot would bake the dirty flag into every future rewind.
1876    shutdown_guest_clean(PROVEN_SSH_HOST, ssh_port, &username, &password).await?;
1877    cmd_stop(Some(vm_dir), None).await?;
1878    snapshot_golden(&img_bin, &disk).await?;
1879    eprintln!("golden refreshed — `run` resumes this state from now on.");
1880    Ok(())
1881}
1882
1883/// Standalone `install`: full install, then supervise the VM for a human
1884/// via the shared tail (final frame + optional shell + Ctrl-C wait + kill).
1885/// `shell` only affects this tail, never the install itself.
1886pub async fn cmd_install(p: InstallParams, shell: bool) -> Result<()> {
1887    let username = p.username.clone();
1888    let password = p.password.clone();
1889    let mut session = install_to_ready(p).await?;
1890    finish_install_capture(&mut session).await;
1891    // Golden before shell/kill: prove the shell now, snapshot now. A bounce
1892    // afterward voids the sidecar (watcher below) instead of having been
1893    // predicted by a timer.
1894    prove_landed_shell(PROVEN_SSH_PORT, &username, &password).await?;
1895    let target = session.vm_dir.join(crate::paths::DISK_IMAGE);
1896    let target_s = target.to_string_lossy().into_owned();
1897    if shell {
1898        let disk = target_s.clone();
1899        tokio::select! {
1900            _ = shell_then_wait(
1901                true,
1902                PROVEN_SSH_HOST,
1903                PROVEN_SSH_PORT,
1904                &username,
1905                &password,
1906                "press Ctrl-C to shut the VM down cleanly",
1907            ) => {},
1908            // Bounce voids golden but the install stands: keep waiting for
1909            // Ctrl-C afterward instead of exiting early.
1910            _ = watch_golden_void(PROVEN_SSH_PORT, disk) => {
1911                shell_then_wait(
1912                    true,
1913                    PROVEN_SSH_HOST,
1914                    PROVEN_SSH_PORT,
1915                    &username,
1916                    &password,
1917                    "press Ctrl-C to shut the VM down cleanly",
1918                )
1919                .await?;
1920            }
1921        }
1922    } else {
1923        eprintln!("install complete (non-interactive — shutting down guest)...");
1924    }
1925    // Clean halt before the snapshot (same reason as `snapshot`): golden
1926    // must capture a clean bit. Ctrl-C still kills instantly everywhere
1927    // else — only snapshot paths pay for clean.
1928    shutdown_guest_clean(PROVEN_SSH_HOST, PROVEN_SSH_PORT, &username, &password).await?;
1929    session.child.kill().await?;
1930    snapshot_golden(&session.img_bin, &target_s).await?;
1931    Ok(())
1932}
1933
1934// ---------------------------------------------------------------------------
1935// report
1936// ---------------------------------------------------------------------------
1937
1938pub struct ReportArgs {
1939    pub log: PathBuf,
1940    /// README to splice the table into (between TESTED markers). If absent,
1941    /// the table prints to stdout for manual pasting.
1942    pub readme: Option<PathBuf>,
1943}
1944
1945/// README filename refreshed automatically by `install` (repo root,
1946/// current dir at runtime). Marker-gated: absent markers mean warn, never
1947/// blind rewrite.
1948pub const README_FILE: &str = "README.md";
1949
1950const REPORT_BEGIN: &str = "<!-- TESTED-BEGIN -->";
1951const REPORT_END: &str = "<!-- TESTED-END -->";
1952
1953fn epoch_to_date(epoch: u64) -> String {
1954    // No chrono dep: days since epoch → approximate YYYY-MM-DD via a tiny
1955    // civil-date conversion (Howard Hinnant's algorithm).
1956    let days = (epoch / 86_400) as i64;
1957    let z = days + 719_468;
1958    let era = z.div_euclid(146_097);
1959    let doe = z.rem_euclid(146_097);
1960    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
1961    let y = yoe + era * 400;
1962    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1963    let mp = (5 * doy + 2) / 153;
1964    let d = doy - (153 * mp + 2) / 5 + 1;
1965    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1966    format!("{:04}-{:02}-{:02}", if m <= 2 { y + 1 } else { y }, m, d)
1967}
1968
1969/// Release page URL for a tag in our portable repo (used to link generated
1970/// report cells to the exact artifacts consumed).
1971fn release_tag_url(tag: &str) -> String {
1972    format!(
1973        "https://github.com/{}/releases/tag/{tag}",
1974        crate::pins::RELEASE_REPO
1975    )
1976}
1977
1978/// Render `tested-isos.jsonl` as a markdown table: the human-readable face
1979/// of the machine-readable log. Short commit + `*` when the build was dirty
1980/// (hash alone doesn't reproduce it); virtio as short SHA of the consumed
1981/// ISO (name when `--drivers-dir` bypassed the ISO). Newest first: the log
1982/// is append-only, so rows are collected then reversed for display.
1983/// QEMU/wimlib/virtio cells link to their exact release pages.
1984pub fn render_report(log: &Path) -> Result<String> {
1985    let text = std::fs::read_to_string(log).with_context(|| format!("read {}", log.display()))?;
1986    let mut rows = vec![
1987        "| Date | ISO | Arch | Accel | Host | QEMU | wimlib | virtio | Commit | Result |"
1988            .to_string(),
1989        "|---|---|---|---|---|---|---|---|---|---|".to_string(),
1990    ];
1991    let mut entries = Vec::new();
1992    for (n, line) in text.lines().enumerate() {
1993        let line = line.trim();
1994        if line.is_empty() {
1995            continue;
1996        }
1997        let r: crate::provenance::TestRecord = serde_json::from_str(line)
1998            .with_context(|| format!("{} line {}", log.display(), n + 1))?;
1999        let p = &r.provenance;
2000        let commit_short = p.build_commit.chars().take(7).collect::<String>();
2001        // Clean-tree hashes exist upstream — link them. Dirty-tree hashes
2002        // (`*`) don't, so they stay plain text (a link would 404).
2003        let commit = if p.build_dirty {
2004            format!("{commit_short}*")
2005        } else {
2006            format!(
2007                "[{commit_short}]({}/commit/{})",
2008                env!("CARGO_PKG_REPOSITORY"),
2009                p.build_commit
2010            )
2011        };
2012        let virtio = match &p.deps.virtio_sha256 {
2013            Some(sha) => format!(
2014                "[{}]({})",
2015                sha.chars().take(7).collect::<String>(),
2016                release_tag_url(crate::pins::DRIVERS_RELEASE_TAG)
2017            ),
2018            None => p.deps.virtio_iso_name.clone(),
2019        };
2020        entries.push(format!(
2021            "| {} | {} | {} | {} | {} {} | [{}]({}) | [{}]({}) | {} | {} | {} |",
2022            epoch_to_date(r.tested_at_epoch),
2023            p.source_iso.file_name,
2024            p.guest.arch,
2025            p.guest.accel,
2026            p.host.os,
2027            p.host.os_version,
2028            p.deps.qemu_tag,
2029            release_tag_url(&p.deps.qemu_tag),
2030            p.deps.wimlib_tag,
2031            release_tag_url(&p.deps.wimlib_tag),
2032            virtio,
2033            commit,
2034            r.outcome,
2035        ));
2036    }
2037    entries.reverse();
2038    rows.extend(entries);
2039    Ok(rows.join("\n") + "\n")
2040}
2041
2042/// Score one PNG through the k-NN classifier ([`crate::screen_knn`]:
2043/// blurred unit-norm luminance + cosine vs the baked cluster centers).
2044/// OOD triage in one shot — no fixture dir, no snapshot, nothing
2045/// blessed. The verdict names the matched exemplar, so a miss is a
2046/// viewable cause. User-supplied path, so loading is fallible
2047/// (`try_load_rgb_8bit`) — bad input exits nonzero via `anyhow`, never a
2048/// panic out of the fixture loader.
2049pub fn cmd_classify(png: &std::path::Path) -> Result<()> {
2050    use crate::screen_knn::{KNN_TOP_K, KNN_UNCERTAIN_GAP, KnnIndex, bundled_index};
2051    let path = png
2052        .to_str()
2053        .with_context(|| format!("non-UTF8 image path: {}", png.display()))?;
2054    let (rgb, w, h) = crate::screen_knn::try_load_rgb_8bit(path)
2055        .map_err(|e| anyhow::anyhow!("load {path}: {e}"))?;
2056    if rgb.is_empty() || w == 0 {
2057        println!("top-1: Dark gap 1.000 (empty input — nothing captured)");
2058        println!("verdict: COMMITTED (margin holds — narration states the label)");
2059        return Ok(());
2060    }
2061    let index = bundled_index();
2062    let q = KnnIndex::embed_frame(&rgb, w, h);
2063    let (top, gap, matched) = index
2064        .predict(&q, None)
2065        .with_context(|| "empty bundled k-NN index — rebuild artifacts/knn_index.bin")?;
2066    println!("top-1: {top:?} gap {gap:.4} via {matched}");
2067    for (label, cos, name) in index.query(&q, None, KNN_TOP_K) {
2068        let class = crate::screen_knn::BY_INDEX
2069            .iter()
2070            .find(|c| **c as usize == label)
2071            .copied()
2072            .unwrap_or(crate::screen_knn::ScreenClass::Dark);
2073        println!("  {class:?}: {cos:.4} {name}");
2074    }
2075    if gap < KNN_UNCERTAIN_GAP {
2076        println!(
2077            "verdict: UNCERTAIN (gap below {KNN_UNCERTAIN_GAP:.2} — narration hedges, nothing gates)"
2078        );
2079    } else {
2080        println!("verdict: COMMITTED (margin holds — narration states the label)");
2081    }
2082    Ok(())
2083}
2084
2085pub fn cmd_report(a: ReportArgs) -> Result<()> {
2086    let table = render_report(&a.log)?;
2087    match a.readme {
2088        None => print!("{table}"),
2089        Some(readme) => {
2090            let text = std::fs::read_to_string(&readme)?;
2091            let (head, rest) = text
2092                .split_once(REPORT_BEGIN)
2093                .with_context(|| format!("{} has no {REPORT_BEGIN} marker", readme.display()))?;
2094            let (_, tail) = rest
2095                .split_once(REPORT_END)
2096                .with_context(|| format!("{} has no {REPORT_END} marker", readme.display()))?;
2097            let updated = format!("{head}{REPORT_BEGIN}\n{table}{REPORT_END}{tail}");
2098            std::fs::write(&readme, updated)?;
2099            eprintln!("updated {}", readme.display());
2100        }
2101    }
2102    Ok(())
2103}
2104
2105// ---------------------------------------------------------------------------
2106// guest
2107// ---------------------------------------------------------------------------
2108
2109/// Guest verbs (work on any booted machine via SSH). Same verbs the
2110/// install flow uses internally — exposed here for live machines.
2111#[derive(clap::Subcommand)]
2112pub enum GuestOp {
2113    /// Execute one command, print stdout.
2114    Exec {
2115        /// Command line (joined with spaces).
2116        #[arg(last = true)]
2117        cmd: Vec<String>,
2118    },
2119    /// Rotate the guest password (verified by fresh login).
2120    SetPassword {
2121        /// New password (never logged).
2122        new_password: String,
2123    },
2124    /// Set Automatic Repair on/off.
2125    SetRecovery {
2126        /// `true` keeps it, `false` disables it.
2127        #[arg(action = clap::ArgAction::Set, value_parser = clap::value_parser!(bool))]
2128        enabled: bool,
2129    },
2130    /// Set automatic Windows updates on/off.
2131    SetUpdates {
2132        /// `true` enables wuauserv, `false` disables it.
2133        #[arg(action = clap::ArgAction::Set, value_parser = clap::value_parser!(bool))]
2134        enabled: bool,
2135    },
2136    /// Ask the guest whether Setup is finished (READY/BUSY verdict).
2137    Probe,
2138}
2139
2140pub struct GuestArgs {
2141    pub op: GuestOp,
2142    pub ssh_port: u16,
2143    pub username: String,
2144    pub password: String,
2145}
2146
2147pub async fn cmd_guest(a: GuestArgs) -> Result<()> {
2148    use crate::qemu::PROVEN_SSH_HOST;
2149    let host = PROVEN_SSH_HOST;
2150    match a.op {
2151        GuestOp::Exec { cmd } => {
2152            let out =
2153                crate::ssh::ssh_exec(host, a.ssh_port, &a.username, &a.password, &cmd.join(" "))
2154                    .await?;
2155            print!("{out}");
2156        }
2157        GuestOp::SetPassword { new_password } => {
2158            crate::ssh::change_guest_password(
2159                host,
2160                a.ssh_port,
2161                &a.username,
2162                &a.password,
2163                &new_password,
2164            )
2165            .await?;
2166            eprintln!("password rotated (verified by fresh login)");
2167        }
2168        GuestOp::SetRecovery { enabled } => {
2169            crate::ssh::set_recovery_enabled(host, a.ssh_port, &a.username, &a.password, enabled)
2170                .await?;
2171        }
2172        GuestOp::SetUpdates { enabled } => {
2173            crate::ssh::set_auto_updates(host, a.ssh_port, &a.username, &a.password, enabled)
2174                .await?;
2175        }
2176        GuestOp::Probe => {
2177            let progress =
2178                crate::ssh::probe_setup_done(host, a.ssh_port, &a.username, &a.password).await?;
2179            eprintln!("{}", if progress.is_ready() { "READY" } else { "BUSY" });
2180        }
2181    }
2182    Ok(())
2183}
2184
2185// ---------------------------------------------------------------------------
2186// overlay / stop
2187// ---------------------------------------------------------------------------
2188
2189pub async fn cmd_overlay(
2190    base: Option<PathBuf>,
2191    overlay: PathBuf,
2192    qemu_dir: Option<PathBuf>,
2193) -> Result<()> {
2194    // Base defaults to the disk `run` boots — overlays are deltas over it.
2195    let base = match base {
2196        Some(b) => b,
2197        None => default_vm_dir()?.join(crate::paths::DISK_IMAGE),
2198    };
2199    if !base.is_file() {
2200        anyhow::bail!("base {} missing (run `install` first)", base.display());
2201    }
2202    let img = qemu_dir
2203        .map(|d| {
2204            d.join(crate::paths::PORTABLE_BIN_DIR)
2205                .join(crate::paths::QEMU_IMG_NAME)
2206        })
2207        .unwrap_or_else(|| PathBuf::from(crate::paths::QEMU_IMG_NAME));
2208    DiskManager::create_overlay(&img, &base, &overlay).await?;
2209    eprintln!("overlay {} over {}", overlay.display(), base.display());
2210    Ok(())
2211}
2212
2213pub async fn cmd_stop(vm_dir: Option<PathBuf>, qmp_sock: Option<String>) -> Result<()> {
2214    use crate::qmp::QmpClient;
2215    let vm_dir = match vm_dir {
2216        Some(d) => d,
2217        None => default_vm_dir()?,
2218    };
2219    // Default QMP endpoint lives next to the disk (never /tmp); explicit
2220    // --qmp-sock overrides (URLs/paths as given).
2221    let qmp_sock = qmp_sock.unwrap_or_else(|| vm_endpoint(&vm_dir, QMP_SOCK_NAME));
2222    // Best-effort pid lookup for messaging (kill fallback below).
2223    let pid = std::fs::read_to_string(vm_dir.join(crate::paths::QEMU_PIDFILE))
2224        .ok()
2225        .map(|s| s.trim().to_string())
2226        .filter(|s| !s.is_empty());
2227    if !qmp_alive(&qmp_sock).await {
2228        // Not reachable: drop a stale pidfile if present, then report.
2229        let pidfile = vm_dir.join(crate::paths::QEMU_PIDFILE);
2230        if pidfile.exists() {
2231            let _ = std::fs::remove_file(&pidfile);
2232        }
2233        match pid {
2234            Some(p) => println!(
2235                "no QMP on {qmp_sock}: VM is unreachable (wedged or already gone). If `ps -p {p}` is alive, `kill {p}` to clean up."
2236            ),
2237            None => println!("no running VM on {qmp_sock}"),
2238        }
2239        return Ok(());
2240    }
2241    let mut qmp = QmpClient::connect(&qmp_sock).await?;
2242    qmp.quit().await?;
2243    // Drop the session before probing: single-client transports refuse a
2244    // probe while our own session is open (false "dead").
2245    drop(qmp);
2246    for _ in 0..timeouts::QMP_QUIT_POLL_COUNT {
2247        if !qmp_alive(&qmp_sock).await {
2248            break;
2249        }
2250        tokio::time::sleep(timeouts::QMP_QUIT_POLL_INTERVAL).await;
2251    }
2252    let pidfile = vm_dir.join(crate::paths::QEMU_PIDFILE);
2253    let _ = std::fs::remove_file(&pidfile);
2254    if qmp_alive(&qmp_sock).await {
2255        anyhow::bail!(
2256            "VM ignored QMP quit; kill it manually (see {} before cleanup)",
2257            crate::paths::QEMU_PIDFILE
2258        );
2259    }
2260    eprintln!("stopped");
2261    Ok(())
2262}
2263
2264// ---------------------------------------------------------------------------
2265// downloader-backed commands
2266// ---------------------------------------------------------------------------
2267
2268/// Download one file into place (skip when cached and valid). Shared by
2269/// `fetch` and `setup` so both print the same `cached|downloaded` lines.
2270/// `force` re-downloads even a valid cache entry (for URL-rotated
2271/// artifacts like the Windows ISO); `setup` always passes false.
2272#[cfg(feature = "downloader")]
2273pub async fn fetch_one(
2274    url: &str,
2275    dest: &std::path::Path,
2276    hash: Option<&str>,
2277    force: bool,
2278) -> Result<()> {
2279    use crate::downloader;
2280    let name = dest
2281        .file_name()
2282        .map(|n| n.to_string_lossy().into_owned())
2283        .unwrap_or_else(|| dest.display().to_string());
2284    let is_iso = name.ends_with(".iso");
2285    // A previously cached file may be a bot-check HTML stub
2286    // (HTTP 200 with no ISO magic) — drop it so it re-downloads
2287    // instead of poisoning this run and hanging EDK2 at boot.
2288    if is_iso && dest.exists() && downloader::validate_iso_image(dest).is_err() {
2289        eprintln!(
2290            "cached {} is not an ISO image; re-downloading",
2291            dest.display()
2292        );
2293        std::fs::remove_file(dest)?;
2294    }
2295    match downloader::download_if_missing(url, dest, hash, force).await? {
2296        downloader::DownloadStatus::Cached { path } => {
2297            if is_iso {
2298                downloader::validate_iso_image(&path)?;
2299            }
2300            eprintln!("cached {}", path.display())
2301        }
2302        downloader::DownloadStatus::Downloaded { path, sha256 } => {
2303            if is_iso && let Err(e) = downloader::validate_iso_image(&path) {
2304                let _ = std::fs::remove_file(&path);
2305                return Err(e)
2306                    .with_context(|| format!("downloaded {} failed validation", path.display()));
2307            }
2308            eprintln!("downloaded {} (sha256 {sha256})", path.display())
2309        }
2310    }
2311    Ok(())
2312}
2313
2314#[cfg(feature = "downloader")]
2315pub async fn cmd_fetch_qemu(
2316    qemu_tag: Option<String>,
2317    dir: Option<PathBuf>,
2318    allow_unverified: bool,
2319) -> Result<()> {
2320    let q = crate::qemu_portable::ensure(dir, qemu_tag, allow_unverified).await?;
2321    eprintln!("portable QEMU {} at {}", q.version, q.root.display());
2322    for bin in q.system_binaries() {
2323        eprintln!("  system: {}", bin.display());
2324    }
2325    eprintln!("  img:    {}", q.qemu_img().display());
2326    Ok(())
2327}
2328
2329#[cfg(feature = "downloader")]
2330pub struct FetchArgs {
2331    pub win_iso_url: Option<String>,
2332    pub win_iso_sha256: Option<String>,
2333    pub virtio_iso_url: Option<String>,
2334    pub dir: Option<PathBuf>,
2335    pub virtio_sha256: Option<String>,
2336    pub openssh: bool,
2337    pub arch: Option<Architecture>,
2338    /// Re-download even valid cache entries (for URL-rotated artifacts
2339    /// like the Windows ISO, whose slot name can't see upstream changes).
2340    pub force: bool,
2341}
2342
2343#[cfg(feature = "downloader")]
2344pub async fn cmd_fetch(a: FetchArgs) -> Result<()> {
2345    use crate::downloader;
2346    let dir = match a.dir {
2347        Some(d) => d,
2348        None => downloader::iso_cache_dir()?,
2349    };
2350    // Explicit flag wins; else a pre-fetched time-limited link via env.
2351    // No page scraper: Microsoft links require the interactive form.
2352    // Absent entirely: skip the Windows ISO (e.g. you already have one
2353    // on disk and only need virtio-win.iso).
2354    let mut items: Vec<(String, &str, Option<String>)> = Vec::new();
2355    match downloader::resolve_win_iso_url(a.win_iso_url) {
2356        Ok(u) => {
2357            // Explicit flag wins, else $WIN11_ISO_SHA256; absent = TLS only.
2358            let win_hash = a
2359                .win_iso_sha256
2360                .or_else(|| std::env::var("WIN11_ISO_SHA256").ok());
2361            items.push((u, crate::paths::WIN11_ISO_NAME, win_hash))
2362        }
2363        Err(e) => eprintln!("skipping Windows ISO: {e:#}"),
2364    }
2365    // virtio-win.iso: explicit URL wins, else our vendored release
2366    // asset (hash from the release sidecar). No fallback: a failed
2367    // lookup means the pin is wrong or GitHub is unreachable, and
2368    // silently substituting unpinned upstream bytes would hide either.
2369    let (virtio_url, virtio_hash) = match a.virtio_iso_url {
2370        Some(u) => {
2371            if a.virtio_sha256.is_none() {
2372                tracing::warn!(
2373                    "custom --virtio-iso-url without --virtio-sha256: virtio-win.iso will be TLS-only (no hash verification)"
2374                );
2375            }
2376            (u, a.virtio_sha256)
2377        }
2378        None => {
2379            let (u, h) = downloader::virtio_release_info().await.with_context(|| {
2380                format!(
2381                    "virtio release lookup failed for {} (check the pin and GitHub API rate limits)",
2382                    downloader::VIRTIO_RELEASE_TAG
2383                )
2384            })?;
2385            (u, a.virtio_sha256.or(Some(h)))
2386        }
2387    };
2388    items.push((virtio_url, crate::paths::VIRTIO_ISO, virtio_hash));
2389    if a.openssh {
2390        let arch = resolve_arch(a.arch);
2391        items.push((
2392            downloader::openssh_zip_url(arch),
2393            arch.openssh_zip_name(),
2394            Some(arch.openssh_sha256().to_string()),
2395        ));
2396    }
2397    for (url, name, hash) in items {
2398        fetch_one(&url, &dir.join(name), hash.as_deref(), a.force).await?;
2399    }
2400    Ok(())
2401}
2402
2403#[cfg(feature = "downloader")]
2404pub async fn cmd_setup(virtio_iso_url: Option<String>, arch: Option<Architecture>) -> Result<()> {
2405    use crate::downloader;
2406    let arch = resolve_arch(arch);
2407    let q = crate::qemu_portable::ensure(None, None, false).await?;
2408    eprintln!("portable QEMU {} at {}", q.version, q.root.display());
2409    let w = crate::qemu_portable::ensure_wimlib(None, None, false).await?;
2410    eprintln!("portable wimlib {} at {}", w.version, w.root.display());
2411    let dir = downloader::iso_cache_dir()?;
2412    let (virtio_url, virtio_hash) = match virtio_iso_url {
2413        Some(u) => {
2414            tracing::warn!(
2415                "custom virtio ISO URL without --virtio-sha256: virtio-win.iso will be TLS-only (no hash verification)"
2416            );
2417            (u, None)
2418        }
2419        None => {
2420            let (u, h) = downloader::virtio_release_info().await?;
2421            (u, Some(h))
2422        }
2423    };
2424    fetch_one(
2425        &virtio_url,
2426        &dir.join(crate::paths::VIRTIO_ISO),
2427        virtio_hash.as_deref(),
2428        false,
2429    )
2430    .await?;
2431    fetch_one(
2432        &downloader::openssh_zip_url(arch),
2433        &dir.join(arch.openssh_zip_name()),
2434        Some(arch.openssh_sha256()),
2435        false,
2436    )
2437    .await?;
2438    eprintln!("setup complete (Windows ISO still yours: pass --win-iso to build-media)");
2439    Ok(())
2440}
2441
2442#[cfg(feature = "downloader")]
2443pub async fn cmd_fetch_wimlib(
2444    wimlib_tag: Option<String>,
2445    dir: Option<PathBuf>,
2446    allow_unverified: bool,
2447) -> Result<()> {
2448    let w = crate::qemu_portable::ensure_wimlib(dir, wimlib_tag, allow_unverified).await?;
2449    eprintln!("portable wimlib {} at {}", w.version, w.root.display());
2450    eprintln!("  bin: {}", w.wimlib_bin().display());
2451    Ok(())
2452}
2453
2454/// Verify every pinned external artifact WITHOUT downloading archives or
2455/// installing anything (CI-friendly: KBs of metadata, plus two ~5 MB OpenSSH
2456/// zips). Checks, per artifact:
2457/// 1. the release asset exists (availability for that environment), and
2458/// 2. its hash matches the code-pinned expectation.
2459///
2460/// Hash-only sources are preferred wherever they exist (`SHA256SUMS.txt`,
2461/// virtio `.sha256` sidecar); only OpenSSH (no upstream sums) downloads the
2462/// payload itself. Prints one line per check; returns an error summarizing
2463/// all failures so a single CI run reports everything at once.
2464#[cfg(feature = "downloader")]
2465pub async fn cmd_verify_pins() -> Result<()> {
2466    use crate::downloader;
2467    use crate::qemu_portable::{parse_sums, release_by_tag};
2468    let mut failures: Vec<String> = Vec::new();
2469    let ok = |label: &str| eprintln!("pin ok: {label}");
2470
2471    // Portable QEMU + wimlib: all three platform markers, sums hash vs pin.
2472    for (product, tag, prefix, is_wimlib) in [
2473        (
2474            "qemu",
2475            crate::pins::QEMU_PORTABLE_TAG,
2476            crate::paths::QEMU_ASSET_PREFIX,
2477            false,
2478        ),
2479        (
2480            "wimlib",
2481            crate::pins::WIMLIB_PORTABLE_TAG,
2482            crate::paths::WIMLIB_ASSET_PREFIX,
2483            true,
2484        ),
2485    ] {
2486        let assets = match release_by_tag(tag).await {
2487            Ok(a) => a,
2488            Err(e) => {
2489                failures.push(format!("{product} {tag}: release lookup failed: {e:#}"));
2490                continue;
2491            }
2492        };
2493        let sums_url = match assets
2494            .iter()
2495            .find(|(n, _)| n == crate::paths::SHA256SUMS_FILE)
2496            .map(|(_, u)| u.clone())
2497        {
2498            Some(u) => u,
2499            None => {
2500                failures.push(format!(
2501                    "{product} {tag}: no {}",
2502                    crate::paths::SHA256SUMS_FILE
2503                ));
2504                continue;
2505            }
2506        };
2507        let sums_body = match downloader::fetch_text(&sums_url).await {
2508            Ok(b) => b,
2509            Err(e) => {
2510                failures.push(format!("{product} {tag}: sums fetch failed: {e:#}"));
2511                continue;
2512            }
2513        };
2514        for marker in [
2515            crate::paths::MARKER_MACOS_ARM64,
2516            crate::paths::MARKER_LINUX_X86_64,
2517            crate::paths::MARKER_LINUX_AARCH64,
2518        ] {
2519            let label = format!("{product} {tag} [{marker}]");
2520            let Some(asset) = assets
2521                .iter()
2522                .find(|(n, _)| n.contains(marker) && n.starts_with(prefix))
2523                .map(|(n, _)| n.clone())
2524            else {
2525                failures.push(format!("{label}: no release asset"));
2526                continue;
2527            };
2528            let Some(expected) = (if is_wimlib {
2529                crate::qemu_portable::pinned_wimlib_sha256(marker)
2530            } else {
2531                crate::qemu_portable::pinned_qemu_sha256(marker)
2532            }) else {
2533                failures.push(format!("{label}: no pinned hash for marker"));
2534                continue;
2535            };
2536            match parse_sums(&sums_body, &asset) {
2537                Some(h) if h.eq_ignore_ascii_case(expected) => ok(&label),
2538                Some(h) => failures.push(format!(
2539                    "{label}: sums hash {h} != pinned {expected} (stale pin? asset rotated?)"
2540                )),
2541                None => failures.push(format!(
2542                    "{label}: {asset} missing from {}",
2543                    crate::paths::SHA256SUMS_FILE
2544                )),
2545            }
2546        }
2547    }
2548
2549    // virtio-win.iso: sidecar must be a valid 64-hex digest AND match the
2550    // code pin (closes the TOFU gap: a forged sidecar+ISO pair fails here).
2551    match downloader::virtio_release_info().await {
2552        Ok((url, sha)) => {
2553            ok(&format!("virtio-win.iso [{sha}] ({url})"));
2554        }
2555        Err(e) => failures.push(format!("virtio-win.iso: release lookup failed: {e:#}")),
2556    }
2557    // OpenSSH: no upstream sums — download both zips (~5 MB) to a tempdir
2558    // and hash against the arch-strict pins.
2559    let tmp = tempfile::tempdir().context("verify-pins tempdir")?;
2560    for arch in [crate::Architecture::Amd64, crate::Architecture::Arm64] {
2561        let label = format!("{} ({})", arch.openssh_zip_name(), arch.as_xml_str());
2562        let dest = tmp.path().join(arch.openssh_zip_name());
2563        match downloader::download(&downloader::openssh_zip_url(arch), &dest).await {
2564            Ok(actual) => {
2565                let _ = std::fs::remove_file(&dest);
2566                if actual.eq_ignore_ascii_case(arch.openssh_sha256()) {
2567                    ok(&label);
2568                } else {
2569                    failures.push(format!(
2570                        "{label}: downloaded hash {actual} != pinned {}",
2571                        arch.openssh_sha256()
2572                    ));
2573                }
2574            }
2575            Err(e) => failures.push(format!("{label}: download failed: {e:#}")),
2576        }
2577    }
2578
2579    if failures.is_empty() {
2580        eprintln!("verify-pins: all pinned artifacts available and hash-matched");
2581        Ok(())
2582    } else {
2583        for f in &failures {
2584            eprintln!("pin FAIL: {f}");
2585        }
2586        anyhow::bail!("verify-pins: {} check(s) failed", failures.len())
2587    }
2588}
2589
2590// ---------------------------------------------------------------------------
2591// VM helpers (shared by run / install)
2592// ---------------------------------------------------------------------------
2593
2594/// Last meaningful line of the guest serial log (EDK2/Windows boot chatter).
2595/// Shown in the boot-wait ticker so a slow boot narrates itself instead of
2596/// printing bare elapsed seconds (observed live: 450 s of silence during a
2597/// recovery boot). Empty when the log has nothing yet.
2598///
2599/// Filters EDK2 memory-map/TPM noise (`ConvertPages`, `Tcg2`) that repeats
2600/// for minutes and says nothing — without this the ticker quotes firmware
2601/// trivia as status (observed live).
2602fn last_serial_line(serial_log: &str) -> String {
2603    /// Substrings marking firmware noise, never boot progress.
2604    const NOISE: &[&str] = &[
2605        "ConvertPages: failed to find range",
2606        "Tpm2SubmitCommand",
2607        "Tcg2",
2608        "Tpm2GetCapability",
2609    ];
2610    let text = std::fs::read_to_string(serial_log).unwrap_or_default();
2611    // Serial carries ANSI escapes and \r; take the last line with text
2612    // (reverse scan stops at the first hit instead of walking the log).
2613    fn stripped(line: &str, noise: &[&str]) -> Option<String> {
2614        // Strip common ANSI CSI sequences (best-effort, no regex dep).
2615        let mut s = String::with_capacity(line.len());
2616        let mut chars = line.chars().peekable();
2617        while let Some(c) = chars.next() {
2618            if c == '\x1b' && chars.peek() == Some(&'[') {
2619                for c2 in chars.by_ref() {
2620                    if c2.is_ascii_alphabetic() {
2621                        break;
2622                    }
2623                }
2624            } else {
2625                s.push(c);
2626            }
2627        }
2628        let s = s.trim().to_string();
2629        (!s.is_empty() && !noise.iter().any(|n| s.contains(n))).then_some(s)
2630    }
2631    let line = text
2632        .replace('\r', "\n")
2633        .lines()
2634        .rev()
2635        .filter_map(|l| stripped(l, NOISE))
2636        .next()
2637        .unwrap_or_default();
2638    // Cap length: some lines are progress bars several KB wide.
2639    if line.len() > 100 {
2640        format!("{}...", &line[..100])
2641    } else {
2642        line
2643    }
2644}
2645/// Fatal boot-failure patterns in the guest serial log (EDK2/Windows).
2646/// Patterns live in `templates/boot-fatal-patterns.txt` (one substring per
2647/// line), not in code — new dead screens are learned by editing a text
2648/// file, not shipping a release. Conservative by design: only signatures
2649/// that never appear in a healthy boot. A hit means VNC would show a dead
2650/// screen — fail fast with the evidence instead of polling SSH.
2651fn fatal_boot_patterns() -> Vec<String> {
2652    const TPL: &str = include_str!("../templates/boot-fatal-patterns.txt");
2653    TPL.lines()
2654        .map(str::trim)
2655        .filter(|l| !l.is_empty() && !l.starts_with('#'))
2656        .map(str::to_string)
2657        .collect()
2658}
2659
2660/// Firmware boot handoffs in the serial log: OVMF prints one
2661/// `BdsDxe: starting <entry>` line per boot attempt it launches (failed
2662/// candidates log `failed to load` instead), so the count rises on every
2663/// guest reboot — the below-screenshot "did it bounce?" signal. QEMU's
2664/// file chardev truncates at VM start, so it counts this session only.
2665/// Caveat: a boot entry whose `Start()` returns without loading can add a
2666/// line without a full reboot — the trend (flat vs rising) is the signal.
2667fn boot_count(serial_log: &str) -> u64 {
2668    std::fs::read_to_string(serial_log)
2669        .unwrap_or_default()
2670        .matches("BdsDxe: starting")
2671        .count() as u64
2672}
2673
2674/// One-shot narration for a rising [`boot_count`]: `None` while flat, a
2675/// line for the first boot, a reboot line after it. Count regressions
2676/// (a truncated log) stay silent — never claim a reboot that didn't show.
2677fn boot_note(old: u64, new: u64) -> Option<String> {
2678    (new > old).then(|| {
2679        if new == 1 {
2680            "guest booted (first firmware boot)".to_string()
2681        } else {
2682            format!("guest rebooted (firmware boot #{new} seen on serial)")
2683        }
2684    })
2685}
2686
2687/// Fatal serial signature check (see [`fatal_boot_patterns`]): returns the
2688/// cause only — `cmd_run`'s failure arms append the evidence block (frame
2689/// path + serial tail + VNC) via [`boot_failure_report`].
2690fn check_boot_failure(serial_log: &str) -> Result<()> {
2691    let fatal = fatal_boot_patterns();
2692    let text = std::fs::read_to_string(serial_log).unwrap_or_default();
2693    // Only the tail matters (log persists across runs); keep the last 8 KB.
2694    let tail = if text.len() > 8192 {
2695        &text[text.len() - 8192..]
2696    } else {
2697        &text
2698    };
2699    for pat in &fatal {
2700        if tail.contains(pat) {
2701            anyhow::bail!("guest failed to boot (serial shows {pat:?})");
2702        }
2703    }
2704    Ok(())
2705}
2706
2707/// Guest-activity ledger: the sole consumer of `info blockstats` plus
2708/// host-side disk-size samples. Answers "is the guest doing anything" so
2709/// the warning policy can tell a slow install (moving) from a parked one
2710/// (flat). Sample on every tick; judge on horizons — qcow2 grows stepwise,
2711/// so per-second diffs false-report static.
2712struct ActivityMonitor {
2713    last_total: u64,
2714    last_change: std::time::Instant,
2715    warned: bool,
2716    disk_start: Option<u64>,
2717    disk_last: u64,
2718    disk_last_change: std::time::Instant,
2719    last_sample: Option<std::time::Instant>,
2720    /// I/O bytes/s, exponential average over [`Self::EMA_WINDOW_SECS`].
2721    pub(crate) io_ema_bps: f64,
2722    /// Disk-growth bytes/s, same window.
2723    pub(crate) growth_ema_bps: f64,
2724}
2725
2726impl ActivityMonitor {
2727    /// EMA window in seconds: bursts read as rates, not spikes.
2728    const EMA_WINDOW_SECS: f64 = 300.0;
2729
2730    fn new() -> Self {
2731        let now = std::time::Instant::now();
2732        Self {
2733            last_total: 0,
2734            last_change: now,
2735            warned: false,
2736            disk_start: None,
2737            disk_last: 0,
2738            disk_last_change: now,
2739            last_sample: None,
2740            io_ema_bps: 0.0,
2741            growth_ema_bps: 0.0,
2742        }
2743    }
2744
2745    /// Sum all `rd_bytes`/`wr_bytes` in HMP `info blockstats` output.
2746    /// Best-effort parse (unparseable → None, never fail the wait on it).
2747    fn parse_total(text: &str) -> Option<u64> {
2748        let mut total = 0u64;
2749        let mut found = false;
2750        for key in ["rd_bytes=", "wr_bytes="] {
2751            for part in text.split(key).skip(1) {
2752                let digits: String = part.chars().take_while(|c| c.is_ascii_digit()).collect();
2753                if let Ok(n) = digits.parse::<u64>() {
2754                    total = total.saturating_add(n);
2755                    found = true;
2756                }
2757            }
2758        }
2759        found.then_some(total)
2760    }
2761
2762    /// One EMA step, pure: `prev` toward `inst` over `dt_secs` in a
2763    /// `window_secs` horizon. Unit-testable without clocks.
2764    fn ema_step(prev: f64, inst: f64, dt_secs: f64, window_secs: f64) -> f64 {
2765        if dt_secs <= 0.0 {
2766            return prev;
2767        }
2768        let alpha = (dt_secs / window_secs).min(1.0);
2769        prev + alpha * (inst - prev)
2770    }
2771
2772    /// Feed one tick: monitor counters plus host-side disk size. Every
2773    /// part best-effort — an unreachable monitor or stat failure skips
2774    /// that signal, never the wait. `None` disk skips growth tracking
2775    /// (blockstats still feed the stall watchdog).
2776    async fn sample(&mut self, mon: &crate::ipc::Monitor, disk: Option<&Path>) {
2777        let now = std::time::Instant::now();
2778        let dt = self
2779            .last_sample
2780            .map(|t| now.duration_since(t).as_secs_f64())
2781            .unwrap_or(0.0);
2782        self.last_sample = Some(now);
2783        let text = mon.command("info blockstats").await.unwrap_or_default();
2784        if let Some(total) = Self::parse_total(&text) {
2785            // Unconditional on movement: a flat interval feeds inst 0.0 so
2786            // the average decays toward zero instead of freezing at its
2787            // last active rate for hours on an idle guest.
2788            if dt > 0.0 {
2789                let inst = total.saturating_sub(self.last_total) as f64 / dt;
2790                self.io_ema_bps = Self::ema_step(self.io_ema_bps, inst, dt, Self::EMA_WINDOW_SECS);
2791            }
2792            if total != self.last_total {
2793                self.last_total = total;
2794                self.last_change = now;
2795                self.warned = false;
2796            }
2797        }
2798        if let Some(disk) = disk
2799            && let Ok(size) = std::fs::metadata(disk).map(|m| m.len())
2800        {
2801            if self.disk_start.is_none() {
2802                // First sample arms the baseline without tripping motion:
2803                // a pre-existing disk is not growth.
2804                self.disk_start = Some(size);
2805                self.disk_last = size;
2806                self.disk_last_change = now;
2807            } else if dt > 0.0 {
2808                let inst = size.saturating_sub(self.disk_last) as f64 / dt;
2809                self.growth_ema_bps =
2810                    Self::ema_step(self.growth_ema_bps, inst, dt, Self::EMA_WINDOW_SECS);
2811                // Growth timer advances only on real growth; the average
2812                // still decays through the zero inst above.
2813                if size != self.disk_last {
2814                    self.disk_last_change = now;
2815                }
2816                self.disk_last = size;
2817            }
2818        }
2819    }
2820
2821    /// Seconds since block I/O last moved.
2822    fn idle_secs(&self) -> u64 {
2823        self.last_change.elapsed().as_secs()
2824    }
2825
2826    /// Seconds since the disk image last grew.
2827    fn disk_idle_secs(&self) -> u64 {
2828        self.disk_last_change.elapsed().as_secs()
2829    }
2830
2831    /// Bytes the disk image grew since the first sample (saturating).
2832    fn growth_since_start(&self) -> u64 {
2833        self.disk_start
2834            .map(|s| self.disk_last.saturating_sub(s))
2835            .unwrap_or(0)
2836    }
2837
2838    /// Moving right now: any I/O inside the warn horizon.
2839    fn is_moving(&self) -> bool {
2840        self.idle_secs() < timeouts::IDLE_WARN_SECS
2841    }
2842
2843    /// Stall watchdog, conditioned on screen state: frozen disk I/O during
2844    /// valid progress (Setup applying, OOBE, boot art, idle desktop) is a
2845    /// slow host, never a stuck guest — progress answers only to the
2846    /// operator. The bail fires solely on the conjunction: a non-progress
2847    /// screen (error states, Dark, FlatField) AND ceased block I/O AND a
2848    /// disk that stopped growing. `None` state (no frame yet) takes the
2849    /// strict path: nothing rendered is itself evidence of stuck.
2850    /// `fatal` decides the teeth: the run boot wait bails (a dead boot
2851    /// has its own SSH deadline anyway), the install path only ever warns
2852    /// — nothing but the operator halts an install. `Err` on bail so
2853    /// fatal callers `?` straight out.
2854    fn check_stall(&mut self, state: Option<ScreenState>, fatal: bool) -> Result<()> {
2855        let progress = matches!(
2856            state,
2857            Some(
2858                ScreenState::InstallerStep
2859                    | ScreenState::OobeStep
2860                    | ScreenState::FirmwareBoot
2861                    | ScreenState::Lockscreen
2862            )
2863        );
2864        if progress {
2865            // Slow host, not stuck guest: reset the warn latch so a later
2866            // genuine stall still warns, and return without judging.
2867            self.warned = false;
2868            return Ok(());
2869        }
2870        let idle = self.idle_secs();
2871        let disk_idle = self.disk_idle_secs();
2872        if idle >= timeouts::IDLE_BAIL_SECS && disk_idle >= timeouts::IDLE_BAIL_SECS {
2873            if !fatal {
2874                // Install path: say so loudly, keep waiting. Only the
2875                // operator halts an install. Warn every time past bail
2876                // (not warn-once): a stall that persists for hours should
2877                // stay visible, and nothing else will say it.
2878                eprintln!(
2879                    "warning: no disk I/O for {idle}s, disk static for {disk_idle}s and no SSH — guest may be parked at an input screen (Ctrl-C stops the install, nothing else does)"
2880                );
2881                return Ok(());
2882            }
2883            // Cause only; failure arms append frame + serial + VNC.
2884            anyhow::bail!(
2885                "guest appears stuck: no disk I/O for {idle}s, disk static for {disk_idle}s and no SSH — likely parked at an input screen (recovery, EULA)"
2886            );
2887        }
2888        if idle >= timeouts::IDLE_WARN_SECS && !self.warned {
2889            self.warned = true;
2890            // Never name an input screen without seeing one: the SSH-probe
2891            // loop calls with no frame (None), while the sampler task may
2892            // concurrently report progress. A blind loop claiming a parked
2893            // input screen next to an installer-progress line is the exact
2894            // contradiction that erodes trust in every other warning.
2895            if state.is_none() {
2896                eprintln!("warning: no disk I/O for {idle}s and no SSH banner yet — still waiting");
2897            } else {
2898                eprintln!(
2899                    "warning: no disk I/O for {idle}s and no SSH yet — guest may be stuck at an input screen"
2900                );
2901            }
2902        }
2903        Ok(())
2904    }
2905}
2906
2907/// Time-lapse dir name under the VM dir, and frame filename prefix.
2908/// Single source: screenshots_dir() builds the path, take_screenshot names files.
2909pub const SCREENSHOTS_DIR: &str = "screenshots";
2910
2911fn screenshots_dir(vm_dir: &Path) -> PathBuf {
2912    vm_dir.join(SCREENSHOTS_DIR)
2913}
2914
2915/// Monitor command setting the VNC password. Single source so the run
2916/// and install paths cannot drift (or typo) apart again.
2917fn vnc_password_command() -> String {
2918    format!("change vnc password {PROVEN_VNC_PASSWORD}")
2919}
2920
2921/// Evidence block for a failed boot wait: final frame (path + screen
2922/// classification), last serial line, activity evidence, VNC coordinates.
2923/// Pure formatter so the layout is unit-testable; [`boot_failure_report`]
2924/// gathers the parts.
2925fn format_failure_report(
2926    frame: Option<(PathBuf, ScreenState)>,
2927    serial: &str,
2928    boots: u64,
2929    activity: Option<(u64, u64)>,
2930    vnc: &Option<String>,
2931) -> String {
2932    let mut out = match frame {
2933        Some((p, s)) => format!("boot diagnosis: {s} — {}", p.display()),
2934        None => "boot diagnosis: no screenshot could be captured".to_string(),
2935    };
2936    if !serial.is_empty() {
2937        out.push_str(&format!("\n  last serial: {serial}"));
2938    }
2939    out.push_str(&format!("\n  guest boots seen: {boots}"));
2940    if let Some((idle_secs, growth)) = activity {
2941        out.push_str(&format!(
2942            "\n  guest activity: no I/O for {idle_secs}s, disk +{}",
2943            fmt_bytes(growth)
2944        ));
2945    }
2946    if let Some(u) = vnc {
2947        out.push_str(&format!("\n  vnc: {u} (password {PROVEN_VNC_PASSWORD})"));
2948    }
2949    out
2950}
2951
2952/// Gather the evidence for [`format_failure_report`]: one final frame off
2953/// the live monitor (the serial is silent through a Windows boot, so the
2954/// screen is the primary witness), the last meaningful serial line, one
2955/// activity sample, and the caller's VNC coordinates. Every part is
2956/// best-effort — a missing piece is stated, never invented.
2957async fn boot_failure_report(
2958    mon: &crate::ipc::Monitor,
2959    serial_log: &str,
2960    shots_dir: &Path,
2961    vnc: &Option<String>,
2962) -> String {
2963    let frame = take_screenshot(mon, shots_dir)
2964        .await
2965        .map(|(p, s, _)| (p, s));
2966    let serial = last_serial_line(serial_log);
2967    let mut activity_mon = ActivityMonitor::new();
2968    let disk = shots_dir.parent().map(|d| d.join(crate::paths::DISK_IMAGE));
2969    activity_mon.sample(mon, disk.as_deref()).await;
2970    let activity = Some((activity_mon.idle_secs(), activity_mon.growth_since_start()));
2971    format_failure_report(frame, &serial, boot_count(serial_log), activity, vnc)
2972}
2973
2974/// Background time-lapse: ticks on the profile until aborted. Returns the
2975/// join handle (`None` when every cadence is off); callers `.abort()` it
2976/// when the wait ends.
2977fn spawn_sampler(
2978    mon: std::sync::Arc<crate::ipc::Monitor>,
2979    screenshots_dir: PathBuf,
2980    disk: PathBuf,
2981    profile: SamplingProfile,
2982    label: &'static str,
2983) -> Option<tokio::task::JoinHandle<()>> {
2984    let tick = profile.tick()?;
2985    Some(tokio::spawn(async move {
2986        // First frame immediately (proves the display is alive early),
2987        // then on cadence. Numbered, basename-only (the dir was announced
2988        // once above), so the log reads as progress toward the SSH answer.
2989        let mut sampler = ScreenSampler::new(mon, screenshots_dir);
2990        let mut activity = ActivityMonitor::new();
2991        sampler.poll(&profile).await;
2992        report_sample(label, &sampler, &activity);
2993        let mut ticker = tokio::time::interval(tick);
2994        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
2995        ticker.tick().await; // skip the immediate tick
2996        loop {
2997            ticker.tick().await;
2998            activity.sample(&sampler.mon, Some(disk.as_path())).await;
2999            sampler.poll(&profile).await;
3000            // Stall check after the fresh classification: frozen I/O
3001            // during valid progress is a slow host, never a stuck guest.
3002            // Warn-only by construction (fatal=false never errs): no
3003            // screen, state, or activity reading exits this loop early.
3004            // The task ends solely on abort (victory) or cancellation.
3005            activity.check_stall(sampler.state(), false).ok();
3006            report_sample(label, &sampler, &activity);
3007        }
3008    }))
3009}
3010
3011/// One scrollback-safe status line per tick: the whole instrument panel.
3012/// Nothing prints for [`SampleOutcome::Skipped`].
3013fn report_sample(label: &str, sampler: &ScreenSampler, activity: &ActivityMonitor) {
3014    let (noun, n, state, margin, file) = match &sampler.last_outcome {
3015        SampleOutcome::Saved(p, s, m) => (
3016            "screenshot",
3017            sampler.shot_n,
3018            *s,
3019            *m,
3020            p.file_name()
3021                .unwrap_or_default()
3022                .to_string_lossy()
3023                .into_owned(),
3024        ),
3025        // Status lines carry wall-clock runtime, not a counter: on a
3026        // 3-hour install "status 412" says nothing, "2h41m" says where.
3027        SampleOutcome::Classified(s, m) => (
3028            "status",
3029            sampler.started.elapsed().as_secs(),
3030            *s,
3031            *m,
3032            String::new(),
3033        ),
3034        SampleOutcome::Skipped => return,
3035    };
3036    // Error reads warn only under the activity conjunction (flat guest);
3037    // a moving guest with an error read is a transient misread or live
3038    // recovery, and logs as observation, never alarm.
3039    let warn = if is_error_state(state) && !activity.is_moving() {
3040        "WARNING: "
3041    } else {
3042        ""
3043    };
3044    let file_part = if file.is_empty() {
3045        String::new()
3046    } else {
3047        format!("{file} ")
3048    };
3049    // Disk growth reads with its own age: a disk that stopped growing
3050    // long ago while I/O still trickles is a different shape than both
3051    // moving together.
3052    let disk_part = if activity.disk_idle_secs() >= timeouts::IDLE_WARN_SECS {
3053        format!(
3054            "disk +{} (static {})",
3055            fmt_bytes(activity.growth_since_start()),
3056            fmt_secs(activity.disk_idle_secs())
3057        )
3058    } else {
3059        format!("disk +{}", fmt_bytes(activity.growth_since_start()))
3060    };
3061    eprintln!(
3062        "{warn}{label} {noun} {}: {file_part}{} (phase {}, static {}, io {}/s avg, {disk_part}, io-idle {})",
3063        if noun == "status" {
3064            fmt_secs(n)
3065        } else {
3066            n.to_string()
3067        },
3068        describe(state, margin),
3069        fmt_secs(sampler.phase_secs()),
3070        fmt_secs(sampler.static_secs()),
3071        fmt_bytes(activity.io_ema_bps as u64),
3072        fmt_secs(activity.idle_secs()),
3073    );
3074}
3075
3076/// Tri-state banner probe: distinguishes a closed port (nothing
3077/// listening — sshd not started) from an open-but-silent one (TCP
3078/// accepted, no SSH banner — sshd starting, or something else holding
3079/// the port). The wait loops log transitions; a long silence that moves
3080/// Closed→Silent is progress, not a stall.
3081#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3082enum BannerProbe {
3083    Banner,
3084    /// Accepted, no bytes (timeout or clean EOF): listener present,
3085    /// banner not out yet.
3086    OpenSilent,
3087    /// Accepted, but the bytes are not SSH: wrong daemon, port squat,
3088    /// or corrupt transmission — never "sshd starting".
3089    Unexpected,
3090    Closed,
3091}
3092
3093async fn probe_banner(port: u16) -> (BannerProbe, Option<String>) {
3094    use tokio::io::AsyncReadExt;
3095    let stream = match tokio::time::timeout(
3096        timeouts::SSH_BANNER_CONNECT_BUDGET,
3097        tokio::net::TcpStream::connect((PROVEN_SSH_HOST, port)),
3098    )
3099    .await
3100    {
3101        Ok(Ok(s)) => s,
3102        _ => return (BannerProbe::Closed, None),
3103    };
3104    let mut buf = [0u8; 256];
3105    let mut stream = stream;
3106    match tokio::time::timeout(timeouts::SSH_BANNER_READ_BUDGET, stream.read(&mut buf)).await {
3107        Ok(Ok(n)) if n > 0 => {
3108            let b = String::from_utf8_lossy(&buf[..n]);
3109            if b.starts_with("SSH-") {
3110                (BannerProbe::Banner, Some(b.trim().to_string()))
3111            } else {
3112                (BannerProbe::Unexpected, None)
3113            }
3114        }
3115        // Accepted but silent: starting, not absent.
3116        _ => (BannerProbe::OpenSilent, None),
3117    }
3118}
3119
3120/// One banner read ([`timeouts::SSH_BANNER_CONNECT_BUDGET`] +
3121/// [`timeouts::SSH_BANNER_READ_BUDGET`]). `None` = no sshd right now.
3122async fn banner_once(port: u16) -> Option<String> {
3123    probe_banner(port).await.1
3124}
3125
3126/// Guest readiness: banner phases for display, registry probe for truth.
3127/// The FIRST banner only means Setup reached a boot with SSH up — Windows
3128/// then typically reboots into further passes. Victory is declared when
3129/// the guest itself reports Setup done (no OOBE in progress, no reboot
3130/// pending), not after any fixed time window. Returns the banner (for the
3131/// `tested-isos.jsonl` record).
3132///
3133/// Always probes with the default password (the media is always built with
3134/// it — Setup rejects weak ones mid-install). A custom `password` is
3135/// rotated in after READY, before the ready line, via
3136/// `change_guest_password` (which verifies the new login). The custom
3137/// password never touches the answer file.
3138/// Shared observability for the install/boot waits: the one monitor
3139/// session plus the paths it watches. Bundled so the wait fns don't
3140/// sprawl argument lists (clippy limit is 7). `vnc` is the report
3141/// coordinate (None for gtk/cocoa/none displays).
3142#[derive(Clone)]
3143struct GuestScope {
3144    mon: std::sync::Arc<crate::ipc::Monitor>,
3145    shots_dir: PathBuf,
3146    serial_log: String,
3147    vnc: Option<String>,
3148}
3149
3150async fn wait_install_ready(
3151    port: u16,
3152    deadline: Duration,
3153    user: &str,
3154    password: &str,
3155    recovery: bool,
3156    auto_updates: bool,
3157    scope: &GuestScope,
3158) -> Result<String> {
3159    use crate::ssh::{GuestProgress, probe_setup_done};
3160    use crate::unattend::DEFAULT_PASSWORD;
3161    let start = std::time::Instant::now();
3162    // Phase 1: first banner.
3163    let mut activity = ActivityMonitor::new();
3164    // Disk beside the screenshots dir feeds growth tracking (`shots_dir`
3165    // is `<vm>/screenshots`, so its parent is the VM dir).
3166    let disk = scope
3167        .shots_dir
3168        .parent()
3169        .map(|d| d.join(crate::paths::DISK_IMAGE));
3170    // Reboot awareness while Setup applies (no SSH yet — serial is the
3171    // only below-screenshot voice): count OVMF firmware handoffs.
3172    let mut boots_seen = boot_count(&scope.serial_log);
3173    // The install never times out on its own: only the operator stops it
3174    // (Ctrl-C). Past the deadline the loop says so loudly and keeps
3175    // waiting — a slow host is not a failed install.
3176    let mut deadline_warned = false;
3177    // Miss-reason tracking: a silence that moves closed→silent is sshd
3178    // stirring (progress); log transitions, never pollute per tick. None
3179    // until the first probe, so tick 1 always announces the baseline.
3180    let mut probe_state: Option<BannerProbe> = None;
3181    let banner = loop {
3182        if start.elapsed() > deadline && !deadline_warned {
3183            deadline_warned = true;
3184            eprintln!(
3185                "still no SSH banner on {PROVEN_SSH_HOST}:{port} after {} s — still waiting (Ctrl-C stops the install, nothing else does)",
3186                deadline.as_secs()
3187            );
3188        }
3189        match probe_banner(port).await {
3190            (BannerProbe::Banner, Some(b)) => {
3191                eprintln!(
3192                    "guest SSH is up (first contact) — Setup is still installing Windows, not ready yet ({b})"
3193                );
3194                break b;
3195            }
3196            (state, _) => {
3197                if Some(state) != probe_state {
3198                    probe_state = Some(state);
3199                    match state {
3200                        BannerProbe::Closed => eprintln!(
3201                            "ssh port {port} closed (sshd not started yet) — still waiting"
3202                        ),
3203                        BannerProbe::OpenSilent => eprintln!(
3204                            "ssh port {port} open but silent (sshd starting?) — still waiting"
3205                        ),
3206                        BannerProbe::Unexpected => eprintln!(
3207                            "ssh port {port} answered but not with SSH (wrong daemon or port squat?) — still waiting"
3208                        ),
3209                        BannerProbe::Banner => {}
3210                    }
3211                }
3212            }
3213        }
3214        // Dead-screen watchdog (same as run): fail fast with evidence.
3215        check_boot_failure(&scope.serial_log)?;
3216        // Reboot narration: Setup reboots between passes; announce each
3217        // firmware bounce instead of leaving the long wait mute.
3218        let boots = boot_count(&scope.serial_log);
3219        if let Some(note) = boot_note(boots_seen, boots) {
3220            eprintln!("{note}");
3221        }
3222        boots_seen = boots;
3223        // Stall watchdog: frozen disk I/O + no banner = parked. No screen
3224        // state down here (SSH probing, not frame watching), so take the
3225        // strict path — same as a boot that never rendered. Warn-only:
3226        // nothing but the operator halts an install.
3227        activity.sample(&scope.mon, disk.as_deref()).await;
3228        activity.check_stall(None, false)?;
3229        tokio::time::sleep(timeouts::SSH_POLL_INTERVAL).await;
3230    };
3231    // Phase 2: ask the guest until it reports done. Banner loss between
3232    // probes means a reboot (reported); probe errors mean sshd is
3233    // mid-restart (retried, not fatal). Each probe gets a hard budget: a
3234    // stalled handshake mid-reboot must surface, never hang the loop.
3235    // Separate counter for the overloaded state: banner stable but every
3236    // exec timing out means the guest is too saturated to cold-start
3237    // PowerShell (Setup still applying), not rebooting. Hammering it with
3238    // a probe every 10 s only stacks more powershell.exe on the pile, so
3239    // the cadence backs off while stalled.
3240    //
3241    // Narration policy: transient states print once per *change* (reboot,
3242    // new pending phase) plus a slow heartbeat — never one line per probe.
3243    // Default output is progress; words like "failed"/"ERROR" are reserved
3244    // for things that are actually wrong (raw errors: RUST_LOG=debug).
3245    let mut reboots = 0u32;
3246    let mut was_up = true;
3247    let mut exec_stalls = 0u32;
3248    // Last pending-state line printed, and when the heartbeat last fired.
3249    let mut phase: Option<String> = None;
3250    let mut last_beat = start;
3251    // Same operator-only rule as phase 1: the install never times out on
3252    // its own. Past the deadline the loop says so loudly and keeps
3253    // probing — a slow host is not a failed install.
3254    let mut deadline_warned = false;
3255    loop {
3256        if start.elapsed() > deadline && !deadline_warned {
3257            deadline_warned = true;
3258            eprintln!(
3259                "still waiting for guest readiness on {PROVEN_SSH_HOST}:{port} after {} s — still probing (Ctrl-C stops the install, nothing else does)",
3260                deadline.as_secs()
3261            );
3262        }
3263        // The probe itself gets a hard budget: a stalled handshake
3264        // mid-reboot would otherwise hang the loop silently (observed as
3265        // "long polling, never noticing SSH is up"). Timeout = not yet.
3266        match tokio::time::timeout(
3267            timeouts::READINESS_PROBE_BUDGET,
3268            probe_setup_done(PROVEN_SSH_HOST, port, user, DEFAULT_PASSWORD),
3269        )
3270        .await
3271        {
3272            Ok(Ok(GuestProgress::Ready)) => {
3273                if password != DEFAULT_PASSWORD {
3274                    eprintln!("rotating guest password ...");
3275                    crate::ssh::change_guest_password(
3276                        PROVEN_SSH_HOST,
3277                        port,
3278                        user,
3279                        DEFAULT_PASSWORD,
3280                        password,
3281                    )
3282                    .await?;
3283                }
3284                // Recovery policy (default off, docker-like): a damaged disk
3285                // fails fast instead of parking at "Diagnosing your PC".
3286                // Specialize already set the off state on the first OS boot
3287                // (an early Ctrl-C is covered there); this step applies the
3288                // flag's end state as the credential (post-rotation) —
3289                // `--recovery` re-arms both switches.
3290                if let Err(e) = crate::ssh::set_recovery_enabled(
3291                    PROVEN_SSH_HOST,
3292                    port,
3293                    user,
3294                    password,
3295                    recovery,
3296                )
3297                .await
3298                {
3299                    eprintln!("warning: bcdedit failed ({e:#}); recovery state unchanged");
3300                }
3301                // Update policy (default off, docker-like): wuauserv runs as
3302                // SYSTEM and would otherwise reboot the box on Microsoft's
3303                // schedule with no logon. Disabled = deterministic; manual
3304                // updates over SSH still work anytime.
3305                if !auto_updates
3306                    && let Err(e) =
3307                        crate::ssh::set_auto_updates(PROVEN_SSH_HOST, port, user, password, false)
3308                            .await
3309                {
3310                    eprintln!("warning: wuauserv disable failed ({e:#})");
3311                }
3312                // Headless diet (was specialize orders; moved post-READY so
3313                // four PowerShell cold starts stop serializing into Setup):
3314                // NLA Private + service trim in one invocation, best-effort.
3315                if let Err(e) =
3316                    crate::ssh::apply_headless_diet(PROVEN_SSH_HOST, port, user, password).await
3317                {
3318                    eprintln!("warning: headless diet failed ({e:#})");
3319                }
3320                eprintln!(
3321                    "guest reports Setup complete across {reboots} reboot(s) — install complete"
3322                );
3323                return Ok(banner);
3324            }
3325            Ok(Ok(GuestProgress::Busy(what))) => {
3326                exec_stalls = 0;
3327                if phase.as_deref() == Some(what.as_str()) {
3328                    // Unchanged since the last probe: stay quiet unless the
3329                    // heartbeat is due (proof of life on a long install).
3330                    if last_beat.elapsed() >= timeouts::PROGRESS_HEARTBEAT {
3331                        last_beat = std::time::Instant::now();
3332                        eprintln!(
3333                            "still installing: {what} — {}s elapsed, {reboots} reboot(s) so far",
3334                            start.elapsed().as_secs()
3335                        );
3336                    }
3337                } else {
3338                    eprintln!("still installing: {what}");
3339                    phase = Some(what);
3340                    last_beat = std::time::Instant::now();
3341                }
3342            }
3343            Ok(Err(e)) => {
3344                exec_stalls += 1;
3345                if e.downcast_ref::<crate::ssh::ProbeOutputBroken>().is_some() {
3346                    // OUR probe broke, not the guest: never narrate that as a
3347                    // reboot. Rare but real, so it stays at the default level.
3348                    if exec_stalls == 1 || exec_stalls == 5 {
3349                        eprintln!(
3350                            "warning: readiness probe could not read the guest's reply ({e:#}) — probe/output problem, not a reboot; retrying ..."
3351                        );
3352                    }
3353                } else if exec_stalls == 1 {
3354                    // Expected while Setup reboots: sshd restarts with the
3355                    // guest. One calm line per stall run; the raw transport
3356                    // error goes to RUST_LOG=debug instead of reading as a
3357                    // failure.
3358                    eprintln!(
3359                        "waiting: SSH dropped — Windows is rebooting as part of Setup, retrying ..."
3360                    );
3361                    tracing::debug!("probe error: {e:#}");
3362                } else if exec_stalls == 5 {
3363                    // Five straight exec failures with the banner up is not a
3364                    // reboot (the banner would drop) — it is saturation.
3365                    eprintln!(
3366                        "exec stalled 5x with SSH stable — guest is overloaded (Setup still applying), not rebooting; backing off probes ..."
3367                    );
3368                }
3369            }
3370            Err(_) => {
3371                exec_stalls += 1;
3372                if exec_stalls == 1 {
3373                    eprintln!(
3374                        "waiting: probe timed out — guest is busy (Setup still applying), retrying ..."
3375                    );
3376                } else if exec_stalls == 5 {
3377                    eprintln!(
3378                        "probe timed out 5x with SSH stable — guest is overloaded, backing off probes ..."
3379                    );
3380                }
3381            }
3382        }
3383        let up = banner_once(port).await.is_some();
3384        match (was_up, up) {
3385            (true, false) => {
3386                eprintln!(
3387                    "Windows is rebooting (#{}) — SSH dropped, waiting for it to return ...",
3388                    reboots + 1
3389                );
3390            }
3391            (false, true) => {
3392                reboots += 1;
3393                exec_stalls = 0;
3394                eprintln!("SSH back (reboot #{reboots} finished) — resuming probes ...");
3395            }
3396            _ => {}
3397        }
3398        was_up = up;
3399        // Back off while stalled (10 s → up to 60 s): each probe spawns a
3400        // PowerShell cold start, and hammering a saturated guest buries it.
3401        let backoff = 1 + (exec_stalls / 5).min(5);
3402        tokio::time::sleep(timeouts::READINESS_PROBE_INTERVAL * backoff).await;
3403    }
3404}
3405
3406/// Ctrl-C and SIGTERM both mean "stop the VM". Signals don't unwind, so
3407/// without this a SIGTERM'd CLI would orphan QEMU despite `kill_on_drop`.
3408#[cfg(unix)]
3409async fn shutdown_signal() {
3410    use tokio::signal::unix::{SignalKind, signal};
3411    let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler");
3412    tokio::select! {
3413        _ = tokio::signal::ctrl_c() => {},
3414        _ = term.recv() => {},
3415    }
3416}
3417
3418#[cfg(not(unix))]
3419async fn shutdown_signal() {
3420    let _ = tokio::signal::ctrl_c().await;
3421}
3422
3423#[cfg(test)]
3424mod tests {
3425    use super::*;
3426
3427    fn install_fixture(memory_mb: u32, cpus: u32) -> (Vec<String>, Vec<String>) {
3428        let dir = std::env::temp_dir();
3429        let code = dir.join("code.fd");
3430        let vars = dir.join("vars.fd");
3431        let usb = dir.join("usb.dmg");
3432        let spec = InstallQemuArgv {
3433            machine: "virt",
3434            accel: "tcg",
3435            cpu: "max",
3436            memory_mb,
3437            cpus,
3438            display: Display::Vnc("vnc=127.0.0.1:10,password=on".to_string()),
3439            code_tpl: &code,
3440            vars_fd: &vars,
3441            serial_log: "serial.log",
3442            mon_sock: "mon.sock",
3443            qmp_sock: "qmp.sock",
3444            usb_image: &usb,
3445            target: "disk.qcow2",
3446            arch: Architecture::Arm64,
3447        };
3448        (
3449            install_qemu_argv(&spec),
3450            qemu_img_create_args("disk.qcow2", 128),
3451        )
3452    }
3453
3454    #[test]
3455    fn install_sizing_reaches_qemu_argv() {
3456        // The flags a user passes must be the bytes QEMU gets: no QEMU
3457        // needed, just the pure argv constructors.
3458        // Golden sidecar lives next to the disk it blesses.
3459        assert_eq!(
3460            golden_sidecar("disk.qcow2"),
3461            std::path::PathBuf::from("disk.qcow2.golden")
3462        );
3463        let (argv, img) = install_fixture(8192, 8);
3464        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
3465        assert_eq!(at("-m"), "8192");
3466        assert_eq!(at("-smp"), "8");
3467        assert_eq!(img.last().unwrap(), "128G");
3468        // Defaults stay proven-shaped.
3469        let (argv, img) = install_fixture(4096, 4);
3470        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
3471        assert_eq!(at("-m"), "4096");
3472        assert_eq!(at("-smp"), "4");
3473        assert_eq!(at("-display"), "vnc=127.0.0.1:10,password=on");
3474        let img64 = qemu_img_create_args("disk.qcow2", 64);
3475        assert_eq!(img64.last().unwrap(), "64G");
3476        assert_eq!(img[..5], img64[..5]);
3477    }
3478
3479    #[test]
3480    fn live_migration_uris_quote_paths() {
3481        // NIC name comes from `info network`, never guessed: first
3482        // type=nic entry wins, netdev/user lines are skipped.
3483        let info = "virtio-net-pci.0: index=0,type=nic,model=virtio-net-pci,macaddr=52:54:00:12:34:56\n \\ n1: index=0,type=user,net=10.0.2.0/24,hostfwd=tcp::2232-:22\n";
3484        assert_eq!(find_nic_name(info), Some("virtio-net-pci.0"));
3485        assert_eq!(find_nic_name("n1: index=0,type=user\n"), None);
3486        assert_eq!(find_nic_name("garbage\n"), None);
3487        // Migration URIs quote paths (cache dirs contain spaces) and the
3488        // live companions live next to the disk they belong to.
3489        let spaced = std::path::Path::new("/Volumes/2TB Storage Vault/vm/golden-live.state");
3490        assert_eq!(
3491            migrate_write_uri(spaced),
3492            "exec:cat > '/Volumes/2TB Storage Vault/vm/golden-live.state'"
3493        );
3494        assert_eq!(
3495            migrate_read_uri(spaced),
3496            "exec:cat '/Volumes/2TB Storage Vault/vm/golden-live.state'"
3497        );
3498        let quoted = std::path::Path::new("/tmp/o'brien/state");
3499        assert_eq!(
3500            migrate_write_uri(quoted),
3501            "exec:cat > '/tmp/o'\\''brien/state'"
3502        );
3503        let dir = std::path::Path::new("/tmp/vm");
3504        let (state, vars, overlay) = live_paths(dir);
3505        assert_eq!(state, dir.join(crate::paths::LIVE_STATE_FILE));
3506        assert_eq!(vars, dir.join(crate::paths::LIVE_VARS_BACKUP));
3507        assert_eq!(overlay, dir.join(crate::paths::LIVE_OVERLAY));
3508    }
3509
3510    #[test]
3511    fn install_cocoa_display_passes_through() {
3512        // Non-VNC displays reach QEMU verbatim (the VNC password step is
3513        // guarded separately); cocoa installs show a window instead.
3514        let dir = std::env::temp_dir();
3515        let code = dir.join("code.fd");
3516        let vars = dir.join("vars.fd");
3517        let usb = dir.join("usb.dmg");
3518        let spec = InstallQemuArgv {
3519            machine: "virt",
3520            accel: "tcg",
3521            cpu: "max",
3522            memory_mb: 4096,
3523            cpus: 4,
3524            display: Display::Cocoa,
3525            code_tpl: &code,
3526            vars_fd: &vars,
3527            serial_log: "serial.log",
3528            mon_sock: "mon.sock",
3529            qmp_sock: "qmp.sock",
3530            usb_image: &usb,
3531            target: "disk.qcow2",
3532            arch: Architecture::Arm64,
3533        };
3534        let argv = install_qemu_argv(&spec);
3535        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
3536        assert_eq!(at("-display"), "cocoa");
3537    }
3538
3539    #[test]
3540    fn blockstats_parse_totals() {
3541        let sample = "drive-tgt: rd_bytes=1048576 wr_bytes=524288 rd_operations=12\n\
3542                      drive-usb: rd_bytes=100 wr_bytes=0\n";
3543        assert_eq!(
3544            ActivityMonitor::parse_total(sample),
3545            Some(1048576 + 524288 + 100)
3546        );
3547        assert_eq!(ActivityMonitor::parse_total(""), None);
3548    }
3549
3550    #[test]
3551    fn activity_math_without_qemu() {
3552        // Pure derivations on hand-built state: no monitor, no sleeps.
3553        let now = std::time::Instant::now();
3554        let mut m = ActivityMonitor {
3555            last_total: 1000,
3556            last_change: now - Duration::from_secs(61),
3557            warned: false,
3558            disk_start: Some(100),
3559            disk_last: 150,
3560            disk_last_change: now - Duration::from_secs(61),
3561            last_sample: Some(now),
3562            io_ema_bps: 0.0,
3563            growth_ema_bps: 0.0,
3564        };
3565        assert_eq!(m.idle_secs(), 61);
3566        assert_eq!(m.disk_idle_secs(), 61);
3567        assert_eq!(m.growth_since_start(), 50);
3568        assert!(!m.is_moving());
3569        // EMA: half-window step moves halfway to the instant rate.
3570        assert_eq!(ActivityMonitor::ema_step(0.0, 100.0, 150.0, 300.0), 50.0);
3571        assert_eq!(ActivityMonitor::ema_step(50.0, 100.0, 0.0, 300.0), 50.0);
3572        // Fresh activity resets the idle clock.
3573        m.last_change = std::time::Instant::now();
3574        assert!(m.is_moving());
3575    }
3576
3577    #[test]
3578    fn stall_watchdog_needs_non_progress_and_flat_guest() {
3579        // Progress states never bail, however long I/O has been flat: a
3580        // slow host applying the image answers only to the operator, not
3581        // the stall watchdog (live 2026-10-07: 120s of CPU-bound setup
3582        // with InstallerStep on screen aborted a valid install).
3583        let mut m = ActivityMonitor {
3584            last_total: 1000,
3585            last_change: std::time::Instant::now() - Duration::from_secs(10_000),
3586            warned: false,
3587            disk_start: Some(100),
3588            disk_last: 100,
3589            disk_last_change: std::time::Instant::now() - Duration::from_secs(10_000),
3590            last_sample: None,
3591            io_ema_bps: 0.0,
3592            growth_ema_bps: 0.0,
3593        };
3594        for state in [
3595            ScreenState::InstallerStep,
3596            ScreenState::OobeStep,
3597            ScreenState::FirmwareBoot,
3598            ScreenState::Lockscreen,
3599        ] {
3600            assert!(m.check_stall(Some(state), true).is_ok(), "{state:?}");
3601        }
3602        // Non-progress + flat on both signals bails when fatal.
3603        assert!(m.check_stall(Some(ScreenState::ErrorScreen), true).is_err());
3604        assert!(m.check_stall(Some(ScreenState::Dark), true).is_err());
3605        // No frame yet: strict path, bails like a boot that never rendered.
3606        assert!(m.check_stall(None, true).is_err());
3607        // Flat I/O but a growing disk is not parked: bail needs both.
3608        m.disk_last_change = std::time::Instant::now();
3609        m.disk_last = 200;
3610        assert!(m.check_stall(Some(ScreenState::ErrorScreen), true).is_ok());
3611        // Install path is warn-only: the same flat guest that bails above
3612        // only warns when fatal is false — nothing but the operator halts
3613        // an install.
3614        m.disk_last_change = std::time::Instant::now() - Duration::from_secs(10_000);
3615        m.disk_last = 100;
3616        assert!(m.check_stall(Some(ScreenState::ErrorScreen), false).is_ok());
3617        assert!(m.check_stall(None, false).is_ok());
3618    }
3619
3620    #[test]
3621    fn tilde_expands_to_home() {
3622        let home = std::env::var("HOME").unwrap();
3623        assert_eq!(
3624            expand_tilde("~/x.iso".into()),
3625            PathBuf::from(home.clone()).join("x.iso")
3626        );
3627        assert_eq!(expand_tilde("~".into()), PathBuf::from(home));
3628        // Untouched: relative, absolute, other users.
3629        assert_eq!(expand_tilde("rel/x.iso".into()), PathBuf::from("rel/x.iso"));
3630        assert_eq!(
3631            expand_tilde("/abs/x.iso".into()),
3632            PathBuf::from("/abs/x.iso")
3633        );
3634        assert_eq!(
3635            expand_tilde("~other/x.iso".into()),
3636            PathBuf::from("~other/x.iso")
3637        );
3638    }
3639
3640    #[test]
3641    fn missing_iso_error_names_the_path_it_tried() {
3642        let tmp = tempfile::tempdir().unwrap();
3643        let present = tmp.path().join("present.iso");
3644        std::fs::write(&present, b"x").unwrap();
3645        assert!(require_win_iso(&present).is_ok());
3646        // A directory is not an ISO.
3647        assert!(require_win_iso(tmp.path()).is_err());
3648
3649        let missing = tmp.path().join("Win11.iso");
3650        let err = require_win_iso(&missing).unwrap_err().to_string();
3651        assert!(err.contains(&missing.display().to_string()), "{err}");
3652        assert!(!err.contains("quote-shielded"), "{err}");
3653        assert!(!err.contains("unquoted"), "{err}");
3654
3655        // A literal `~` survives expand_tilde only when $HOME is unset (or
3656        // the path is ~otheruser) — the hint must say that, not "quote it".
3657        let err = require_win_iso(Path::new("~/Win11.iso"))
3658            .unwrap_err()
3659            .to_string();
3660        assert!(err.contains("$HOME"), "{err}");
3661        let err = require_win_iso(Path::new("~other/x.iso"))
3662            .unwrap_err()
3663            .to_string();
3664        assert!(err.contains("~otheruser"), "{err}");
3665    }
3666
3667    #[test]
3668    fn report_renders_table() {
3669        use crate::provenance::{DependencyPins, GuestParams, HostSpecs, IsoIdentity, Provenance};
3670        let record = crate::provenance::TestRecord {
3671            tested_at_epoch: 1_758_600_000,
3672            outcome: "ssh-banner".to_string(),
3673            ssh_banner: Some("SSH-2.0-test".to_string()),
3674            provenance: Provenance {
3675                builder_version: "0.1.0".to_string(),
3676                build_commit: "abcdef1234567".to_string(),
3677                build_dirty: true,
3678                built_at_epoch: 1_758_600_000,
3679                source_iso: IsoIdentity {
3680                    file_name: "Win11.iso".to_string(),
3681                    size_bytes: 1,
3682                    sha256: "x".to_string(),
3683                    pvd_creation: None,
3684                    wim_images: vec![],
3685                },
3686                host: HostSpecs {
3687                    os: "macos".to_string(),
3688                    os_version: "26.0".to_string(),
3689                    arch: "aarch64".to_string(),
3690                },
3691                deps: DependencyPins {
3692                    qemu_tag: "qemu-v11.1.1".to_string(),
3693                    wimlib_tag: "wimlib-v1.14.5-27".to_string(),
3694                    virtio_iso_name: "virtio-win.iso".to_string(),
3695                    virtio_sha256: None,
3696                    openssh_zip_name: "OpenSSH-ARM64.zip".to_string(),
3697                    openssh_release_tag: "t".to_string(),
3698                },
3699                guest: GuestParams {
3700                    arch: "arm64".to_string(),
3701                    username: "u".to_string(),
3702                    locale: "en-US".to_string(),
3703                    accel: "tcg".to_string(),
3704                },
3705            },
3706        };
3707        let dir = tempfile::tempdir().unwrap();
3708        let log = dir.path().join("tested-isos.jsonl");
3709        std::fs::write(&log, serde_json::to_string(&record).unwrap() + "\n").unwrap();
3710        let table = render_report(&log).unwrap();
3711        assert!(table.contains("| Date | ISO |"), "{table}");
3712        assert!(table.contains("Win11.iso"), "{table}");
3713        assert!(table.contains("abcdef1*"), "{table}");
3714        // No virtio hash in the fixture → falls back to the ISO name.
3715        assert!(table.contains("virtio-win.iso"), "{table}");
3716        assert_eq!(epoch_to_date(1_758_600_000), "2025-09-23");
3717    }
3718
3719    // --- boot failure screen classification -------------------------------
3720
3721    #[test]
3722    fn boot_count_and_note_from_serial() {
3723        let path = std::env::temp_dir().join(format!("wh-boot-count-{}.log", std::process::id()));
3724        std::fs::write(
3725            &path,
3726            "BdsDxe: loading Boot0001 \"USB\"\n\
3727             BdsDxe: starting Boot0001 \"USB\"\n\
3728             BdsDxe: failed to load Boot0002 \"NVMe\": Not Found\n\
3729             BdsDxe: starting Boot0003 \"Windows Boot Manager\"\n",
3730        )
3731        .unwrap();
3732        assert_eq!(boot_count(path.to_str().unwrap()), 2);
3733        let _ = std::fs::remove_file(&path);
3734        assert_eq!(boot_count("/nonexistent/wh-no-serial.log"), 0);
3735        // Narration: first boot, reboots, flat, and regressions.
3736        assert_eq!(boot_note(0, 0), None);
3737        assert_eq!(
3738            boot_note(0, 1).as_deref(),
3739            Some("guest booted (first firmware boot)")
3740        );
3741        assert_eq!(
3742            boot_note(1, 3).as_deref(),
3743            Some("guest rebooted (firmware boot #3 seen on serial)")
3744        );
3745        assert_eq!(boot_note(3, 3), None);
3746        assert_eq!(boot_note(3, 2), None);
3747    }
3748
3749    #[test]
3750    fn screen_state_real_frames_classify_by_directory() {
3751        // Integration over real screendumps through the k-NN classifier.
3752        // The class directory IS the label: drop a capture in, rebuild
3753        // the index, and both this test and the runtime pick it up with
3754        // no filename list anywhere.
3755        // Layout: tests/fixtures/<windows-version>/<class-dir>/*.png.
3756        //
3757        // Verdicts are snapshotted, not asserted at 100%: the corpus
3758        // holds known-unlearnable twin pairs, so exact-fit is demanded
3759        // nowhere. A changed verdict fails with a diff; bless it with
3760        // `cargo insta review` (or `INSTA_UPDATE=always` as the
3761        // auto-accept escape hatch).
3762        // Single dir→label map: a new class dir touches one arm, never two.
3763        let target_for_class = |class: &str| match class {
3764            "dark" => ScreenState::Dark,
3765            "flat-field" => ScreenState::FlatField,
3766            "error-shell" => ScreenState::ErrorShell,
3767            "error-recovery" => ScreenState::ErrorRecovery,
3768            "error-bluescreen" | "error-modal" => ScreenState::ErrorScreen,
3769            "oobe-step" => ScreenState::OobeStep,
3770            "installer-step" => ScreenState::InstallerStep,
3771            "firmware-boot" => ScreenState::FirmwareBoot,
3772            "lockscreen" => ScreenState::Lockscreen,
3773            // Unknown future class dirs: fail loudly here instead of
3774            // silently absorbing into the snapshot.
3775            _ => panic!("test map missing class dir: {class}"),
3776        };
3777        let root = format!("{}/tests/fixtures", env!("CARGO_MANIFEST_DIR"));
3778        // The shipped path, not a test-only twin: the baked artifact
3779        // scores here exactly as the live tick scores in production.
3780        let index = crate::screen_knn::bundled_index();
3781        let mut checked = 0;
3782        let mut lines = Vec::new();
3783        let mut misses = Vec::new();
3784        let mut ok_gap_sum = 0.0f64;
3785        let mut versions: Vec<_> = std::fs::read_dir(&root)
3786            .unwrap()
3787            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3788            .collect();
3789        versions.sort();
3790        for version in versions {
3791            // Skip Finder noise (.DS_Store) and anything else that is
3792            // not a version directory.
3793            if !std::path::Path::new(&format!("{root}/{version}")).is_dir() {
3794                continue;
3795            }
3796            let mut classes: Vec<_> = std::fs::read_dir(format!("{root}/{version}"))
3797                .unwrap()
3798                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3799                .collect();
3800            classes.sort();
3801            for class in classes {
3802                let dir = format!("{root}/{version}/{class}");
3803                if !std::path::Path::new(&dir).is_dir() {
3804                    continue;
3805                }
3806                let mut names: Vec<_> = std::fs::read_dir(&dir)
3807                    .unwrap()
3808                    .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3809                    .filter(|n| n.ends_with(".png"))
3810                    .collect();
3811                names.sort();
3812                for name in names {
3813                    let key = format!("{version}/{class}/{name}");
3814                    // Unknown class dirs fail loudly via the map (never
3815                    // silently absorbed); misses group at the bottom under
3816                    // their own header, so no horizontal hunt/peck. Gaps
3817                    // print to stdout (not the snapshot: float formatting
3818                    // must stay bit-exact everywhere, and the gap is a
3819                    // tuning signal, not a verdict). Run with
3820                    // `-- --nocapture` to score an index rebuild: wider
3821                    // gaps bless new centers, narrower ones don't.
3822                    let want = target_for_class(&class);
3823                    let (got, gap, matched) = classify_fixture(&index, &key);
3824                    println!("gap {gap:.4} {key} via {matched}");
3825                    if got == want {
3826                        ok_gap_sum += f64::from(gap);
3827                        lines.push(format!("ok   {key} => {got:?}"));
3828                    } else {
3829                        misses.push(format!(
3830                            "MISS {key} => got {got:?}, want {want:?} via {matched}"
3831                        ));
3832                    }
3833                    checked += 1;
3834                }
3835            }
3836        }
3837        assert!(checked > 0, "no fixtures found under tests/fixtures");
3838        let ok_count = checked - misses.len();
3839        let mean_ok = ok_gap_sum / f64::from(ok_count.max(1) as u32);
3840        println!("mean ok-gap {mean_ok:.4} over {ok_count}/{checked}");
3841        lines.push(format!("--- misses {}/{checked} ---", misses.len()));
3842        lines.extend(misses);
3843        insta::assert_snapshot!("screen_state_by_directory", lines.join("\n"));
3844    }
3845
3846    /// Test-only fixture classification through the real live path:
3847    /// [`crate::vision::classify_screen`] on the decoded frame. Returns
3848    /// the state plus the matched exemplar name, so misses carry their
3849    /// cause into the snapshot itself.
3850    fn classify_fixture(
3851        index: &crate::screen_knn::KnnIndex,
3852        name: &str,
3853    ) -> (ScreenState, f32, String) {
3854        let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
3855        let (rgb, w, h) = crate::screen_knn::load_rgb_8bit(&path);
3856        let q = crate::screen_knn::KnnIndex::embed_frame(&rgb, w, h);
3857        let (got_class, gap, matched) = index.predict(&q, None).unwrap();
3858        let got = match got_class {
3859            crate::screen_knn::ScreenClass::Dark => ScreenState::Dark,
3860            crate::screen_knn::ScreenClass::FlatField => ScreenState::FlatField,
3861            crate::screen_knn::ScreenClass::ErrorShell => ScreenState::ErrorShell,
3862            crate::screen_knn::ScreenClass::InstallerStep => ScreenState::InstallerStep,
3863            crate::screen_knn::ScreenClass::Lockscreen => ScreenState::Lockscreen,
3864            crate::screen_knn::ScreenClass::FirmwareBoot => ScreenState::FirmwareBoot,
3865            crate::screen_knn::ScreenClass::OobeStep => ScreenState::OobeStep,
3866            crate::screen_knn::ScreenClass::ErrorRecovery => ScreenState::ErrorRecovery,
3867            crate::screen_knn::ScreenClass::ErrorScreen => ScreenState::ErrorScreen,
3868        };
3869        (got, gap, matched)
3870    }
3871
3872    #[test]
3873    fn vnc_password_command_is_exact() {
3874        // Regression: the install path once sent "change vnc p.password",
3875        // which QEMU ignores — VNC auth then failed with no error anywhere.
3876        assert_eq!(
3877            vnc_password_command(),
3878            format!("change vnc password {PROVEN_VNC_PASSWORD}")
3879        );
3880    }
3881
3882    #[test]
3883    fn run_chain_install_params_passes_cadence_through() {
3884        // Regression: `run --win-iso --screenshots-every-secs 10` installed
3885        // at 60s cadence because the chain hardcoded the default.
3886        let args = RunArgs {
3887            disk: None,
3888            ssh_port: crate::qemu::PROVEN_SSH_PORT,
3889            display: crate::qemu::Display::parse("vnc=127.0.0.1:10").unwrap(),
3890            memory: 4096,
3891            cpus: 4,
3892            disk_size: 64,
3893            vm_dir: None,
3894            qemu_dir: None,
3895            username: "u".into(),
3896            password: "p".into(),
3897            shell: false,
3898            live: false,
3899            win_iso: None,
3900            install_timeout_secs: 60,
3901            screenshots_every_secs: 10,
3902            classify_every_secs: Some(5),
3903        };
3904        let p = run_chain_install_params(&args, PathBuf::from("w.iso"));
3905        assert_eq!(p.screenshots_every_secs, 10);
3906        assert_eq!(p.classify_every_secs, Some(5));
3907        assert_eq!(p.install_timeout_secs, 60);
3908        assert_eq!(p.memory_mb, 4096);
3909        assert_eq!(p.cpus, 4);
3910        assert_eq!(p.disk_size_gb, 64);
3911    }
3912
3913    #[test]
3914    fn failure_report_carries_frame_serial_vnc() {
3915        let report = format_failure_report(
3916            Some((
3917                PathBuf::from("/vm/screenshots/screenshot-1.png"),
3918                ScreenState::FlatField,
3919            )),
3920            "BdsDxe: starting Boot0003",
3921            3,
3922            Some((95, 12_582_912)),
3923            &Some("vnc://127.0.0.1:5910".to_string()),
3924        );
3925        assert!(report.contains("solid color field"), "{report}");
3926        assert!(report.contains("guest boots seen: 3"), "{report}");
3927        assert!(
3928            report.contains("/vm/screenshots/screenshot-1.png"),
3929            "{report}"
3930        );
3931        assert!(
3932            report.contains("last serial: BdsDxe: starting Boot0003"),
3933            "{report}"
3934        );
3935        assert!(report.contains("vnc: vnc://127.0.0.1:5910"), "{report}");
3936        assert!(report.contains("no I/O for 95s"), "{report}");
3937    }
3938
3939    #[test]
3940    fn failure_report_states_missing_parts() {
3941        let report = format_failure_report(None, "", 0, None, &None);
3942        assert!(
3943            report.contains("no screenshot could be captured"),
3944            "{report}"
3945        );
3946        assert!(!report.contains("last serial"), "{report}");
3947        assert!(!report.contains("vnc:"), "{report}");
3948    }
3949}