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 {} {}@{PROVEN_SSH_HOST} (password: {})",
522            a.ssh_port, a.username, a.password
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 {} {}@{PROVEN_SSH_HOST} (password: {})",
939        a.ssh_port, a.username, a.password,
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!("ready — ssh -p {} {}@{PROVEN_SSH_HOST} (password: {})", PROVEN_SSH_PORT, p.username, p.password);
1731        }
1732        _ = shutdown_signal() => {
1733            eprintln!("interrupted; stopping guest...");
1734            if let Some(h) = &screenshots {
1735                h.abort();
1736            }
1737            child.kill().await?;
1738            // Interrupt is NOT success: bail so callers (`run --win-iso`)
1739            // stop the chain instead of booting a half-installed disk.
1740            anyhow::bail!("interrupted during install; disk left half-written (rerun to start over)");
1741        }
1742    }
1743    Ok(InstallSession {
1744        child,
1745        mon,
1746        vm_dir,
1747        screenshots,
1748        img_bin,
1749    })
1750}
1751
1752/// Snapshot the running guest's disk as the new golden state (`docker
1753/// commit`): proves the shell, stops QEMU, snapshots offline, and writes
1754/// the sidecar. The guest must be up (boot it with `run` first); QEMU is
1755/// left stopped afterward, so boot again to resume the new golden.
1756/// With `live`: QMP `savevm` on the running guest instead (no shutdown —
1757/// instant-boot state, experimental; the writable pflash drive may veto
1758/// it, in which case nothing is written and the guest keeps running).
1759pub async fn cmd_snapshot(
1760    vm_dir: Option<PathBuf>,
1761    qemu_dir: Option<PathBuf>,
1762    username: String,
1763    password: String,
1764    ssh_port: u16,
1765    live: bool,
1766) -> Result<()> {
1767    let vm_dir = match vm_dir {
1768        Some(d) => d,
1769        None => default_vm_dir()?,
1770    };
1771    let disk = vm_dir
1772        .join(crate::paths::DISK_IMAGE)
1773        .to_string_lossy()
1774        .into_owned();
1775    if !std::path::Path::new(&disk).is_file() {
1776        anyhow::bail!("no disk at {disk} (install first)");
1777    }
1778    // The guest must be running: a snapshot of a stopped disk proves
1779    // nothing about the shell.
1780    if banner_once(ssh_port).await.is_none() {
1781        anyhow::bail!(
1782            "no SSH banner on {PROVEN_SSH_HOST}:{ssh_port} (boot the guest with `run` first)"
1783        );
1784    }
1785    prove_landed_shell(ssh_port, &username, &password).await?;
1786    if live {
1787        // Live path: pivot an overlay (atomic — the base freezes at this
1788        // instant, post-save writes land in the overlay), then migrate
1789        // RAM + devices to the state file (migration transfers pflash
1790        // content, so the savevm veto does not apply), then back up VARS
1791        // (raw pflash lives outside every snapshot). Guest keeps running
1792        // throughout; crash-consistent like a power cut at the pivot.
1793        let (state, vars_backup, overlay) = live_paths(&vm_dir);
1794        // Fresh pivot each save: a leftover overlay would fail the pivot
1795        // and poison the consistency story.
1796        for p in [&state, &vars_backup, &overlay] {
1797            let _ = std::fs::remove_file(p);
1798        }
1799        let qmp_sock = crate::ipc::vm_endpoint(&vm_dir, crate::ipc::QMP_SOCK_NAME);
1800        let mut qmp = crate::qmp::QmpClient::connect(&qmp_sock).await?;
1801        eprintln!("pivoting live overlay (freezing base) ...");
1802        qmp.live_overlay("tgt", &overlay.to_string_lossy())
1803            .await
1804            .map_err(|e| anyhow::anyhow!("live overlay pivot refused ({e:#}) — guest untouched"))?;
1805        eprintln!("migrating guest state to file (brief stun) ...");
1806        qmp.migrate_to_file(&state).await.map_err(|e| {
1807            anyhow::anyhow!(
1808                "live migration refused ({e:#}) — guest still running on the overlay; delete {} to unwind",
1809                overlay.display()
1810            )
1811        })?;
1812        let deadline =
1813            std::time::Instant::now() + Duration::from_secs(timeouts::MIGRATION_BUDGET_SECS);
1814        loop {
1815            let status = qmp.query_migrate_status().await?;
1816            if status == "completed" {
1817                break;
1818            }
1819            if status == "failed" || status == "cancelled" {
1820                anyhow::bail!(
1821                    "live migration {status} — guest still running on the overlay; delete {} to unwind",
1822                    overlay.display()
1823                );
1824            }
1825            if std::time::Instant::now() > deadline {
1826                anyhow::bail!(
1827                    "live migration still '{status}' after {} s — guest still running on the overlay; delete {} to unwind",
1828                    timeouts::MIGRATION_BUDGET_SECS,
1829                    overlay.display()
1830                );
1831            }
1832            tokio::time::sleep(Duration::from_secs(timeouts::MIGRATION_POLL_SECS)).await;
1833        }
1834        std::fs::copy(vm_dir.join(crate::paths::VARS_FILE), &vars_backup)?;
1835        // Post-migration liveness: a completed job can still leave the VM
1836        // paused (observed: guest "locked up" after a clean save). Verify
1837        // running, resume if paused — never hand back a frozen guest.
1838        match qmp.query_vm_status().await?.as_str() {
1839            "running" => {}
1840            stalled => {
1841                eprintln!("guest {stalled} after migration — resuming ...");
1842                qmp.resume_vm().await?;
1843            }
1844        }
1845        std::fs::write(
1846            live_sidecar(&disk),
1847            format!("{}\n", crate::provenance::now_epoch()),
1848        )?;
1849        eprintln!("live snapshot saved — `run --live` resumes it instantly; guest still running.");
1850        return Ok(());
1851    }
1852    let img_bin = match qemu_dir {
1853        Some(d) => d
1854            .join(crate::paths::PORTABLE_BIN_DIR)
1855            .join(crate::paths::QEMU_IMG_NAME),
1856        None => {
1857            #[cfg(feature = "downloader")]
1858            {
1859                let q = crate::qemu_portable::pinned_cached()?;
1860                q.root
1861                    .join(crate::paths::PORTABLE_BIN_DIR)
1862                    .join(crate::paths::QEMU_IMG_NAME)
1863            }
1864            #[cfg(not(feature = "downloader"))]
1865            {
1866                PathBuf::from(crate::paths::QEMU_IMG_NAME)
1867            }
1868        }
1869    };
1870    // Clean halt first (guest-initiated, so the bit is clean), then QMP
1871    // quit reaps a halted QEMU, then the offline snapshot. A power-cut
1872    // snapshot would bake the dirty flag into every future rewind.
1873    shutdown_guest_clean(PROVEN_SSH_HOST, ssh_port, &username, &password).await?;
1874    cmd_stop(Some(vm_dir), None).await?;
1875    snapshot_golden(&img_bin, &disk).await?;
1876    eprintln!("golden refreshed — `run` resumes this state from now on.");
1877    Ok(())
1878}
1879
1880/// Standalone `install`: full install, then supervise the VM for a human
1881/// via the shared tail (final frame + optional shell + Ctrl-C wait + kill).
1882/// `shell` only affects this tail, never the install itself.
1883pub async fn cmd_install(p: InstallParams, shell: bool) -> Result<()> {
1884    let username = p.username.clone();
1885    let password = p.password.clone();
1886    let mut session = install_to_ready(p).await?;
1887    finish_install_capture(&mut session).await;
1888    // Golden before shell/kill: prove the shell now, snapshot now. A bounce
1889    // afterward voids the sidecar (watcher below) instead of having been
1890    // predicted by a timer.
1891    prove_landed_shell(PROVEN_SSH_PORT, &username, &password).await?;
1892    let target = session.vm_dir.join(crate::paths::DISK_IMAGE);
1893    let target_s = target.to_string_lossy().into_owned();
1894    if shell {
1895        let disk = target_s.clone();
1896        tokio::select! {
1897            _ = shell_then_wait(
1898                true,
1899                PROVEN_SSH_HOST,
1900                PROVEN_SSH_PORT,
1901                &username,
1902                &password,
1903                "press Ctrl-C to shut the VM down cleanly",
1904            ) => {},
1905            // Bounce voids golden but the install stands: keep waiting for
1906            // Ctrl-C afterward instead of exiting early.
1907            _ = watch_golden_void(PROVEN_SSH_PORT, disk) => {
1908                shell_then_wait(
1909                    true,
1910                    PROVEN_SSH_HOST,
1911                    PROVEN_SSH_PORT,
1912                    &username,
1913                    &password,
1914                    "press Ctrl-C to shut the VM down cleanly",
1915                )
1916                .await?;
1917            }
1918        }
1919    } else {
1920        eprintln!("install complete (non-interactive — shutting down guest)...");
1921    }
1922    // Clean halt before the snapshot (same reason as `snapshot`): golden
1923    // must capture a clean bit. Ctrl-C still kills instantly everywhere
1924    // else — only snapshot paths pay for clean.
1925    shutdown_guest_clean(PROVEN_SSH_HOST, PROVEN_SSH_PORT, &username, &password).await?;
1926    session.child.kill().await?;
1927    snapshot_golden(&session.img_bin, &target_s).await?;
1928    Ok(())
1929}
1930
1931// ---------------------------------------------------------------------------
1932// report
1933// ---------------------------------------------------------------------------
1934
1935pub struct ReportArgs {
1936    pub log: PathBuf,
1937    /// README to splice the table into (between TESTED markers). If absent,
1938    /// the table prints to stdout for manual pasting.
1939    pub readme: Option<PathBuf>,
1940}
1941
1942/// README filename refreshed automatically by `install` (repo root,
1943/// current dir at runtime). Marker-gated: absent markers mean warn, never
1944/// blind rewrite.
1945pub const README_FILE: &str = "README.md";
1946
1947const REPORT_BEGIN: &str = "<!-- TESTED-BEGIN -->";
1948const REPORT_END: &str = "<!-- TESTED-END -->";
1949
1950fn epoch_to_date(epoch: u64) -> String {
1951    // No chrono dep: days since epoch → approximate YYYY-MM-DD via a tiny
1952    // civil-date conversion (Howard Hinnant's algorithm).
1953    let days = (epoch / 86_400) as i64;
1954    let z = days + 719_468;
1955    let era = z.div_euclid(146_097);
1956    let doe = z.rem_euclid(146_097);
1957    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
1958    let y = yoe + era * 400;
1959    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1960    let mp = (5 * doy + 2) / 153;
1961    let d = doy - (153 * mp + 2) / 5 + 1;
1962    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1963    format!("{:04}-{:02}-{:02}", if m <= 2 { y + 1 } else { y }, m, d)
1964}
1965
1966/// Release page URL for a tag in our portable repo (used to link generated
1967/// report cells to the exact artifacts consumed).
1968fn release_tag_url(tag: &str) -> String {
1969    format!(
1970        "https://github.com/{}/releases/tag/{tag}",
1971        crate::pins::RELEASE_REPO
1972    )
1973}
1974
1975/// Render `tested-isos.jsonl` as a markdown table: the human-readable face
1976/// of the machine-readable log. Short commit + `*` when the build was dirty
1977/// (hash alone doesn't reproduce it); virtio as short SHA of the consumed
1978/// ISO (name when `--drivers-dir` bypassed the ISO). Newest first: the log
1979/// is append-only, so rows are collected then reversed for display.
1980/// QEMU/wimlib/virtio cells link to their exact release pages.
1981pub fn render_report(log: &Path) -> Result<String> {
1982    let text = std::fs::read_to_string(log).with_context(|| format!("read {}", log.display()))?;
1983    let mut rows = vec![
1984        "| Date | ISO | Arch | Accel | Host | QEMU | wimlib | virtio | Commit | Result |"
1985            .to_string(),
1986        "|---|---|---|---|---|---|---|---|---|---|".to_string(),
1987    ];
1988    let mut entries = Vec::new();
1989    for (n, line) in text.lines().enumerate() {
1990        let line = line.trim();
1991        if line.is_empty() {
1992            continue;
1993        }
1994        let r: crate::provenance::TestRecord = serde_json::from_str(line)
1995            .with_context(|| format!("{} line {}", log.display(), n + 1))?;
1996        let p = &r.provenance;
1997        let commit_short = p.build_commit.chars().take(7).collect::<String>();
1998        // Clean-tree hashes exist upstream — link them. Dirty-tree hashes
1999        // (`*`) don't, so they stay plain text (a link would 404).
2000        let commit = if p.build_dirty {
2001            format!("{commit_short}*")
2002        } else {
2003            format!(
2004                "[{commit_short}]({}/commit/{})",
2005                env!("CARGO_PKG_REPOSITORY"),
2006                p.build_commit
2007            )
2008        };
2009        let virtio = match &p.deps.virtio_sha256 {
2010            Some(sha) => format!(
2011                "[{}]({})",
2012                sha.chars().take(7).collect::<String>(),
2013                release_tag_url(crate::pins::DRIVERS_RELEASE_TAG)
2014            ),
2015            None => p.deps.virtio_iso_name.clone(),
2016        };
2017        entries.push(format!(
2018            "| {} | {} | {} | {} | {} {} | [{}]({}) | [{}]({}) | {} | {} | {} |",
2019            epoch_to_date(r.tested_at_epoch),
2020            p.source_iso.file_name,
2021            p.guest.arch,
2022            p.guest.accel,
2023            p.host.os,
2024            p.host.os_version,
2025            p.deps.qemu_tag,
2026            release_tag_url(&p.deps.qemu_tag),
2027            p.deps.wimlib_tag,
2028            release_tag_url(&p.deps.wimlib_tag),
2029            virtio,
2030            commit,
2031            r.outcome,
2032        ));
2033    }
2034    entries.reverse();
2035    rows.extend(entries);
2036    Ok(rows.join("\n") + "\n")
2037}
2038
2039/// Score one PNG through the k-NN classifier ([`crate::screen_knn`]:
2040/// blurred unit-norm luminance + cosine vs the baked cluster centers).
2041/// OOD triage in one shot — no fixture dir, no snapshot, nothing
2042/// blessed. The verdict names the matched exemplar, so a miss is a
2043/// viewable cause. User-supplied path, so loading is fallible
2044/// (`try_load_rgb_8bit`) — bad input exits nonzero via `anyhow`, never a
2045/// panic out of the fixture loader.
2046pub fn cmd_classify(png: &std::path::Path) -> Result<()> {
2047    use crate::screen_knn::{KNN_TOP_K, KNN_UNCERTAIN_GAP, KnnIndex, bundled_index};
2048    let path = png
2049        .to_str()
2050        .with_context(|| format!("non-UTF8 image path: {}", png.display()))?;
2051    let (rgb, w, h) = crate::screen_knn::try_load_rgb_8bit(path)
2052        .map_err(|e| anyhow::anyhow!("load {path}: {e}"))?;
2053    if rgb.is_empty() || w == 0 {
2054        println!("top-1: Dark gap 1.000 (empty input — nothing captured)");
2055        println!("verdict: COMMITTED (margin holds — narration states the label)");
2056        return Ok(());
2057    }
2058    let index = bundled_index();
2059    let q = KnnIndex::embed_frame(&rgb, w, h);
2060    let (top, gap, matched) = index
2061        .predict(&q, None)
2062        .with_context(|| "empty bundled k-NN index — rebuild artifacts/knn_index.bin")?;
2063    println!("top-1: {top:?} gap {gap:.4} via {matched}");
2064    for (label, cos, name) in index.query(&q, None, KNN_TOP_K) {
2065        let class = crate::screen_knn::BY_INDEX
2066            .iter()
2067            .find(|c| **c as usize == label)
2068            .copied()
2069            .unwrap_or(crate::screen_knn::ScreenClass::Dark);
2070        println!("  {class:?}: {cos:.4} {name}");
2071    }
2072    if gap < KNN_UNCERTAIN_GAP {
2073        println!(
2074            "verdict: UNCERTAIN (gap below {KNN_UNCERTAIN_GAP:.2} — narration hedges, nothing gates)"
2075        );
2076    } else {
2077        println!("verdict: COMMITTED (margin holds — narration states the label)");
2078    }
2079    Ok(())
2080}
2081
2082pub fn cmd_report(a: ReportArgs) -> Result<()> {
2083    let table = render_report(&a.log)?;
2084    match a.readme {
2085        None => print!("{table}"),
2086        Some(readme) => {
2087            let text = std::fs::read_to_string(&readme)?;
2088            let (head, rest) = text
2089                .split_once(REPORT_BEGIN)
2090                .with_context(|| format!("{} has no {REPORT_BEGIN} marker", readme.display()))?;
2091            let (_, tail) = rest
2092                .split_once(REPORT_END)
2093                .with_context(|| format!("{} has no {REPORT_END} marker", readme.display()))?;
2094            let updated = format!("{head}{REPORT_BEGIN}\n{table}{REPORT_END}{tail}");
2095            std::fs::write(&readme, updated)?;
2096            eprintln!("updated {}", readme.display());
2097        }
2098    }
2099    Ok(())
2100}
2101
2102// ---------------------------------------------------------------------------
2103// guest
2104// ---------------------------------------------------------------------------
2105
2106/// Guest verbs (work on any booted machine via SSH). Same verbs the
2107/// install flow uses internally — exposed here for live machines.
2108#[derive(clap::Subcommand)]
2109pub enum GuestOp {
2110    /// Execute one command, print stdout.
2111    Exec {
2112        /// Command line (joined with spaces).
2113        #[arg(last = true)]
2114        cmd: Vec<String>,
2115    },
2116    /// Rotate the guest password (verified by fresh login).
2117    SetPassword {
2118        /// New password (never logged).
2119        new_password: String,
2120    },
2121    /// Set Automatic Repair on/off.
2122    SetRecovery {
2123        /// `true` keeps it, `false` disables it.
2124        #[arg(action = clap::ArgAction::Set, value_parser = clap::value_parser!(bool))]
2125        enabled: bool,
2126    },
2127    /// Set automatic Windows updates on/off.
2128    SetUpdates {
2129        /// `true` enables wuauserv, `false` disables it.
2130        #[arg(action = clap::ArgAction::Set, value_parser = clap::value_parser!(bool))]
2131        enabled: bool,
2132    },
2133    /// Ask the guest whether Setup is finished (READY/BUSY verdict).
2134    Probe,
2135}
2136
2137pub struct GuestArgs {
2138    pub op: GuestOp,
2139    pub ssh_port: u16,
2140    pub username: String,
2141    pub password: String,
2142}
2143
2144pub async fn cmd_guest(a: GuestArgs) -> Result<()> {
2145    use crate::qemu::PROVEN_SSH_HOST;
2146    let host = PROVEN_SSH_HOST;
2147    match a.op {
2148        GuestOp::Exec { cmd } => {
2149            let out =
2150                crate::ssh::ssh_exec(host, a.ssh_port, &a.username, &a.password, &cmd.join(" "))
2151                    .await?;
2152            print!("{out}");
2153        }
2154        GuestOp::SetPassword { new_password } => {
2155            crate::ssh::change_guest_password(
2156                host,
2157                a.ssh_port,
2158                &a.username,
2159                &a.password,
2160                &new_password,
2161            )
2162            .await?;
2163            eprintln!("password rotated (verified by fresh login)");
2164        }
2165        GuestOp::SetRecovery { enabled } => {
2166            crate::ssh::set_recovery_enabled(host, a.ssh_port, &a.username, &a.password, enabled)
2167                .await?;
2168        }
2169        GuestOp::SetUpdates { enabled } => {
2170            crate::ssh::set_auto_updates(host, a.ssh_port, &a.username, &a.password, enabled)
2171                .await?;
2172        }
2173        GuestOp::Probe => {
2174            let progress =
2175                crate::ssh::probe_setup_done(host, a.ssh_port, &a.username, &a.password).await?;
2176            eprintln!("{}", if progress.is_ready() { "READY" } else { "BUSY" });
2177        }
2178    }
2179    Ok(())
2180}
2181
2182// ---------------------------------------------------------------------------
2183// overlay / stop
2184// ---------------------------------------------------------------------------
2185
2186pub async fn cmd_overlay(
2187    base: Option<PathBuf>,
2188    overlay: PathBuf,
2189    qemu_dir: Option<PathBuf>,
2190) -> Result<()> {
2191    // Base defaults to the disk `run` boots — overlays are deltas over it.
2192    let base = match base {
2193        Some(b) => b,
2194        None => default_vm_dir()?.join(crate::paths::DISK_IMAGE),
2195    };
2196    if !base.is_file() {
2197        anyhow::bail!("base {} missing (run `install` first)", base.display());
2198    }
2199    let img = qemu_dir
2200        .map(|d| {
2201            d.join(crate::paths::PORTABLE_BIN_DIR)
2202                .join(crate::paths::QEMU_IMG_NAME)
2203        })
2204        .unwrap_or_else(|| PathBuf::from(crate::paths::QEMU_IMG_NAME));
2205    DiskManager::create_overlay(&img, &base, &overlay).await?;
2206    eprintln!("overlay {} over {}", overlay.display(), base.display());
2207    Ok(())
2208}
2209
2210pub async fn cmd_stop(vm_dir: Option<PathBuf>, qmp_sock: Option<String>) -> Result<()> {
2211    use crate::qmp::QmpClient;
2212    let vm_dir = match vm_dir {
2213        Some(d) => d,
2214        None => default_vm_dir()?,
2215    };
2216    // Default QMP endpoint lives next to the disk (never /tmp); explicit
2217    // --qmp-sock overrides (URLs/paths as given).
2218    let qmp_sock = qmp_sock.unwrap_or_else(|| vm_endpoint(&vm_dir, QMP_SOCK_NAME));
2219    // Best-effort pid lookup for messaging (kill fallback below).
2220    let pid = std::fs::read_to_string(vm_dir.join(crate::paths::QEMU_PIDFILE))
2221        .ok()
2222        .map(|s| s.trim().to_string())
2223        .filter(|s| !s.is_empty());
2224    if !qmp_alive(&qmp_sock).await {
2225        // Not reachable: drop a stale pidfile if present, then report.
2226        let pidfile = vm_dir.join(crate::paths::QEMU_PIDFILE);
2227        if pidfile.exists() {
2228            let _ = std::fs::remove_file(&pidfile);
2229        }
2230        match pid {
2231            Some(p) => println!(
2232                "no QMP on {qmp_sock}: VM is unreachable (wedged or already gone). If `ps -p {p}` is alive, `kill {p}` to clean up."
2233            ),
2234            None => println!("no running VM on {qmp_sock}"),
2235        }
2236        return Ok(());
2237    }
2238    let mut qmp = QmpClient::connect(&qmp_sock).await?;
2239    qmp.quit().await?;
2240    // Drop the session before probing: single-client transports refuse a
2241    // probe while our own session is open (false "dead").
2242    drop(qmp);
2243    for _ in 0..timeouts::QMP_QUIT_POLL_COUNT {
2244        if !qmp_alive(&qmp_sock).await {
2245            break;
2246        }
2247        tokio::time::sleep(timeouts::QMP_QUIT_POLL_INTERVAL).await;
2248    }
2249    let pidfile = vm_dir.join(crate::paths::QEMU_PIDFILE);
2250    let _ = std::fs::remove_file(&pidfile);
2251    if qmp_alive(&qmp_sock).await {
2252        anyhow::bail!(
2253            "VM ignored QMP quit; kill it manually (see {} before cleanup)",
2254            crate::paths::QEMU_PIDFILE
2255        );
2256    }
2257    eprintln!("stopped");
2258    Ok(())
2259}
2260
2261// ---------------------------------------------------------------------------
2262// downloader-backed commands
2263// ---------------------------------------------------------------------------
2264
2265/// Download one file into place (skip when cached and valid). Shared by
2266/// `fetch` and `setup` so both print the same `cached|downloaded` lines.
2267/// `force` re-downloads even a valid cache entry (for URL-rotated
2268/// artifacts like the Eval ISO); `setup` always passes false.
2269#[cfg(feature = "downloader")]
2270pub async fn fetch_one(
2271    url: &str,
2272    dest: &std::path::Path,
2273    hash: Option<&str>,
2274    force: bool,
2275) -> Result<()> {
2276    use crate::downloader;
2277    let name = dest
2278        .file_name()
2279        .map(|n| n.to_string_lossy().into_owned())
2280        .unwrap_or_else(|| dest.display().to_string());
2281    let is_iso = name.ends_with(".iso");
2282    // A previously cached file may be a bot-check HTML stub
2283    // (HTTP 200 with no ISO magic) — drop it so it re-downloads
2284    // instead of poisoning this run and hanging EDK2 at boot.
2285    if is_iso && dest.exists() && downloader::validate_iso_image(dest).is_err() {
2286        eprintln!(
2287            "cached {} is not an ISO image; re-downloading",
2288            dest.display()
2289        );
2290        std::fs::remove_file(dest)?;
2291    }
2292    match downloader::download_if_missing(url, dest, hash, force).await? {
2293        downloader::DownloadStatus::Cached { path } => {
2294            if is_iso {
2295                downloader::validate_iso_image(&path)?;
2296            }
2297            eprintln!("cached {}", path.display())
2298        }
2299        downloader::DownloadStatus::Downloaded { path, sha256 } => {
2300            if is_iso && let Err(e) = downloader::validate_iso_image(&path) {
2301                let _ = std::fs::remove_file(&path);
2302                return Err(e)
2303                    .with_context(|| format!("downloaded {} failed validation", path.display()));
2304            }
2305            eprintln!("downloaded {} (sha256 {sha256})", path.display())
2306        }
2307    }
2308    Ok(())
2309}
2310
2311#[cfg(feature = "downloader")]
2312pub async fn cmd_fetch_qemu(
2313    qemu_tag: Option<String>,
2314    dir: Option<PathBuf>,
2315    allow_unverified: bool,
2316) -> Result<()> {
2317    let q = crate::qemu_portable::ensure(dir, qemu_tag, allow_unverified).await?;
2318    eprintln!("portable QEMU {} at {}", q.version, q.root.display());
2319    for bin in q.system_binaries() {
2320        eprintln!("  system: {}", bin.display());
2321    }
2322    eprintln!("  img:    {}", q.qemu_img().display());
2323    Ok(())
2324}
2325
2326#[cfg(feature = "downloader")]
2327pub struct FetchArgs {
2328    pub win_iso_url: Option<String>,
2329    pub win_iso_sha256: Option<String>,
2330    pub virtio_iso_url: Option<String>,
2331    pub dir: Option<PathBuf>,
2332    pub virtio_sha256: Option<String>,
2333    pub openssh: bool,
2334    pub arch: Option<Architecture>,
2335    /// Re-download even valid cache entries (for URL-rotated artifacts
2336    /// like the Eval ISO, whose slot name can't see upstream changes).
2337    pub force: bool,
2338}
2339
2340#[cfg(feature = "downloader")]
2341pub async fn cmd_fetch(a: FetchArgs) -> Result<()> {
2342    use crate::downloader;
2343    let dir = match a.dir {
2344        Some(d) => d,
2345        None => downloader::iso_cache_dir()?,
2346    };
2347    // Explicit flag wins; else a pre-fetched time-limited link via env.
2348    // No page scraper: EvalCenter links require the interactive form.
2349    // Absent entirely: skip the Eval ISO (e.g. you already have one
2350    // on disk and only need virtio-win.iso).
2351    let mut items: Vec<(String, &str, Option<String>)> = Vec::new();
2352    match downloader::resolve_eval_iso_url(a.win_iso_url) {
2353        Ok(u) => {
2354            // Explicit flag wins, else $WIN11_EVAL_ISO_SHA256; absent = TLS only.
2355            let eval_hash = a
2356                .win_iso_sha256
2357                .or_else(|| std::env::var("WIN11_EVAL_ISO_SHA256").ok());
2358            items.push((u, crate::paths::EVAL_ISO_NAME, eval_hash))
2359        }
2360        Err(e) => eprintln!("skipping Windows ISO: {e:#}"),
2361    }
2362    // virtio-win.iso: explicit URL wins, else our vendored release
2363    // asset (hash from the release sidecar). No fallback: a failed
2364    // lookup means the pin is wrong or GitHub is unreachable, and
2365    // silently substituting unpinned upstream bytes would hide either.
2366    let (virtio_url, virtio_hash) = match a.virtio_iso_url {
2367        Some(u) => {
2368            if a.virtio_sha256.is_none() {
2369                tracing::warn!(
2370                    "custom --virtio-iso-url without --virtio-sha256: virtio-win.iso will be TLS-only (no hash verification)"
2371                );
2372            }
2373            (u, a.virtio_sha256)
2374        }
2375        None => {
2376            let (u, h) = downloader::virtio_release_info().await.with_context(|| {
2377                format!(
2378                    "virtio release lookup failed for {} (check the pin and GitHub API rate limits)",
2379                    downloader::VIRTIO_RELEASE_TAG
2380                )
2381            })?;
2382            (u, a.virtio_sha256.or(Some(h)))
2383        }
2384    };
2385    items.push((virtio_url, crate::paths::VIRTIO_ISO, virtio_hash));
2386    if a.openssh {
2387        let arch = resolve_arch(a.arch);
2388        items.push((
2389            downloader::openssh_zip_url(arch),
2390            arch.openssh_zip_name(),
2391            Some(arch.openssh_sha256().to_string()),
2392        ));
2393    }
2394    for (url, name, hash) in items {
2395        fetch_one(&url, &dir.join(name), hash.as_deref(), a.force).await?;
2396    }
2397    Ok(())
2398}
2399
2400#[cfg(feature = "downloader")]
2401pub async fn cmd_setup(virtio_iso_url: Option<String>, arch: Option<Architecture>) -> Result<()> {
2402    use crate::downloader;
2403    let arch = resolve_arch(arch);
2404    let q = crate::qemu_portable::ensure(None, None, false).await?;
2405    eprintln!("portable QEMU {} at {}", q.version, q.root.display());
2406    let w = crate::qemu_portable::ensure_wimlib(None, None, false).await?;
2407    eprintln!("portable wimlib {} at {}", w.version, w.root.display());
2408    let dir = downloader::iso_cache_dir()?;
2409    let (virtio_url, virtio_hash) = match virtio_iso_url {
2410        Some(u) => {
2411            tracing::warn!(
2412                "custom virtio ISO URL without --virtio-sha256: virtio-win.iso will be TLS-only (no hash verification)"
2413            );
2414            (u, None)
2415        }
2416        None => {
2417            let (u, h) = downloader::virtio_release_info().await?;
2418            (u, Some(h))
2419        }
2420    };
2421    fetch_one(
2422        &virtio_url,
2423        &dir.join(crate::paths::VIRTIO_ISO),
2424        virtio_hash.as_deref(),
2425        false,
2426    )
2427    .await?;
2428    fetch_one(
2429        &downloader::openssh_zip_url(arch),
2430        &dir.join(arch.openssh_zip_name()),
2431        Some(arch.openssh_sha256()),
2432        false,
2433    )
2434    .await?;
2435    eprintln!("setup complete (Windows ISO still yours: pass --win-iso to build-media)");
2436    Ok(())
2437}
2438
2439#[cfg(feature = "downloader")]
2440pub async fn cmd_fetch_wimlib(
2441    wimlib_tag: Option<String>,
2442    dir: Option<PathBuf>,
2443    allow_unverified: bool,
2444) -> Result<()> {
2445    let w = crate::qemu_portable::ensure_wimlib(dir, wimlib_tag, allow_unverified).await?;
2446    eprintln!("portable wimlib {} at {}", w.version, w.root.display());
2447    eprintln!("  bin: {}", w.wimlib_bin().display());
2448    Ok(())
2449}
2450
2451/// Verify every pinned external artifact WITHOUT downloading archives or
2452/// installing anything (CI-friendly: KBs of metadata, plus two ~5 MB OpenSSH
2453/// zips). Checks, per artifact:
2454/// 1. the release asset exists (availability for that environment), and
2455/// 2. its hash matches the code-pinned expectation.
2456///
2457/// Hash-only sources are preferred wherever they exist (`SHA256SUMS.txt`,
2458/// virtio `.sha256` sidecar); only OpenSSH (no upstream sums) downloads the
2459/// payload itself. Prints one line per check; returns an error summarizing
2460/// all failures so a single CI run reports everything at once.
2461#[cfg(feature = "downloader")]
2462pub async fn cmd_verify_pins() -> Result<()> {
2463    use crate::downloader;
2464    use crate::qemu_portable::{parse_sums, release_by_tag};
2465    let mut failures: Vec<String> = Vec::new();
2466    let ok = |label: &str| eprintln!("pin ok: {label}");
2467
2468    // Portable QEMU + wimlib: all three platform markers, sums hash vs pin.
2469    for (product, tag, prefix, is_wimlib) in [
2470        (
2471            "qemu",
2472            crate::pins::QEMU_PORTABLE_TAG,
2473            crate::paths::QEMU_ASSET_PREFIX,
2474            false,
2475        ),
2476        (
2477            "wimlib",
2478            crate::pins::WIMLIB_PORTABLE_TAG,
2479            crate::paths::WIMLIB_ASSET_PREFIX,
2480            true,
2481        ),
2482    ] {
2483        let assets = match release_by_tag(tag).await {
2484            Ok(a) => a,
2485            Err(e) => {
2486                failures.push(format!("{product} {tag}: release lookup failed: {e:#}"));
2487                continue;
2488            }
2489        };
2490        let sums_url = match assets
2491            .iter()
2492            .find(|(n, _)| n == crate::paths::SHA256SUMS_FILE)
2493            .map(|(_, u)| u.clone())
2494        {
2495            Some(u) => u,
2496            None => {
2497                failures.push(format!(
2498                    "{product} {tag}: no {}",
2499                    crate::paths::SHA256SUMS_FILE
2500                ));
2501                continue;
2502            }
2503        };
2504        let sums_body = match downloader::fetch_text(&sums_url).await {
2505            Ok(b) => b,
2506            Err(e) => {
2507                failures.push(format!("{product} {tag}: sums fetch failed: {e:#}"));
2508                continue;
2509            }
2510        };
2511        for marker in [
2512            crate::paths::MARKER_MACOS_ARM64,
2513            crate::paths::MARKER_LINUX_X86_64,
2514            crate::paths::MARKER_LINUX_AARCH64,
2515        ] {
2516            let label = format!("{product} {tag} [{marker}]");
2517            let Some(asset) = assets
2518                .iter()
2519                .find(|(n, _)| n.contains(marker) && n.starts_with(prefix))
2520                .map(|(n, _)| n.clone())
2521            else {
2522                failures.push(format!("{label}: no release asset"));
2523                continue;
2524            };
2525            let Some(expected) = (if is_wimlib {
2526                crate::qemu_portable::pinned_wimlib_sha256(marker)
2527            } else {
2528                crate::qemu_portable::pinned_qemu_sha256(marker)
2529            }) else {
2530                failures.push(format!("{label}: no pinned hash for marker"));
2531                continue;
2532            };
2533            match parse_sums(&sums_body, &asset) {
2534                Some(h) if h.eq_ignore_ascii_case(expected) => ok(&label),
2535                Some(h) => failures.push(format!(
2536                    "{label}: sums hash {h} != pinned {expected} (stale pin? asset rotated?)"
2537                )),
2538                None => failures.push(format!(
2539                    "{label}: {asset} missing from {}",
2540                    crate::paths::SHA256SUMS_FILE
2541                )),
2542            }
2543        }
2544    }
2545
2546    // virtio-win.iso: sidecar must be a valid 64-hex digest AND match the
2547    // code pin (closes the TOFU gap: a forged sidecar+ISO pair fails here).
2548    match downloader::virtio_release_info().await {
2549        Ok((url, sha)) => {
2550            ok(&format!("virtio-win.iso [{sha}] ({url})"));
2551        }
2552        Err(e) => failures.push(format!("virtio-win.iso: release lookup failed: {e:#}")),
2553    }
2554    // OpenSSH: no upstream sums — download both zips (~5 MB) to a tempdir
2555    // and hash against the arch-strict pins.
2556    let tmp = tempfile::tempdir().context("verify-pins tempdir")?;
2557    for arch in [crate::Architecture::Amd64, crate::Architecture::Arm64] {
2558        let label = format!("{} ({})", arch.openssh_zip_name(), arch.as_xml_str());
2559        let dest = tmp.path().join(arch.openssh_zip_name());
2560        match downloader::download(&downloader::openssh_zip_url(arch), &dest).await {
2561            Ok(actual) => {
2562                let _ = std::fs::remove_file(&dest);
2563                if actual.eq_ignore_ascii_case(arch.openssh_sha256()) {
2564                    ok(&label);
2565                } else {
2566                    failures.push(format!(
2567                        "{label}: downloaded hash {actual} != pinned {}",
2568                        arch.openssh_sha256()
2569                    ));
2570                }
2571            }
2572            Err(e) => failures.push(format!("{label}: download failed: {e:#}")),
2573        }
2574    }
2575
2576    if failures.is_empty() {
2577        eprintln!("verify-pins: all pinned artifacts available and hash-matched");
2578        Ok(())
2579    } else {
2580        for f in &failures {
2581            eprintln!("pin FAIL: {f}");
2582        }
2583        anyhow::bail!("verify-pins: {} check(s) failed", failures.len())
2584    }
2585}
2586
2587// ---------------------------------------------------------------------------
2588// VM helpers (shared by run / install)
2589// ---------------------------------------------------------------------------
2590
2591/// Last meaningful line of the guest serial log (EDK2/Windows boot chatter).
2592/// Shown in the boot-wait ticker so a slow boot narrates itself instead of
2593/// printing bare elapsed seconds (observed live: 450 s of silence during a
2594/// recovery boot). Empty when the log has nothing yet.
2595///
2596/// Filters EDK2 memory-map/TPM noise (`ConvertPages`, `Tcg2`) that repeats
2597/// for minutes and says nothing — without this the ticker quotes firmware
2598/// trivia as status (observed live).
2599fn last_serial_line(serial_log: &str) -> String {
2600    /// Substrings marking firmware noise, never boot progress.
2601    const NOISE: &[&str] = &[
2602        "ConvertPages: failed to find range",
2603        "Tpm2SubmitCommand",
2604        "Tcg2",
2605        "Tpm2GetCapability",
2606    ];
2607    let text = std::fs::read_to_string(serial_log).unwrap_or_default();
2608    // Serial carries ANSI escapes and \r; take the last line with text
2609    // (reverse scan stops at the first hit instead of walking the log).
2610    fn stripped(line: &str, noise: &[&str]) -> Option<String> {
2611        // Strip common ANSI CSI sequences (best-effort, no regex dep).
2612        let mut s = String::with_capacity(line.len());
2613        let mut chars = line.chars().peekable();
2614        while let Some(c) = chars.next() {
2615            if c == '\x1b' && chars.peek() == Some(&'[') {
2616                for c2 in chars.by_ref() {
2617                    if c2.is_ascii_alphabetic() {
2618                        break;
2619                    }
2620                }
2621            } else {
2622                s.push(c);
2623            }
2624        }
2625        let s = s.trim().to_string();
2626        (!s.is_empty() && !noise.iter().any(|n| s.contains(n))).then_some(s)
2627    }
2628    let line = text
2629        .replace('\r', "\n")
2630        .lines()
2631        .rev()
2632        .filter_map(|l| stripped(l, NOISE))
2633        .next()
2634        .unwrap_or_default();
2635    // Cap length: some lines are progress bars several KB wide.
2636    if line.len() > 100 {
2637        format!("{}...", &line[..100])
2638    } else {
2639        line
2640    }
2641}
2642/// Fatal boot-failure patterns in the guest serial log (EDK2/Windows).
2643/// Patterns live in `templates/boot-fatal-patterns.txt` (one substring per
2644/// line), not in code — new dead screens are learned by editing a text
2645/// file, not shipping a release. Conservative by design: only signatures
2646/// that never appear in a healthy boot. A hit means VNC would show a dead
2647/// screen — fail fast with the evidence instead of polling SSH.
2648fn fatal_boot_patterns() -> Vec<String> {
2649    const TPL: &str = include_str!("../templates/boot-fatal-patterns.txt");
2650    TPL.lines()
2651        .map(str::trim)
2652        .filter(|l| !l.is_empty() && !l.starts_with('#'))
2653        .map(str::to_string)
2654        .collect()
2655}
2656
2657/// Firmware boot handoffs in the serial log: OVMF prints one
2658/// `BdsDxe: starting <entry>` line per boot attempt it launches (failed
2659/// candidates log `failed to load` instead), so the count rises on every
2660/// guest reboot — the below-screenshot "did it bounce?" signal. QEMU's
2661/// file chardev truncates at VM start, so it counts this session only.
2662/// Caveat: a boot entry whose `Start()` returns without loading can add a
2663/// line without a full reboot — the trend (flat vs rising) is the signal.
2664fn boot_count(serial_log: &str) -> u64 {
2665    std::fs::read_to_string(serial_log)
2666        .unwrap_or_default()
2667        .matches("BdsDxe: starting")
2668        .count() as u64
2669}
2670
2671/// One-shot narration for a rising [`boot_count`]: `None` while flat, a
2672/// line for the first boot, a reboot line after it. Count regressions
2673/// (a truncated log) stay silent — never claim a reboot that didn't show.
2674fn boot_note(old: u64, new: u64) -> Option<String> {
2675    (new > old).then(|| {
2676        if new == 1 {
2677            "guest booted (first firmware boot)".to_string()
2678        } else {
2679            format!("guest rebooted (firmware boot #{new} seen on serial)")
2680        }
2681    })
2682}
2683
2684/// Fatal serial signature check (see [`fatal_boot_patterns`]): returns the
2685/// cause only — `cmd_run`'s failure arms append the evidence block (frame
2686/// path + serial tail + VNC) via [`boot_failure_report`].
2687fn check_boot_failure(serial_log: &str) -> Result<()> {
2688    let fatal = fatal_boot_patterns();
2689    let text = std::fs::read_to_string(serial_log).unwrap_or_default();
2690    // Only the tail matters (log persists across runs); keep the last 8 KB.
2691    let tail = if text.len() > 8192 {
2692        &text[text.len() - 8192..]
2693    } else {
2694        &text
2695    };
2696    for pat in &fatal {
2697        if tail.contains(pat) {
2698            anyhow::bail!("guest failed to boot (serial shows {pat:?})");
2699        }
2700    }
2701    Ok(())
2702}
2703
2704/// Guest-activity ledger: the sole consumer of `info blockstats` plus
2705/// host-side disk-size samples. Answers "is the guest doing anything" so
2706/// the warning policy can tell a slow install (moving) from a parked one
2707/// (flat). Sample on every tick; judge on horizons — qcow2 grows stepwise,
2708/// so per-second diffs false-report static.
2709struct ActivityMonitor {
2710    last_total: u64,
2711    last_change: std::time::Instant,
2712    warned: bool,
2713    disk_start: Option<u64>,
2714    disk_last: u64,
2715    disk_last_change: std::time::Instant,
2716    last_sample: Option<std::time::Instant>,
2717    /// I/O bytes/s, exponential average over [`Self::EMA_WINDOW_SECS`].
2718    pub(crate) io_ema_bps: f64,
2719    /// Disk-growth bytes/s, same window.
2720    pub(crate) growth_ema_bps: f64,
2721}
2722
2723impl ActivityMonitor {
2724    /// EMA window in seconds: bursts read as rates, not spikes.
2725    const EMA_WINDOW_SECS: f64 = 300.0;
2726
2727    fn new() -> Self {
2728        let now = std::time::Instant::now();
2729        Self {
2730            last_total: 0,
2731            last_change: now,
2732            warned: false,
2733            disk_start: None,
2734            disk_last: 0,
2735            disk_last_change: now,
2736            last_sample: None,
2737            io_ema_bps: 0.0,
2738            growth_ema_bps: 0.0,
2739        }
2740    }
2741
2742    /// Sum all `rd_bytes`/`wr_bytes` in HMP `info blockstats` output.
2743    /// Best-effort parse (unparseable → None, never fail the wait on it).
2744    fn parse_total(text: &str) -> Option<u64> {
2745        let mut total = 0u64;
2746        let mut found = false;
2747        for key in ["rd_bytes=", "wr_bytes="] {
2748            for part in text.split(key).skip(1) {
2749                let digits: String = part.chars().take_while(|c| c.is_ascii_digit()).collect();
2750                if let Ok(n) = digits.parse::<u64>() {
2751                    total = total.saturating_add(n);
2752                    found = true;
2753                }
2754            }
2755        }
2756        found.then_some(total)
2757    }
2758
2759    /// One EMA step, pure: `prev` toward `inst` over `dt_secs` in a
2760    /// `window_secs` horizon. Unit-testable without clocks.
2761    fn ema_step(prev: f64, inst: f64, dt_secs: f64, window_secs: f64) -> f64 {
2762        if dt_secs <= 0.0 {
2763            return prev;
2764        }
2765        let alpha = (dt_secs / window_secs).min(1.0);
2766        prev + alpha * (inst - prev)
2767    }
2768
2769    /// Feed one tick: monitor counters plus host-side disk size. Every
2770    /// part best-effort — an unreachable monitor or stat failure skips
2771    /// that signal, never the wait. `None` disk skips growth tracking
2772    /// (blockstats still feed the stall watchdog).
2773    async fn sample(&mut self, mon: &crate::ipc::Monitor, disk: Option<&Path>) {
2774        let now = std::time::Instant::now();
2775        let dt = self
2776            .last_sample
2777            .map(|t| now.duration_since(t).as_secs_f64())
2778            .unwrap_or(0.0);
2779        self.last_sample = Some(now);
2780        let text = mon.command("info blockstats").await.unwrap_or_default();
2781        if let Some(total) = Self::parse_total(&text) {
2782            // Unconditional on movement: a flat interval feeds inst 0.0 so
2783            // the average decays toward zero instead of freezing at its
2784            // last active rate for hours on an idle guest.
2785            if dt > 0.0 {
2786                let inst = total.saturating_sub(self.last_total) as f64 / dt;
2787                self.io_ema_bps = Self::ema_step(self.io_ema_bps, inst, dt, Self::EMA_WINDOW_SECS);
2788            }
2789            if total != self.last_total {
2790                self.last_total = total;
2791                self.last_change = now;
2792                self.warned = false;
2793            }
2794        }
2795        if let Some(disk) = disk
2796            && let Ok(size) = std::fs::metadata(disk).map(|m| m.len())
2797        {
2798            if self.disk_start.is_none() {
2799                // First sample arms the baseline without tripping motion:
2800                // a pre-existing disk is not growth.
2801                self.disk_start = Some(size);
2802                self.disk_last = size;
2803                self.disk_last_change = now;
2804            } else if dt > 0.0 {
2805                let inst = size.saturating_sub(self.disk_last) as f64 / dt;
2806                self.growth_ema_bps =
2807                    Self::ema_step(self.growth_ema_bps, inst, dt, Self::EMA_WINDOW_SECS);
2808                // Growth timer advances only on real growth; the average
2809                // still decays through the zero inst above.
2810                if size != self.disk_last {
2811                    self.disk_last_change = now;
2812                }
2813                self.disk_last = size;
2814            }
2815        }
2816    }
2817
2818    /// Seconds since block I/O last moved.
2819    fn idle_secs(&self) -> u64 {
2820        self.last_change.elapsed().as_secs()
2821    }
2822
2823    /// Seconds since the disk image last grew.
2824    fn disk_idle_secs(&self) -> u64 {
2825        self.disk_last_change.elapsed().as_secs()
2826    }
2827
2828    /// Bytes the disk image grew since the first sample (saturating).
2829    fn growth_since_start(&self) -> u64 {
2830        self.disk_start
2831            .map(|s| self.disk_last.saturating_sub(s))
2832            .unwrap_or(0)
2833    }
2834
2835    /// Moving right now: any I/O inside the warn horizon.
2836    fn is_moving(&self) -> bool {
2837        self.idle_secs() < timeouts::IDLE_WARN_SECS
2838    }
2839
2840    /// Stall watchdog, conditioned on screen state: frozen disk I/O during
2841    /// valid progress (Setup applying, OOBE, boot art, idle desktop) is a
2842    /// slow host, never a stuck guest — progress answers only to the
2843    /// operator. The bail fires solely on the conjunction: a non-progress
2844    /// screen (error states, Dark, FlatField) AND ceased block I/O AND a
2845    /// disk that stopped growing. `None` state (no frame yet) takes the
2846    /// strict path: nothing rendered is itself evidence of stuck.
2847    /// `fatal` decides the teeth: the run boot wait bails (a dead boot
2848    /// has its own SSH deadline anyway), the install path only ever warns
2849    /// — nothing but the operator halts an install. `Err` on bail so
2850    /// fatal callers `?` straight out.
2851    fn check_stall(&mut self, state: Option<ScreenState>, fatal: bool) -> Result<()> {
2852        let progress = matches!(
2853            state,
2854            Some(
2855                ScreenState::InstallerStep
2856                    | ScreenState::OobeStep
2857                    | ScreenState::FirmwareBoot
2858                    | ScreenState::Lockscreen
2859            )
2860        );
2861        if progress {
2862            // Slow host, not stuck guest: reset the warn latch so a later
2863            // genuine stall still warns, and return without judging.
2864            self.warned = false;
2865            return Ok(());
2866        }
2867        let idle = self.idle_secs();
2868        let disk_idle = self.disk_idle_secs();
2869        if idle >= timeouts::IDLE_BAIL_SECS && disk_idle >= timeouts::IDLE_BAIL_SECS {
2870            if !fatal {
2871                // Install path: say so loudly, keep waiting. Only the
2872                // operator halts an install. Warn every time past bail
2873                // (not warn-once): a stall that persists for hours should
2874                // stay visible, and nothing else will say it.
2875                eprintln!(
2876                    "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)"
2877                );
2878                return Ok(());
2879            }
2880            // Cause only; failure arms append frame + serial + VNC.
2881            anyhow::bail!(
2882                "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)"
2883            );
2884        }
2885        if idle >= timeouts::IDLE_WARN_SECS && !self.warned {
2886            self.warned = true;
2887            // Never name an input screen without seeing one: the SSH-probe
2888            // loop calls with no frame (None), while the sampler task may
2889            // concurrently report progress. A blind loop claiming a parked
2890            // input screen next to an installer-progress line is the exact
2891            // contradiction that erodes trust in every other warning.
2892            if state.is_none() {
2893                eprintln!("warning: no disk I/O for {idle}s and no SSH banner yet — still waiting");
2894            } else {
2895                eprintln!(
2896                    "warning: no disk I/O for {idle}s and no SSH yet — guest may be stuck at an input screen"
2897                );
2898            }
2899        }
2900        Ok(())
2901    }
2902}
2903
2904/// Time-lapse dir name under the VM dir, and frame filename prefix.
2905/// Single source: screenshots_dir() builds the path, take_screenshot names files.
2906pub const SCREENSHOTS_DIR: &str = "screenshots";
2907
2908fn screenshots_dir(vm_dir: &Path) -> PathBuf {
2909    vm_dir.join(SCREENSHOTS_DIR)
2910}
2911
2912/// Monitor command setting the VNC password. Single source so the run
2913/// and install paths cannot drift (or typo) apart again.
2914fn vnc_password_command() -> String {
2915    format!("change vnc password {PROVEN_VNC_PASSWORD}")
2916}
2917
2918/// Evidence block for a failed boot wait: final frame (path + screen
2919/// classification), last serial line, activity evidence, VNC coordinates.
2920/// Pure formatter so the layout is unit-testable; [`boot_failure_report`]
2921/// gathers the parts.
2922fn format_failure_report(
2923    frame: Option<(PathBuf, ScreenState)>,
2924    serial: &str,
2925    boots: u64,
2926    activity: Option<(u64, u64)>,
2927    vnc: &Option<String>,
2928) -> String {
2929    let mut out = match frame {
2930        Some((p, s)) => format!("boot diagnosis: {s} — {}", p.display()),
2931        None => "boot diagnosis: no screenshot could be captured".to_string(),
2932    };
2933    if !serial.is_empty() {
2934        out.push_str(&format!("\n  last serial: {serial}"));
2935    }
2936    out.push_str(&format!("\n  guest boots seen: {boots}"));
2937    if let Some((idle_secs, growth)) = activity {
2938        out.push_str(&format!(
2939            "\n  guest activity: no I/O for {idle_secs}s, disk +{}",
2940            fmt_bytes(growth)
2941        ));
2942    }
2943    if let Some(u) = vnc {
2944        out.push_str(&format!("\n  vnc: {u} (password {PROVEN_VNC_PASSWORD})"));
2945    }
2946    out
2947}
2948
2949/// Gather the evidence for [`format_failure_report`]: one final frame off
2950/// the live monitor (the serial is silent through a Windows boot, so the
2951/// screen is the primary witness), the last meaningful serial line, one
2952/// activity sample, and the caller's VNC coordinates. Every part is
2953/// best-effort — a missing piece is stated, never invented.
2954async fn boot_failure_report(
2955    mon: &crate::ipc::Monitor,
2956    serial_log: &str,
2957    shots_dir: &Path,
2958    vnc: &Option<String>,
2959) -> String {
2960    let frame = take_screenshot(mon, shots_dir)
2961        .await
2962        .map(|(p, s, _)| (p, s));
2963    let serial = last_serial_line(serial_log);
2964    let mut activity_mon = ActivityMonitor::new();
2965    let disk = shots_dir.parent().map(|d| d.join(crate::paths::DISK_IMAGE));
2966    activity_mon.sample(mon, disk.as_deref()).await;
2967    let activity = Some((activity_mon.idle_secs(), activity_mon.growth_since_start()));
2968    format_failure_report(frame, &serial, boot_count(serial_log), activity, vnc)
2969}
2970
2971/// Background time-lapse: ticks on the profile until aborted. Returns the
2972/// join handle (`None` when every cadence is off); callers `.abort()` it
2973/// when the wait ends.
2974fn spawn_sampler(
2975    mon: std::sync::Arc<crate::ipc::Monitor>,
2976    screenshots_dir: PathBuf,
2977    disk: PathBuf,
2978    profile: SamplingProfile,
2979    label: &'static str,
2980) -> Option<tokio::task::JoinHandle<()>> {
2981    let tick = profile.tick()?;
2982    Some(tokio::spawn(async move {
2983        // First frame immediately (proves the display is alive early),
2984        // then on cadence. Numbered, basename-only (the dir was announced
2985        // once above), so the log reads as progress toward the SSH answer.
2986        let mut sampler = ScreenSampler::new(mon, screenshots_dir);
2987        let mut activity = ActivityMonitor::new();
2988        sampler.poll(&profile).await;
2989        report_sample(label, &sampler, &activity);
2990        let mut ticker = tokio::time::interval(tick);
2991        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
2992        ticker.tick().await; // skip the immediate tick
2993        loop {
2994            ticker.tick().await;
2995            activity.sample(&sampler.mon, Some(disk.as_path())).await;
2996            sampler.poll(&profile).await;
2997            // Stall check after the fresh classification: frozen I/O
2998            // during valid progress is a slow host, never a stuck guest.
2999            // Warn-only by construction (fatal=false never errs): no
3000            // screen, state, or activity reading exits this loop early.
3001            // The task ends solely on abort (victory) or cancellation.
3002            activity.check_stall(sampler.state(), false).ok();
3003            report_sample(label, &sampler, &activity);
3004        }
3005    }))
3006}
3007
3008/// One scrollback-safe status line per tick: the whole instrument panel.
3009/// Nothing prints for [`SampleOutcome::Skipped`].
3010fn report_sample(label: &str, sampler: &ScreenSampler, activity: &ActivityMonitor) {
3011    let (noun, n, state, margin, file) = match &sampler.last_outcome {
3012        SampleOutcome::Saved(p, s, m) => (
3013            "screenshot",
3014            sampler.shot_n,
3015            *s,
3016            *m,
3017            p.file_name()
3018                .unwrap_or_default()
3019                .to_string_lossy()
3020                .into_owned(),
3021        ),
3022        // Status lines carry wall-clock runtime, not a counter: on a
3023        // 3-hour install "status 412" says nothing, "2h41m" says where.
3024        SampleOutcome::Classified(s, m) => (
3025            "status",
3026            sampler.started.elapsed().as_secs(),
3027            *s,
3028            *m,
3029            String::new(),
3030        ),
3031        SampleOutcome::Skipped => return,
3032    };
3033    // Error reads warn only under the activity conjunction (flat guest);
3034    // a moving guest with an error read is a transient misread or live
3035    // recovery, and logs as observation, never alarm.
3036    let warn = if is_error_state(state) && !activity.is_moving() {
3037        "WARNING: "
3038    } else {
3039        ""
3040    };
3041    let file_part = if file.is_empty() {
3042        String::new()
3043    } else {
3044        format!("{file} ")
3045    };
3046    // Disk growth reads with its own age: a disk that stopped growing
3047    // long ago while I/O still trickles is a different shape than both
3048    // moving together.
3049    let disk_part = if activity.disk_idle_secs() >= timeouts::IDLE_WARN_SECS {
3050        format!(
3051            "disk +{} (static {})",
3052            fmt_bytes(activity.growth_since_start()),
3053            fmt_secs(activity.disk_idle_secs())
3054        )
3055    } else {
3056        format!("disk +{}", fmt_bytes(activity.growth_since_start()))
3057    };
3058    eprintln!(
3059        "{warn}{label} {noun} {}: {file_part}{} (phase {}, static {}, io {}/s avg, {disk_part}, io-idle {})",
3060        if noun == "status" {
3061            fmt_secs(n)
3062        } else {
3063            n.to_string()
3064        },
3065        describe(state, margin),
3066        fmt_secs(sampler.phase_secs()),
3067        fmt_secs(sampler.static_secs()),
3068        fmt_bytes(activity.io_ema_bps as u64),
3069        fmt_secs(activity.idle_secs()),
3070    );
3071}
3072
3073/// Tri-state banner probe: distinguishes a closed port (nothing
3074/// listening — sshd not started) from an open-but-silent one (TCP
3075/// accepted, no SSH banner — sshd starting, or something else holding
3076/// the port). The wait loops log transitions; a long silence that moves
3077/// Closed→Silent is progress, not a stall.
3078#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3079enum BannerProbe {
3080    Banner,
3081    /// Accepted, no bytes (timeout or clean EOF): listener present,
3082    /// banner not out yet.
3083    OpenSilent,
3084    /// Accepted, but the bytes are not SSH: wrong daemon, port squat,
3085    /// or corrupt transmission — never "sshd starting".
3086    Unexpected,
3087    Closed,
3088}
3089
3090async fn probe_banner(port: u16) -> (BannerProbe, Option<String>) {
3091    use tokio::io::AsyncReadExt;
3092    let stream = match tokio::time::timeout(
3093        timeouts::SSH_BANNER_CONNECT_BUDGET,
3094        tokio::net::TcpStream::connect((PROVEN_SSH_HOST, port)),
3095    )
3096    .await
3097    {
3098        Ok(Ok(s)) => s,
3099        _ => return (BannerProbe::Closed, None),
3100    };
3101    let mut buf = [0u8; 256];
3102    let mut stream = stream;
3103    match tokio::time::timeout(timeouts::SSH_BANNER_READ_BUDGET, stream.read(&mut buf)).await {
3104        Ok(Ok(n)) if n > 0 => {
3105            let b = String::from_utf8_lossy(&buf[..n]);
3106            if b.starts_with("SSH-") {
3107                (BannerProbe::Banner, Some(b.trim().to_string()))
3108            } else {
3109                (BannerProbe::Unexpected, None)
3110            }
3111        }
3112        // Accepted but silent: starting, not absent.
3113        _ => (BannerProbe::OpenSilent, None),
3114    }
3115}
3116
3117/// One banner read ([`timeouts::SSH_BANNER_CONNECT_BUDGET`] +
3118/// [`timeouts::SSH_BANNER_READ_BUDGET`]). `None` = no sshd right now.
3119async fn banner_once(port: u16) -> Option<String> {
3120    probe_banner(port).await.1
3121}
3122
3123/// Guest readiness: banner phases for display, registry probe for truth.
3124/// The FIRST banner only means Setup reached a boot with SSH up — Windows
3125/// then typically reboots into further passes. Victory is declared when
3126/// the guest itself reports Setup done (no OOBE in progress, no reboot
3127/// pending), not after any fixed time window. Returns the banner (for the
3128/// `tested-isos.jsonl` record).
3129///
3130/// Always probes with the default password (the media is always built with
3131/// it — Setup rejects weak ones mid-install). A custom `password` is
3132/// rotated in after READY, before the ready line, via
3133/// `change_guest_password` (which verifies the new login). The custom
3134/// password never touches the answer file.
3135/// Shared observability for the install/boot waits: the one monitor
3136/// session plus the paths it watches. Bundled so the wait fns don't
3137/// sprawl argument lists (clippy limit is 7). `vnc` is the report
3138/// coordinate (None for gtk/cocoa/none displays).
3139#[derive(Clone)]
3140struct GuestScope {
3141    mon: std::sync::Arc<crate::ipc::Monitor>,
3142    shots_dir: PathBuf,
3143    serial_log: String,
3144    vnc: Option<String>,
3145}
3146
3147async fn wait_install_ready(
3148    port: u16,
3149    deadline: Duration,
3150    user: &str,
3151    password: &str,
3152    recovery: bool,
3153    auto_updates: bool,
3154    scope: &GuestScope,
3155) -> Result<String> {
3156    use crate::ssh::{GuestProgress, probe_setup_done};
3157    use crate::unattend::DEFAULT_PASSWORD;
3158    let start = std::time::Instant::now();
3159    // Phase 1: first banner.
3160    let mut activity = ActivityMonitor::new();
3161    // Disk beside the screenshots dir feeds growth tracking (`shots_dir`
3162    // is `<vm>/screenshots`, so its parent is the VM dir).
3163    let disk = scope
3164        .shots_dir
3165        .parent()
3166        .map(|d| d.join(crate::paths::DISK_IMAGE));
3167    // Reboot awareness while Setup applies (no SSH yet — serial is the
3168    // only below-screenshot voice): count OVMF firmware handoffs.
3169    let mut boots_seen = boot_count(&scope.serial_log);
3170    // The install never times out on its own: only the operator stops it
3171    // (Ctrl-C). Past the deadline the loop says so loudly and keeps
3172    // waiting — a slow host is not a failed install.
3173    let mut deadline_warned = false;
3174    // Miss-reason tracking: a silence that moves closed→silent is sshd
3175    // stirring (progress); log transitions, never pollute per tick. None
3176    // until the first probe, so tick 1 always announces the baseline.
3177    let mut probe_state: Option<BannerProbe> = None;
3178    let banner = loop {
3179        if start.elapsed() > deadline && !deadline_warned {
3180            deadline_warned = true;
3181            eprintln!(
3182                "still no SSH banner on {PROVEN_SSH_HOST}:{port} after {} s — still waiting (Ctrl-C stops the install, nothing else does)",
3183                deadline.as_secs()
3184            );
3185        }
3186        match probe_banner(port).await {
3187            (BannerProbe::Banner, Some(b)) => {
3188                eprintln!(
3189                    "guest SSH is up (first contact) — Setup is still installing Windows, not ready yet ({b})"
3190                );
3191                break b;
3192            }
3193            (state, _) => {
3194                if Some(state) != probe_state {
3195                    probe_state = Some(state);
3196                    match state {
3197                        BannerProbe::Closed => eprintln!(
3198                            "ssh port {port} closed (sshd not started yet) — still waiting"
3199                        ),
3200                        BannerProbe::OpenSilent => eprintln!(
3201                            "ssh port {port} open but silent (sshd starting?) — still waiting"
3202                        ),
3203                        BannerProbe::Unexpected => eprintln!(
3204                            "ssh port {port} answered but not with SSH (wrong daemon or port squat?) — still waiting"
3205                        ),
3206                        BannerProbe::Banner => {}
3207                    }
3208                }
3209            }
3210        }
3211        // Dead-screen watchdog (same as run): fail fast with evidence.
3212        check_boot_failure(&scope.serial_log)?;
3213        // Reboot narration: Setup reboots between passes; announce each
3214        // firmware bounce instead of leaving the long wait mute.
3215        let boots = boot_count(&scope.serial_log);
3216        if let Some(note) = boot_note(boots_seen, boots) {
3217            eprintln!("{note}");
3218        }
3219        boots_seen = boots;
3220        // Stall watchdog: frozen disk I/O + no banner = parked. No screen
3221        // state down here (SSH probing, not frame watching), so take the
3222        // strict path — same as a boot that never rendered. Warn-only:
3223        // nothing but the operator halts an install.
3224        activity.sample(&scope.mon, disk.as_deref()).await;
3225        activity.check_stall(None, false)?;
3226        tokio::time::sleep(timeouts::SSH_POLL_INTERVAL).await;
3227    };
3228    // Phase 2: ask the guest until it reports done. Banner loss between
3229    // probes means a reboot (reported); probe errors mean sshd is
3230    // mid-restart (retried, not fatal). Each probe gets a hard budget: a
3231    // stalled handshake mid-reboot must surface, never hang the loop.
3232    // Separate counter for the overloaded state: banner stable but every
3233    // exec timing out means the guest is too saturated to cold-start
3234    // PowerShell (Setup still applying), not rebooting. Hammering it with
3235    // a probe every 10 s only stacks more powershell.exe on the pile, so
3236    // the cadence backs off while stalled.
3237    //
3238    // Narration policy: transient states print once per *change* (reboot,
3239    // new pending phase) plus a slow heartbeat — never one line per probe.
3240    // Default output is progress; words like "failed"/"ERROR" are reserved
3241    // for things that are actually wrong (raw errors: RUST_LOG=debug).
3242    let mut reboots = 0u32;
3243    let mut was_up = true;
3244    let mut exec_stalls = 0u32;
3245    // Last pending-state line printed, and when the heartbeat last fired.
3246    let mut phase: Option<String> = None;
3247    let mut last_beat = start;
3248    // Same operator-only rule as phase 1: the install never times out on
3249    // its own. Past the deadline the loop says so loudly and keeps
3250    // probing — a slow host is not a failed install.
3251    let mut deadline_warned = false;
3252    loop {
3253        if start.elapsed() > deadline && !deadline_warned {
3254            deadline_warned = true;
3255            eprintln!(
3256                "still waiting for guest readiness on {PROVEN_SSH_HOST}:{port} after {} s — still probing (Ctrl-C stops the install, nothing else does)",
3257                deadline.as_secs()
3258            );
3259        }
3260        // The probe itself gets a hard budget: a stalled handshake
3261        // mid-reboot would otherwise hang the loop silently (observed as
3262        // "long polling, never noticing SSH is up"). Timeout = not yet.
3263        match tokio::time::timeout(
3264            timeouts::READINESS_PROBE_BUDGET,
3265            probe_setup_done(PROVEN_SSH_HOST, port, user, DEFAULT_PASSWORD),
3266        )
3267        .await
3268        {
3269            Ok(Ok(GuestProgress::Ready)) => {
3270                if password != DEFAULT_PASSWORD {
3271                    eprintln!("rotating guest password ...");
3272                    crate::ssh::change_guest_password(
3273                        PROVEN_SSH_HOST,
3274                        port,
3275                        user,
3276                        DEFAULT_PASSWORD,
3277                        password,
3278                    )
3279                    .await?;
3280                }
3281                // Recovery policy (default off, docker-like): a damaged disk
3282                // fails fast instead of parking at "Diagnosing your PC".
3283                // Specialize already set the off state on the first OS boot
3284                // (an early Ctrl-C is covered there); this step applies the
3285                // flag's end state as the credential (post-rotation) —
3286                // `--recovery` re-arms both switches.
3287                if let Err(e) = crate::ssh::set_recovery_enabled(
3288                    PROVEN_SSH_HOST,
3289                    port,
3290                    user,
3291                    password,
3292                    recovery,
3293                )
3294                .await
3295                {
3296                    eprintln!("warning: bcdedit failed ({e:#}); recovery state unchanged");
3297                }
3298                // Update policy (default off, docker-like): wuauserv runs as
3299                // SYSTEM and would otherwise reboot the box on Microsoft's
3300                // schedule with no logon. Disabled = deterministic; manual
3301                // updates over SSH still work anytime.
3302                if !auto_updates
3303                    && let Err(e) =
3304                        crate::ssh::set_auto_updates(PROVEN_SSH_HOST, port, user, password, false)
3305                            .await
3306                {
3307                    eprintln!("warning: wuauserv disable failed ({e:#})");
3308                }
3309                // Headless diet (was specialize orders; moved post-READY so
3310                // four PowerShell cold starts stop serializing into Setup):
3311                // NLA Private + service trim in one invocation, best-effort.
3312                if let Err(e) =
3313                    crate::ssh::apply_headless_diet(PROVEN_SSH_HOST, port, user, password).await
3314                {
3315                    eprintln!("warning: headless diet failed ({e:#})");
3316                }
3317                eprintln!(
3318                    "guest reports Setup complete across {reboots} reboot(s) — install complete"
3319                );
3320                return Ok(banner);
3321            }
3322            Ok(Ok(GuestProgress::Busy(what))) => {
3323                exec_stalls = 0;
3324                if phase.as_deref() == Some(what.as_str()) {
3325                    // Unchanged since the last probe: stay quiet unless the
3326                    // heartbeat is due (proof of life on a long install).
3327                    if last_beat.elapsed() >= timeouts::PROGRESS_HEARTBEAT {
3328                        last_beat = std::time::Instant::now();
3329                        eprintln!(
3330                            "still installing: {what} — {}s elapsed, {reboots} reboot(s) so far",
3331                            start.elapsed().as_secs()
3332                        );
3333                    }
3334                } else {
3335                    eprintln!("still installing: {what}");
3336                    phase = Some(what);
3337                    last_beat = std::time::Instant::now();
3338                }
3339            }
3340            Ok(Err(e)) => {
3341                exec_stalls += 1;
3342                if e.downcast_ref::<crate::ssh::ProbeOutputBroken>().is_some() {
3343                    // OUR probe broke, not the guest: never narrate that as a
3344                    // reboot. Rare but real, so it stays at the default level.
3345                    if exec_stalls == 1 || exec_stalls == 5 {
3346                        eprintln!(
3347                            "warning: readiness probe could not read the guest's reply ({e:#}) — probe/output problem, not a reboot; retrying ..."
3348                        );
3349                    }
3350                } else if exec_stalls == 1 {
3351                    // Expected while Setup reboots: sshd restarts with the
3352                    // guest. One calm line per stall run; the raw transport
3353                    // error goes to RUST_LOG=debug instead of reading as a
3354                    // failure.
3355                    eprintln!(
3356                        "waiting: SSH dropped — Windows is rebooting as part of Setup, retrying ..."
3357                    );
3358                    tracing::debug!("probe error: {e:#}");
3359                } else if exec_stalls == 5 {
3360                    // Five straight exec failures with the banner up is not a
3361                    // reboot (the banner would drop) — it is saturation.
3362                    eprintln!(
3363                        "exec stalled 5x with SSH stable — guest is overloaded (Setup still applying), not rebooting; backing off probes ..."
3364                    );
3365                }
3366            }
3367            Err(_) => {
3368                exec_stalls += 1;
3369                if exec_stalls == 1 {
3370                    eprintln!(
3371                        "waiting: probe timed out — guest is busy (Setup still applying), retrying ..."
3372                    );
3373                } else if exec_stalls == 5 {
3374                    eprintln!(
3375                        "probe timed out 5x with SSH stable — guest is overloaded, backing off probes ..."
3376                    );
3377                }
3378            }
3379        }
3380        let up = banner_once(port).await.is_some();
3381        match (was_up, up) {
3382            (true, false) => {
3383                eprintln!(
3384                    "Windows is rebooting (#{}) — SSH dropped, waiting for it to return ...",
3385                    reboots + 1
3386                );
3387            }
3388            (false, true) => {
3389                reboots += 1;
3390                exec_stalls = 0;
3391                eprintln!("SSH back (reboot #{reboots} finished) — resuming probes ...");
3392            }
3393            _ => {}
3394        }
3395        was_up = up;
3396        // Back off while stalled (10 s → up to 60 s): each probe spawns a
3397        // PowerShell cold start, and hammering a saturated guest buries it.
3398        let backoff = 1 + (exec_stalls / 5).min(5);
3399        tokio::time::sleep(timeouts::READINESS_PROBE_INTERVAL * backoff).await;
3400    }
3401}
3402
3403/// Ctrl-C and SIGTERM both mean "stop the VM". Signals don't unwind, so
3404/// without this a SIGTERM'd CLI would orphan QEMU despite `kill_on_drop`.
3405#[cfg(unix)]
3406async fn shutdown_signal() {
3407    use tokio::signal::unix::{SignalKind, signal};
3408    let mut term = signal(SignalKind::terminate()).expect("SIGTERM handler");
3409    tokio::select! {
3410        _ = tokio::signal::ctrl_c() => {},
3411        _ = term.recv() => {},
3412    }
3413}
3414
3415#[cfg(not(unix))]
3416async fn shutdown_signal() {
3417    let _ = tokio::signal::ctrl_c().await;
3418}
3419
3420#[cfg(test)]
3421mod tests {
3422    use super::*;
3423
3424    fn install_fixture(memory_mb: u32, cpus: u32) -> (Vec<String>, Vec<String>) {
3425        let dir = std::env::temp_dir();
3426        let code = dir.join("code.fd");
3427        let vars = dir.join("vars.fd");
3428        let usb = dir.join("usb.dmg");
3429        let spec = InstallQemuArgv {
3430            machine: "virt",
3431            accel: "tcg",
3432            cpu: "max",
3433            memory_mb,
3434            cpus,
3435            display: Display::Vnc("vnc=127.0.0.1:10,password=on".to_string()),
3436            code_tpl: &code,
3437            vars_fd: &vars,
3438            serial_log: "serial.log",
3439            mon_sock: "mon.sock",
3440            qmp_sock: "qmp.sock",
3441            usb_image: &usb,
3442            target: "disk.qcow2",
3443            arch: Architecture::Arm64,
3444        };
3445        (
3446            install_qemu_argv(&spec),
3447            qemu_img_create_args("disk.qcow2", 128),
3448        )
3449    }
3450
3451    #[test]
3452    fn install_sizing_reaches_qemu_argv() {
3453        // The flags a user passes must be the bytes QEMU gets: no QEMU
3454        // needed, just the pure argv constructors.
3455        // Golden sidecar lives next to the disk it blesses.
3456        assert_eq!(
3457            golden_sidecar("disk.qcow2"),
3458            std::path::PathBuf::from("disk.qcow2.golden")
3459        );
3460        let (argv, img) = install_fixture(8192, 8);
3461        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
3462        assert_eq!(at("-m"), "8192");
3463        assert_eq!(at("-smp"), "8");
3464        assert_eq!(img.last().unwrap(), "128G");
3465        // Defaults stay proven-shaped.
3466        let (argv, img) = install_fixture(4096, 4);
3467        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
3468        assert_eq!(at("-m"), "4096");
3469        assert_eq!(at("-smp"), "4");
3470        assert_eq!(at("-display"), "vnc=127.0.0.1:10,password=on");
3471        let img64 = qemu_img_create_args("disk.qcow2", 64);
3472        assert_eq!(img64.last().unwrap(), "64G");
3473        assert_eq!(img[..5], img64[..5]);
3474    }
3475
3476    #[test]
3477    fn live_migration_uris_quote_paths() {
3478        // NIC name comes from `info network`, never guessed: first
3479        // type=nic entry wins, netdev/user lines are skipped.
3480        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";
3481        assert_eq!(find_nic_name(info), Some("virtio-net-pci.0"));
3482        assert_eq!(find_nic_name("n1: index=0,type=user\n"), None);
3483        assert_eq!(find_nic_name("garbage\n"), None);
3484        // Migration URIs quote paths (cache dirs contain spaces) and the
3485        // live companions live next to the disk they belong to.
3486        let spaced = std::path::Path::new("/Volumes/2TB Storage Vault/vm/golden-live.state");
3487        assert_eq!(
3488            migrate_write_uri(spaced),
3489            "exec:cat > '/Volumes/2TB Storage Vault/vm/golden-live.state'"
3490        );
3491        assert_eq!(
3492            migrate_read_uri(spaced),
3493            "exec:cat '/Volumes/2TB Storage Vault/vm/golden-live.state'"
3494        );
3495        let quoted = std::path::Path::new("/tmp/o'brien/state");
3496        assert_eq!(
3497            migrate_write_uri(quoted),
3498            "exec:cat > '/tmp/o'\\''brien/state'"
3499        );
3500        let dir = std::path::Path::new("/tmp/vm");
3501        let (state, vars, overlay) = live_paths(dir);
3502        assert_eq!(state, dir.join(crate::paths::LIVE_STATE_FILE));
3503        assert_eq!(vars, dir.join(crate::paths::LIVE_VARS_BACKUP));
3504        assert_eq!(overlay, dir.join(crate::paths::LIVE_OVERLAY));
3505    }
3506
3507    #[test]
3508    fn install_cocoa_display_passes_through() {
3509        // Non-VNC displays reach QEMU verbatim (the VNC password step is
3510        // guarded separately); cocoa installs show a window instead.
3511        let dir = std::env::temp_dir();
3512        let code = dir.join("code.fd");
3513        let vars = dir.join("vars.fd");
3514        let usb = dir.join("usb.dmg");
3515        let spec = InstallQemuArgv {
3516            machine: "virt",
3517            accel: "tcg",
3518            cpu: "max",
3519            memory_mb: 4096,
3520            cpus: 4,
3521            display: Display::Cocoa,
3522            code_tpl: &code,
3523            vars_fd: &vars,
3524            serial_log: "serial.log",
3525            mon_sock: "mon.sock",
3526            qmp_sock: "qmp.sock",
3527            usb_image: &usb,
3528            target: "disk.qcow2",
3529            arch: Architecture::Arm64,
3530        };
3531        let argv = install_qemu_argv(&spec);
3532        let at = |flag: &str| argv[argv.iter().position(|a| a == flag).unwrap() + 1].clone();
3533        assert_eq!(at("-display"), "cocoa");
3534    }
3535
3536    #[test]
3537    fn blockstats_parse_totals() {
3538        let sample = "drive-tgt: rd_bytes=1048576 wr_bytes=524288 rd_operations=12\n\
3539                      drive-usb: rd_bytes=100 wr_bytes=0\n";
3540        assert_eq!(
3541            ActivityMonitor::parse_total(sample),
3542            Some(1048576 + 524288 + 100)
3543        );
3544        assert_eq!(ActivityMonitor::parse_total(""), None);
3545    }
3546
3547    #[test]
3548    fn activity_math_without_qemu() {
3549        // Pure derivations on hand-built state: no monitor, no sleeps.
3550        let now = std::time::Instant::now();
3551        let mut m = ActivityMonitor {
3552            last_total: 1000,
3553            last_change: now - Duration::from_secs(61),
3554            warned: false,
3555            disk_start: Some(100),
3556            disk_last: 150,
3557            disk_last_change: now - Duration::from_secs(61),
3558            last_sample: Some(now),
3559            io_ema_bps: 0.0,
3560            growth_ema_bps: 0.0,
3561        };
3562        assert_eq!(m.idle_secs(), 61);
3563        assert_eq!(m.disk_idle_secs(), 61);
3564        assert_eq!(m.growth_since_start(), 50);
3565        assert!(!m.is_moving());
3566        // EMA: half-window step moves halfway to the instant rate.
3567        assert_eq!(ActivityMonitor::ema_step(0.0, 100.0, 150.0, 300.0), 50.0);
3568        assert_eq!(ActivityMonitor::ema_step(50.0, 100.0, 0.0, 300.0), 50.0);
3569        // Fresh activity resets the idle clock.
3570        m.last_change = std::time::Instant::now();
3571        assert!(m.is_moving());
3572    }
3573
3574    #[test]
3575    fn stall_watchdog_needs_non_progress_and_flat_guest() {
3576        // Progress states never bail, however long I/O has been flat: a
3577        // slow host applying the image answers only to the operator, not
3578        // the stall watchdog (live 2026-10-07: 120s of CPU-bound setup
3579        // with InstallerStep on screen aborted a valid install).
3580        let mut m = ActivityMonitor {
3581            last_total: 1000,
3582            last_change: std::time::Instant::now() - Duration::from_secs(10_000),
3583            warned: false,
3584            disk_start: Some(100),
3585            disk_last: 100,
3586            disk_last_change: std::time::Instant::now() - Duration::from_secs(10_000),
3587            last_sample: None,
3588            io_ema_bps: 0.0,
3589            growth_ema_bps: 0.0,
3590        };
3591        for state in [
3592            ScreenState::InstallerStep,
3593            ScreenState::OobeStep,
3594            ScreenState::FirmwareBoot,
3595            ScreenState::Lockscreen,
3596        ] {
3597            assert!(m.check_stall(Some(state), true).is_ok(), "{state:?}");
3598        }
3599        // Non-progress + flat on both signals bails when fatal.
3600        assert!(m.check_stall(Some(ScreenState::ErrorScreen), true).is_err());
3601        assert!(m.check_stall(Some(ScreenState::Dark), true).is_err());
3602        // No frame yet: strict path, bails like a boot that never rendered.
3603        assert!(m.check_stall(None, true).is_err());
3604        // Flat I/O but a growing disk is not parked: bail needs both.
3605        m.disk_last_change = std::time::Instant::now();
3606        m.disk_last = 200;
3607        assert!(m.check_stall(Some(ScreenState::ErrorScreen), true).is_ok());
3608        // Install path is warn-only: the same flat guest that bails above
3609        // only warns when fatal is false — nothing but the operator halts
3610        // an install.
3611        m.disk_last_change = std::time::Instant::now() - Duration::from_secs(10_000);
3612        m.disk_last = 100;
3613        assert!(m.check_stall(Some(ScreenState::ErrorScreen), false).is_ok());
3614        assert!(m.check_stall(None, false).is_ok());
3615    }
3616
3617    #[test]
3618    fn tilde_expands_to_home() {
3619        let home = std::env::var("HOME").unwrap();
3620        assert_eq!(
3621            expand_tilde("~/x.iso".into()),
3622            PathBuf::from(home.clone()).join("x.iso")
3623        );
3624        assert_eq!(expand_tilde("~".into()), PathBuf::from(home));
3625        // Untouched: relative, absolute, other users.
3626        assert_eq!(expand_tilde("rel/x.iso".into()), PathBuf::from("rel/x.iso"));
3627        assert_eq!(
3628            expand_tilde("/abs/x.iso".into()),
3629            PathBuf::from("/abs/x.iso")
3630        );
3631        assert_eq!(
3632            expand_tilde("~other/x.iso".into()),
3633            PathBuf::from("~other/x.iso")
3634        );
3635    }
3636
3637    #[test]
3638    fn missing_iso_error_names_the_path_it_tried() {
3639        let tmp = tempfile::tempdir().unwrap();
3640        let present = tmp.path().join("present.iso");
3641        std::fs::write(&present, b"x").unwrap();
3642        assert!(require_win_iso(&present).is_ok());
3643        // A directory is not an ISO.
3644        assert!(require_win_iso(tmp.path()).is_err());
3645
3646        let missing = tmp.path().join("Win11.iso");
3647        let err = require_win_iso(&missing).unwrap_err().to_string();
3648        assert!(err.contains(&missing.display().to_string()), "{err}");
3649        assert!(!err.contains("quote-shielded"), "{err}");
3650        assert!(!err.contains("unquoted"), "{err}");
3651
3652        // A literal `~` survives expand_tilde only when $HOME is unset (or
3653        // the path is ~otheruser) — the hint must say that, not "quote it".
3654        let err = require_win_iso(Path::new("~/Win11.iso"))
3655            .unwrap_err()
3656            .to_string();
3657        assert!(err.contains("$HOME"), "{err}");
3658        let err = require_win_iso(Path::new("~other/x.iso"))
3659            .unwrap_err()
3660            .to_string();
3661        assert!(err.contains("~otheruser"), "{err}");
3662    }
3663
3664    #[test]
3665    fn report_renders_table() {
3666        use crate::provenance::{DependencyPins, GuestParams, HostSpecs, IsoIdentity, Provenance};
3667        let record = crate::provenance::TestRecord {
3668            tested_at_epoch: 1_758_600_000,
3669            outcome: "ssh-banner".to_string(),
3670            ssh_banner: Some("SSH-2.0-test".to_string()),
3671            provenance: Provenance {
3672                builder_version: "0.1.0".to_string(),
3673                build_commit: "abcdef1234567".to_string(),
3674                build_dirty: true,
3675                built_at_epoch: 1_758_600_000,
3676                source_iso: IsoIdentity {
3677                    file_name: "Win11.iso".to_string(),
3678                    size_bytes: 1,
3679                    sha256: "x".to_string(),
3680                    pvd_creation: None,
3681                    wim_images: vec![],
3682                },
3683                host: HostSpecs {
3684                    os: "macos".to_string(),
3685                    os_version: "26.0".to_string(),
3686                    arch: "aarch64".to_string(),
3687                },
3688                deps: DependencyPins {
3689                    qemu_tag: "qemu-v11.1.1".to_string(),
3690                    wimlib_tag: "wimlib-v1.14.5-27".to_string(),
3691                    virtio_iso_name: "virtio-win.iso".to_string(),
3692                    virtio_sha256: None,
3693                    openssh_zip_name: "OpenSSH-ARM64.zip".to_string(),
3694                    openssh_release_tag: "t".to_string(),
3695                },
3696                guest: GuestParams {
3697                    arch: "arm64".to_string(),
3698                    username: "u".to_string(),
3699                    locale: "en-US".to_string(),
3700                    accel: "tcg".to_string(),
3701                },
3702            },
3703        };
3704        let dir = tempfile::tempdir().unwrap();
3705        let log = dir.path().join("tested-isos.jsonl");
3706        std::fs::write(&log, serde_json::to_string(&record).unwrap() + "\n").unwrap();
3707        let table = render_report(&log).unwrap();
3708        assert!(table.contains("| Date | ISO |"), "{table}");
3709        assert!(table.contains("Win11.iso"), "{table}");
3710        assert!(table.contains("abcdef1*"), "{table}");
3711        // No virtio hash in the fixture → falls back to the ISO name.
3712        assert!(table.contains("virtio-win.iso"), "{table}");
3713        assert_eq!(epoch_to_date(1_758_600_000), "2025-09-23");
3714    }
3715
3716    // --- boot failure screen classification -------------------------------
3717
3718    #[test]
3719    fn boot_count_and_note_from_serial() {
3720        let path = std::env::temp_dir().join(format!("wh-boot-count-{}.log", std::process::id()));
3721        std::fs::write(
3722            &path,
3723            "BdsDxe: loading Boot0001 \"USB\"\n\
3724             BdsDxe: starting Boot0001 \"USB\"\n\
3725             BdsDxe: failed to load Boot0002 \"NVMe\": Not Found\n\
3726             BdsDxe: starting Boot0003 \"Windows Boot Manager\"\n",
3727        )
3728        .unwrap();
3729        assert_eq!(boot_count(path.to_str().unwrap()), 2);
3730        let _ = std::fs::remove_file(&path);
3731        assert_eq!(boot_count("/nonexistent/wh-no-serial.log"), 0);
3732        // Narration: first boot, reboots, flat, and regressions.
3733        assert_eq!(boot_note(0, 0), None);
3734        assert_eq!(
3735            boot_note(0, 1).as_deref(),
3736            Some("guest booted (first firmware boot)")
3737        );
3738        assert_eq!(
3739            boot_note(1, 3).as_deref(),
3740            Some("guest rebooted (firmware boot #3 seen on serial)")
3741        );
3742        assert_eq!(boot_note(3, 3), None);
3743        assert_eq!(boot_note(3, 2), None);
3744    }
3745
3746    #[test]
3747    fn screen_state_real_frames_classify_by_directory() {
3748        // Integration over real screendumps through the k-NN classifier.
3749        // The class directory IS the label: drop a capture in, rebuild
3750        // the index, and both this test and the runtime pick it up with
3751        // no filename list anywhere.
3752        // Layout: tests/fixtures/<windows-version>/<class-dir>/*.png.
3753        //
3754        // Verdicts are snapshotted, not asserted at 100%: the corpus
3755        // holds known-unlearnable twin pairs, so exact-fit is demanded
3756        // nowhere. A changed verdict fails with a diff; bless it with
3757        // `cargo insta review` (or `INSTA_UPDATE=always` as the
3758        // auto-accept escape hatch).
3759        // Single dir→label map: a new class dir touches one arm, never two.
3760        let target_for_class = |class: &str| match class {
3761            "dark" => ScreenState::Dark,
3762            "flat-field" => ScreenState::FlatField,
3763            "error-shell" => ScreenState::ErrorShell,
3764            "error-recovery" => ScreenState::ErrorRecovery,
3765            "error-bluescreen" | "error-modal" => ScreenState::ErrorScreen,
3766            "oobe-step" => ScreenState::OobeStep,
3767            "installer-step" => ScreenState::InstallerStep,
3768            "firmware-boot" => ScreenState::FirmwareBoot,
3769            "lockscreen" => ScreenState::Lockscreen,
3770            // Unknown future class dirs: fail loudly here instead of
3771            // silently absorbing into the snapshot.
3772            _ => panic!("test map missing class dir: {class}"),
3773        };
3774        let root = format!("{}/tests/fixtures", env!("CARGO_MANIFEST_DIR"));
3775        // The shipped path, not a test-only twin: the baked artifact
3776        // scores here exactly as the live tick scores in production.
3777        let index = crate::screen_knn::bundled_index();
3778        let mut checked = 0;
3779        let mut lines = Vec::new();
3780        let mut misses = Vec::new();
3781        let mut ok_gap_sum = 0.0f64;
3782        let mut versions: Vec<_> = std::fs::read_dir(&root)
3783            .unwrap()
3784            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3785            .collect();
3786        versions.sort();
3787        for version in versions {
3788            // Skip Finder noise (.DS_Store) and anything else that is
3789            // not a version directory.
3790            if !std::path::Path::new(&format!("{root}/{version}")).is_dir() {
3791                continue;
3792            }
3793            let mut classes: Vec<_> = std::fs::read_dir(format!("{root}/{version}"))
3794                .unwrap()
3795                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3796                .collect();
3797            classes.sort();
3798            for class in classes {
3799                let dir = format!("{root}/{version}/{class}");
3800                if !std::path::Path::new(&dir).is_dir() {
3801                    continue;
3802                }
3803                let mut names: Vec<_> = std::fs::read_dir(&dir)
3804                    .unwrap()
3805                    .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3806                    .filter(|n| n.ends_with(".png"))
3807                    .collect();
3808                names.sort();
3809                for name in names {
3810                    let key = format!("{version}/{class}/{name}");
3811                    // Unknown class dirs fail loudly via the map (never
3812                    // silently absorbed); misses group at the bottom under
3813                    // their own header, so no horizontal hunt/peck. Gaps
3814                    // print to stdout (not the snapshot: float formatting
3815                    // must stay bit-exact everywhere, and the gap is a
3816                    // tuning signal, not a verdict). Run with
3817                    // `-- --nocapture` to score an index rebuild: wider
3818                    // gaps bless new centers, narrower ones don't.
3819                    let want = target_for_class(&class);
3820                    let (got, gap, matched) = classify_fixture(&index, &key);
3821                    println!("gap {gap:.4} {key} via {matched}");
3822                    if got == want {
3823                        ok_gap_sum += f64::from(gap);
3824                        lines.push(format!("ok   {key} => {got:?}"));
3825                    } else {
3826                        misses.push(format!(
3827                            "MISS {key} => got {got:?}, want {want:?} via {matched}"
3828                        ));
3829                    }
3830                    checked += 1;
3831                }
3832            }
3833        }
3834        assert!(checked > 0, "no fixtures found under tests/fixtures");
3835        let ok_count = checked - misses.len();
3836        let mean_ok = ok_gap_sum / f64::from(ok_count.max(1) as u32);
3837        println!("mean ok-gap {mean_ok:.4} over {ok_count}/{checked}");
3838        lines.push(format!("--- misses {}/{checked} ---", misses.len()));
3839        lines.extend(misses);
3840        insta::assert_snapshot!("screen_state_by_directory", lines.join("\n"));
3841    }
3842
3843    /// Test-only fixture classification through the real live path:
3844    /// [`crate::vision::classify_screen`] on the decoded frame. Returns
3845    /// the state plus the matched exemplar name, so misses carry their
3846    /// cause into the snapshot itself.
3847    fn classify_fixture(
3848        index: &crate::screen_knn::KnnIndex,
3849        name: &str,
3850    ) -> (ScreenState, f32, String) {
3851        let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
3852        let (rgb, w, h) = crate::screen_knn::load_rgb_8bit(&path);
3853        let q = crate::screen_knn::KnnIndex::embed_frame(&rgb, w, h);
3854        let (got_class, gap, matched) = index.predict(&q, None).unwrap();
3855        let got = match got_class {
3856            crate::screen_knn::ScreenClass::Dark => ScreenState::Dark,
3857            crate::screen_knn::ScreenClass::FlatField => ScreenState::FlatField,
3858            crate::screen_knn::ScreenClass::ErrorShell => ScreenState::ErrorShell,
3859            crate::screen_knn::ScreenClass::InstallerStep => ScreenState::InstallerStep,
3860            crate::screen_knn::ScreenClass::Lockscreen => ScreenState::Lockscreen,
3861            crate::screen_knn::ScreenClass::FirmwareBoot => ScreenState::FirmwareBoot,
3862            crate::screen_knn::ScreenClass::OobeStep => ScreenState::OobeStep,
3863            crate::screen_knn::ScreenClass::ErrorRecovery => ScreenState::ErrorRecovery,
3864            crate::screen_knn::ScreenClass::ErrorScreen => ScreenState::ErrorScreen,
3865        };
3866        (got, gap, matched)
3867    }
3868
3869    #[test]
3870    fn vnc_password_command_is_exact() {
3871        // Regression: the install path once sent "change vnc p.password",
3872        // which QEMU ignores — VNC auth then failed with no error anywhere.
3873        assert_eq!(
3874            vnc_password_command(),
3875            format!("change vnc password {PROVEN_VNC_PASSWORD}")
3876        );
3877    }
3878
3879    #[test]
3880    fn run_chain_install_params_passes_cadence_through() {
3881        // Regression: `run --win-iso --screenshots-every-secs 10` installed
3882        // at 60s cadence because the chain hardcoded the default.
3883        let args = RunArgs {
3884            disk: None,
3885            ssh_port: crate::qemu::PROVEN_SSH_PORT,
3886            display: crate::qemu::Display::parse("vnc=127.0.0.1:10").unwrap(),
3887            memory: 4096,
3888            cpus: 4,
3889            disk_size: 64,
3890            vm_dir: None,
3891            qemu_dir: None,
3892            username: "u".into(),
3893            password: "p".into(),
3894            shell: false,
3895            live: false,
3896            win_iso: None,
3897            install_timeout_secs: 60,
3898            screenshots_every_secs: 10,
3899            classify_every_secs: Some(5),
3900        };
3901        let p = run_chain_install_params(&args, PathBuf::from("w.iso"));
3902        assert_eq!(p.screenshots_every_secs, 10);
3903        assert_eq!(p.classify_every_secs, Some(5));
3904        assert_eq!(p.install_timeout_secs, 60);
3905        assert_eq!(p.memory_mb, 4096);
3906        assert_eq!(p.cpus, 4);
3907        assert_eq!(p.disk_size_gb, 64);
3908    }
3909
3910    #[test]
3911    fn failure_report_carries_frame_serial_vnc() {
3912        let report = format_failure_report(
3913            Some((
3914                PathBuf::from("/vm/screenshots/screenshot-1.png"),
3915                ScreenState::FlatField,
3916            )),
3917            "BdsDxe: starting Boot0003",
3918            3,
3919            Some((95, 12_582_912)),
3920            &Some("vnc://127.0.0.1:5910".to_string()),
3921        );
3922        assert!(report.contains("solid color field"), "{report}");
3923        assert!(report.contains("guest boots seen: 3"), "{report}");
3924        assert!(
3925            report.contains("/vm/screenshots/screenshot-1.png"),
3926            "{report}"
3927        );
3928        assert!(
3929            report.contains("last serial: BdsDxe: starting Boot0003"),
3930            "{report}"
3931        );
3932        assert!(report.contains("vnc: vnc://127.0.0.1:5910"), "{report}");
3933        assert!(report.contains("no I/O for 95s"), "{report}");
3934    }
3935
3936    #[test]
3937    fn failure_report_states_missing_parts() {
3938        let report = format_failure_report(None, "", 0, None, &None);
3939        assert!(
3940            report.contains("no screenshot could be captured"),
3941            "{report}"
3942        );
3943        assert!(!report.contains("last serial"), "{report}");
3944        assert!(!report.contains("vnc:"), "{report}");
3945    }
3946}