windows-headless 0.3.5-alpha

Provision an SSH-ready headless Windows 11 VM from a retail installer ISO in one command. Unattended setup, portable QEMU, no Docker.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
//! Thin CLI: clap arg shapes + dispatch to [`windows_headless::commands`].
//! All business logic (cache dirs, QEMU argv, media build) lives in the
//! library so it is testable and reusable from other frontends.
use anyhow::Result;
use clap::{Parser, Subcommand};
use std::path::PathBuf;
#[cfg(feature = "downloader")]
use windows_headless::commands::{
    BuildArgs, FetchArgs, cmd_build, cmd_fetch, cmd_fetch_qemu, cmd_fetch_wimlib, cmd_setup,
    cmd_verify_pins,
};
use windows_headless::{
    Architecture, PROVEN_SSH_PORT, PROVEN_VNC_DISPLAY,
    commands::{
        BuildMediaArgs, GenArgs, GuestArgs, GuestOp, InstallParams, ReportArgs, RunArgs,
        cmd_build_media, cmd_classify, cmd_gen, cmd_guest, cmd_install, cmd_overlay, cmd_report,
        cmd_run, cmd_snapshot, cmd_stop,
    },
};

#[derive(Parser)]
#[command(name = "windows-headless", version)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

// VM lifecycle: boot, install, stop, snapshot, guest ops.
#[derive(Subcommand)]
enum VmCmd {
    /// Run: boot the disk, attach if live, install first if missing.
    /// Boots `<vm-dir>/disk.qcow2` (or --disk); attaches to the shell when
    /// already running; installs when the disk is absent (needs cached
    /// media or --win-iso). Never rebuilds: to reinstall a live disk,
    /// delete it (or use hidden `install`), then `run`.
    Run {
        /// Disk image to boot (default: `<vm-dir>/disk.qcow2`).
        #[arg(long)]
        disk: Option<String>,
        #[arg(long, default_value_t = PROVEN_SSH_PORT)]
        ssh_port: u16,
        /// Display backend: `none`, `cocoa`, `gtk`, or `vnc=<spec>`.
        #[arg(long, default_value = PROVEN_VNC_DISPLAY, value_parser = windows_headless::Display::parse)]
        display: windows_headless::Display,
        /// Guest RAM: Docker syntax (`512m`, `4g`; bare digits are MB).
        /// Minimum 2g; Windows 11 setup needs 4g.
        #[arg(long, default_value = "4g", value_parser = windows_headless::sizes::parse_memory_mb)]
        memory: u32,
        /// Guest vCPUs, Docker-style (`--cpus`; `--smp` still works).
        #[arg(long, default_value_t = 4, visible_alias = "smp")]
        cpus: u32,
        /// New-disk size on install: Docker syntax (`64g`; bare digits are
        /// GB). Minimum 32g; ignored when booting an existing disk.
        #[arg(long, default_value = "64g", value_parser = windows_headless::sizes::parse_disk_gb)]
        disk_size: u32,
        /// VM dir for the pidfile (default: project cache `vms/win11`).
        #[arg(long)]
        vm_dir: Option<PathBuf>,
        /// Portable tree override (default: newest cached tree from `fetch-qemu`).
        #[arg(long)]
        qemu_dir: Option<PathBuf>,
        /// Guest username (for `--shell` login).
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_USERNAME)]
        username: String,
        /// Guest password (for `--shell` login).
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_PASSWORD)]
        password: String,
        /// Drop into an interactive guest shell after ready (built-in SSH
        /// client, no host `ssh` needed). Ctrl-D exits back to the CLI.
        /// Default: on when stdin is a terminal, off when piped (CI-safe).
        /// Pass `--shell` / `--shell=false` to force either way.
        #[arg(long)]
        shell: Option<bool>,
        /// Windows ISO: when the disk is missing, install it first
        /// (setup + build-media + install) instead of bailing.
        #[arg(long)]
        win_iso: Option<PathBuf>,
        /// Budget for the unattended install's SSH wait, in seconds
        /// (reached only when `--win-iso` triggers an install).
        #[arg(long, default_value_t = windows_headless::timeouts::DEFAULT_INSTALL_SSH_DEADLINE_SECS)]
        install_timeout_secs: u64,
        /// Screendump cadence during the boot wait in seconds (0 =
        /// disabled). Frames land in `<vm-dir>/screenshots/` — a boot
        /// time-lapse, so a slow or stuck boot is readable without VNC.
        #[arg(long, default_value_t = windows_headless::timeouts::DEFAULT_SCREENSHOTS_EVERY_SECS)]
        screenshots_every_secs: u64,
        /// Screen-classification cadence during the boot wait in seconds
        /// (0 = disabled, omit = accel default: 10s hardware, 30s TCG).
        /// Screendump + nearest-exemplar match with no disk write: phase
        /// changes and error screens surface in the log within seconds
        /// while PNGs stay minute-scale.
        #[arg(long)]
        classify_every_secs: Option<u64>,
        /// Resume the experimental live snapshot (migrated RAM, no boot):
        /// instant when it works. Default off — golden rewind always works.
        /// Take one first with `snapshot --live` on a running guest.
        #[arg(long, default_value_t = false)]
        live: bool,
    },
    /// Proven install: USB-HDD media + NVMe target, unattended answer
    /// file, ends at SSH with the guest reporting Setup complete.
    /// USB media must already exist (`build-media` builds it).
    #[command(hide = true)]
    Install {
        /// USB installer image (default: project cache `media/winusb.dmg`).
        #[arg(long)]
        usb_image: Option<PathBuf>,
        /// Windows ISO: when the USB image is missing, run the full chain
        /// (`setup` + `build-media --win-iso`) instead of bailing.
        /// Absent + missing image = error naming both options.
        #[arg(long)]
        win_iso: Option<PathBuf>,
        /// Screendump cadence in seconds (0 = disabled). Screenshots land in
        /// `<vm-dir>/screenshots/` — a time-lapse of the install.
        #[arg(long, default_value_t = windows_headless::timeouts::DEFAULT_SCREENSHOTS_EVERY_SECS)]
        screenshots_every_secs: u64,
        /// Screen-classification cadence in seconds (0 = disabled, omit =
        /// accel default: 10s hardware, 30s TCG). Screendump + nearest-
        /// exemplar match with no disk write: phase changes and error
        /// screens surface in the log within seconds while PNGs stay
        /// minute-scale.
        #[arg(long)]
        classify_every_secs: Option<u64>,
        /// Guest username (must match the media's answer file; used for
        /// the readiness probe login and the ready line).
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_USERNAME)]
        username: String,
        /// End-state guest password. The media is always built with the
        /// default (Setup-safe); a different value here is rotated in via
        /// `net user` after the guest reports ready, then verified.
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_PASSWORD)]
        password: String,
        /// Drop into an interactive guest shell after ready (built-in SSH
        /// client, no host `ssh` needed). Ctrl-D exits back to the CLI.
        /// Default: on when stdin is a terminal, off when piped (CI-safe).
        /// Pass `--shell` / `--shell=false` to force either way.
        #[arg(long)]
        shell: Option<bool>,
        /// Keep Windows Automatic Repair ("Diagnosing your PC") enabled.
        /// Default off: faster boots. With recovery off, a truly damaged
        /// virtual disk fails fast instead of repairing. Snapshots are
        /// the safety net, not WinRE. The off default is set at specialize
        /// (first OS boot, so even an early Ctrl-C is covered); this flag
        /// re-arms recovery when Setup reports Ready.
        #[arg(long, default_value_t = false)]
        recovery: bool,
        /// Leave Windows Update automatic (download + install + reboot on
        /// Microsoft's schedule, no logon needed). Default off: wuauserv
        /// is disabled at install — no surprise reboots, docker-like.
        /// Manual updates still work anytime over SSH.
        #[arg(long, default_value_t = false)]
        auto_updates: bool,
        /// Budget for the unattended install's SSH wait, in seconds.
        /// Generous on purpose: a slow host applies the image for hours,
        /// and a *parked* guest is caught separately by the no-I/O stall
        /// watchdog — this only bounds an install that is still moving.
        #[arg(long, default_value_t = windows_headless::timeouts::DEFAULT_INSTALL_SSH_DEADLINE_SECS)]
        install_timeout_secs: u64,
        /// Guest RAM: Docker syntax (`512m`, `4g`; bare digits are MB).
        /// Minimum 2g; Windows 11 setup needs 4g.
        #[arg(long, default_value = "4g", value_parser = windows_headless::sizes::parse_memory_mb)]
        memory: u32,
        /// Guest vCPUs, Docker-style (`--cpus`; `--smp` still works).
        #[arg(long, default_value_t = 4, visible_alias = "smp")]
        cpus: u32,
        /// New-disk size: Docker syntax (`64g`; bare digits are GB).
        /// Minimum 32g.
        #[arg(long, default_value = "64g", value_parser = windows_headless::sizes::parse_disk_gb)]
        disk_size: u32,
        /// Display backend for the install VM (`cocoa` opens a window;
        /// default VNC, same as `run`).
        #[arg(long, default_value = PROVEN_VNC_DISPLAY, value_parser = windows_headless::Display::parse)]
        display: windows_headless::Display,
    },
    /// Graceful shutdown via QMP + pidfile cleanup (no orphans).
    #[command(hide = true)]
    Stop {
        /// VM dir holding `qemu.pid` (default: project cache `vms/win11`).
        #[arg(long)]
        vm_dir: Option<PathBuf>,
        /// QMP endpoint of the running VM (default: next to the disk in
        /// the VM dir — never /tmp).
        #[arg(long)]
        qmp_sock: Option<String>,
    },
    /// Snapshot the running guest as the new golden state (`docker
    /// commit`): proves the shell, stops QEMU, snapshots the disk. Boot
    /// the guest with `run` first; boot again afterward to resume it.
    Snapshot {
        /// VM dir holding the disk (default: project cache `vms/win11`).
        #[arg(long)]
        vm_dir: Option<PathBuf>,
        /// Portable tree override (default: newest cached tree from `fetch-qemu`).
        #[arg(long)]
        qemu_dir: Option<PathBuf>,
        /// Guest username (for the shell proof).
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_USERNAME)]
        username: String,
        /// Guest password (for the shell proof).
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_PASSWORD)]
        password: String,
        #[arg(long, default_value_t = PROVEN_SSH_PORT)]
        ssh_port: u16,
        /// Live snapshot (overlay pivot + RAM migration, guest keeps
        /// running): instant-boot state, experimental.
        #[arg(long, default_value_t = false)]
        live: bool,
    },
    /// Run guest verbs against an already-booted machine (no install,
    /// no boot — just SSH). Connection flags mirror `run`/`install`.
    #[command(hide = true)]
    Guest {
        #[command(subcommand)]
        op: GuestOp,
        /// SSH port (default: proven 2232).
        #[arg(long, default_value_t = PROVEN_SSH_PORT)]
        ssh_port: u16,
        /// Guest username.
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_USERNAME)]
        username: String,
        /// Guest password.
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_PASSWORD)]
        password: String,
    },
}

// Offline helpers: answer-file gen, media build, overlay, classify, report.
#[derive(Subcommand)]
enum ToolingCmd {
    /// Render autounattend.xml to stdout or a vvfat dir.
    #[command(hide = true)]
    Gen {
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_USERNAME)]
        username: String,
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_PASSWORD)]
        password: String,
        #[arg(long, default_value = "en-US")]
        locale: String,
        #[arg(long)]
        autologon: bool,
        #[arg(long)]
        unattend_dir: Option<PathBuf>,
        /// Guest arch (default: host arch). Selects the OpenSSH zip names.
        #[arg(long)]
        arch: Option<Architecture>,
    },
    /// Build the USB installer image from the Windows ISO (pure Rust +
    /// vendored `wimlib-imagex`; no host tools). Output defaults to the
    /// media cache (`install` consumes it).
    #[command(hide = true)]
    BuildMedia {
        /// Windows ISO path.
        #[arg(long)]
        win_iso: PathBuf,
        /// Guest arch (default: host arch — HVF/KVM require host == guest).
        /// Selects the OpenSSH zip, NetKVM driver dir, and answer-file arch.
        #[arg(long)]
        arch: Option<Architecture>,
        /// virtio-win ISO (NetKVM drivers extracted in-crate, pure Rust).
        /// Default: `<iso-cache>/virtio-win.iso` (`setup` fetches it).
        #[arg(long)]
        virtio_iso: Option<PathBuf>,
        /// Pre-extracted driver tree override (dev-time; relative paths
        /// preserved under `drivers/`). Wins over `--virtio-iso`.
        #[arg(long)]
        drivers_dir: Option<PathBuf>,
        /// OpenSSH zip path (offline SSH install; Win64 vs ARM64 by --arch).
        /// Default: `<iso-cache>/<name>` (`setup` fetches it).
        #[arg(long)]
        openssh_zip: Option<PathBuf>,
        /// Output image (default: project cache `media/winusb.dmg`).
        #[arg(long)]
        out: Option<PathBuf>,
        /// Rebuild even when the output image + sidecar already exist.
        #[arg(long, default_value_t = false)]
        force: bool,
        /// `wimlib-imagex` binary (default: `$PATH` lookup; the vendored
        /// release asset once published).
        #[arg(long)]
        wimlib_bin: Option<PathBuf>,
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_USERNAME)]
        username: String,
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_PASSWORD)]
        password: String,
        #[arg(long, default_value = "en-US")]
        locale: String,
    },
    /// Offline overlay: qemu-img create -b base overlay.
    #[command(hide = true)]
    Overlay {
        overlay: PathBuf,
        /// Base image (default: `<vm-dir>/disk.qcow2` — the disk `run` boots).
        base: Option<PathBuf>,
        /// Portable tree root (extracted `qemu-portable` dir); else PATH.
        #[arg(long)]
        qemu_dir: Option<PathBuf>,
    },
    /// Score one PNG through the screen classifier (top-1 + gap + top-3
    /// matches, naming the exemplar). OOD triage: no fixture dir, no
    /// snapshot, nothing blessed.
    Classify {
        /// PNG frame to score.
        png: PathBuf,
    },
    /// Render `tested-isos.jsonl` as a markdown table (stdout, or spliced
    /// into a README between `<!-- TESTED-BEGIN/END -->` markers).
    #[command(hide = true)]
    Report {
        /// Log path (default: `./tested-isos.jsonl`).
        #[arg(long, default_value = windows_headless::provenance::TestRecord::LOG)]
        log: PathBuf,
        /// README to update in place (absent: print table to stdout).
        #[arg(long)]
        readme: Option<PathBuf>,
    },
}

// Provisioning: host setup, build, media/driver fetches, pin verification.
#[cfg(feature = "downloader")]
#[derive(Subcommand)]
enum ProvisionCmd {
    /// One-shot host setup: portable QEMU + portable wimlib + virtio-win
    /// ISO + OpenSSH zip, all into the project cache. After this,
    /// `build-media` needs only `--win-iso` (the user-supplied Windows ISO).
    /// Re-runs are cheap (everything already-cached is skipped).
    #[command(hide = true)]
    Setup {
        /// virtio-win.iso URL override (default: vendored release asset).
        #[arg(long)]
        virtio_iso_url: Option<String>,
        /// Guest arch (default: host arch — HVF/KVM require host == guest).
        /// Selects the OpenSSH zip (Win64 vs ARM64) and NetKVM driver dir.
        #[arg(long)]
        arch: Option<Architecture>,
    },
    /// Build the USB installer image: `setup` (fetch deps) + `build-media`,
    /// then install to a disk with proven defaults, settle, and snapshot the
    /// golden landed state. One command from ISO to snapshot, unattended to
    /// completion (CI takes its first snapshot exactly this way); `run`
    /// connects afterward. Only `--win-iso` is required. Sizing stays
    /// default here (prove it stock first); `install` takes the flags.
    Build {
        /// Windows ISO path.
        #[arg(long)]
        win_iso: PathBuf,
        /// Guest arch (default: host arch — HVF/KVM require host == guest).
        #[arg(long)]
        arch: Option<Architecture>,
        /// Output image (default: project cache `media/winusb.dmg`).
        #[arg(long)]
        out: Option<PathBuf>,
        /// Rebuild even when the output image + sidecar already exist.
        #[arg(long, default_value_t = false)]
        force: bool,
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_USERNAME)]
        username: String,
        #[arg(long, default_value = windows_headless::unattend::DEFAULT_PASSWORD)]
        password: String,
        #[arg(long, default_value = "en-US")]
        locale: String,
    },
    /// Download a portable QEMU release into the project cache.
    #[command(hide = true)]
    FetchQemu {
        /// Release tag (default: pinned, see pins::QEMU_PORTABLE_TAG).
        /// Pass an explicit tag only to test a new build.
        #[arg(long)]
        qemu_tag: Option<String>,
        /// Cache base dir (default: `<project>/.cache/qemu-portable`).
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Proceed even when the release ships no SHA256SUMS.txt (or no
        /// entry for our asset). Fails closed by default; also honored via
        /// $WINDOWS_HEADLESS_ALLOW_UNVERIFIED. Testing new builds only.
        #[arg(long, default_value_t = false)]
        allow_unverified: bool,
    },
    /// Download ISOs into the cache dir, skipping what is already present.
    /// virtio-win.iso comes from our own releases (no Fedora bot-wall);
    /// OpenSSH-ARM64.zip from Microsoft. If Fedora's bot-wall blocks
    /// scripted downloads, fetch the file in a real browser and save it
    /// as `<dir>/virtio-win.iso` (or pass any mirror via --virtio-iso-url)
    /// — `fetch` validates and keeps it.
    #[command(hide = true)]
    Fetch {
        /// Windows ISO URL (fresh, time-limited link from a browser).
        #[arg(long)]
        win_iso_url: Option<String>,
        /// Expected SHA-256 for the Windows ISO (default: none — URLs are
        /// time-limited/rotating, so TLS + ISO magic only; also read from
        /// $WIN11_ISO_SHA256 when the flag is absent).
        #[arg(long)]
        win_iso_sha256: Option<String>,
        /// VirtIO ISO URL override (default: vendored release asset).
        #[arg(long)]
        virtio_iso_url: Option<String>,
        /// Cache dir (default: <project>/.cache/iso or $WINDOWS_HEADLESS_ISO_DIR).
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Expected SHA-256 for virtio-win.iso; re-downloads on mismatch
        /// (default: the release `.sha256` sidecar).
        #[arg(long)]
        virtio_sha256: Option<String>,
        /// Also fetch the OpenSSH zip (Microsoft release asset, per --arch).
        #[arg(long, default_value_t = true)]
        openssh: bool,
        /// Guest arch (default: host arch). Selects the OpenSSH zip.
        #[arg(long)]
        arch: Option<Architecture>,
        /// Re-download even valid cache entries (needed when a time-limited
        /// Windows ISO URL now points at a newer build than the cached file).
        #[arg(long, default_value_t = false)]
        force: bool,
    },
    /// Verify every pinned external artifact (availability + hash) WITHOUT
    /// downloading archives or installing anything. CI-friendly: KBs of
    /// release metadata, plus two ~5 MB OpenSSH zips. Covers ALL platforms
    /// (macos-arm64, linux-x86_64, linux-aarch64) from any single runner —
    /// no per-OS matrix needed. Fails non-zero listing every mismatch so one
    /// run reports everything.
    #[command(hide = true)]
    VerifyPins,
    /// Download a portable wimlib release into the project cache.
    #[command(hide = true)]
    FetchWimlib {
        /// Release tag (default: pinned, see pins::WIMLIB_PORTABLE_TAG).
        /// Pass an explicit tag only to test a new build.
        #[arg(long)]
        wimlib_tag: Option<String>,
        /// Cache base dir (default: `<project>/.cache/wimlib-portable`).
        #[arg(long)]
        dir: Option<PathBuf>,
        /// Proceed even when the release ships no SHA256SUMS.txt (or no
        /// entry for our asset). Fails closed by default; also honored via
        /// $WINDOWS_HEADLESS_ALLOW_UNVERIFIED. Testing new builds only.
        #[arg(long, default_value_t = false)]
        allow_unverified: bool,
    },
}

// Top-level dispatch. Grouped into flattened sub-enums so clap's derived
// `from_arg_matches` stays small per function: one monolithic 16-variant
// enum makes the derive merge every arm's temporaries into a single stack
// frame, which trips clippy's stack-frame lints on unoptimized builds.
// (Plain comment, not a doc comment: `///` here would surface as the
// about-text in `--help`.)
#[derive(Subcommand)]
enum Cmd {
    #[command(flatten)]
    Vm(VmCmd),
    #[command(flatten)]
    Tooling(ToolingCmd),
    #[cfg(feature = "downloader")]
    #[command(flatten)]
    Provision(ProvisionCmd),
}

/// Explicit runtime (not `#[tokio::main]`): `shutdown_timeout` with
/// [`windows_headless::timeouts::RUNTIME_EXIT_GRACE`] abandons leaked
/// blocking threads at exit instead of hanging on them. The leak:
/// every shell-loop iteration drops a pending `stdin.read()` when guest
/// output wins the select race, parking a blocking-pool thread in `read()`
/// forever (observed live: "stopped" prints, process never exits, Ctrl-C
/// mashing goes nowhere). One second of grace, then out.
fn main() -> Result<()> {
    // Tracing → stderr (never stdout: stdout carries no progress protocol,
    // while stderr hosts carriage-return progress bars that stdout logs
    // would tear). INFO by default so fail-closed gates announce themselves;
    // an explicitly-set RUST_LOG wins outright (a blanket INFO directive
    // would otherwise shadow it — directives don't override each other).
    let filter = match std::env::var("RUST_LOG").ok().filter(|v| !v.is_empty()) {
        Some(_) => tracing_subscriber::EnvFilter::from_default_env(),
        None => tracing_subscriber::EnvFilter::from_default_env()
            .add_directive(tracing::Level::INFO.into()),
    };
    let _ = tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_env_filter(filter)
        .try_init();
    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;
    let out = rt.block_on(async_main());
    rt.shutdown_timeout(windows_headless::timeouts::RUNTIME_EXIT_GRACE);
    out
}

async fn async_main() -> Result<()> {
    use std::io::IsTerminal;
    /// Shell default: interactive terminal → shell, piped/CI → supervise.
    /// Explicit `--shell` / `--shell=false` always wins.
    fn want_shell(flag: Option<bool>) -> bool {
        flag.unwrap_or_else(|| std::io::stdin().is_terminal())
    }
    let cli = Cli::parse();
    match cli.cmd {
        #[cfg(feature = "downloader")]
        Cmd::Provision(ProvisionCmd::Build {
            win_iso,
            arch,
            out,
            force,
            username,
            password,
            locale,
        }) => {
            // Full chain with proven defaults: media, then install, settle,
            // golden snapshot — then exit. Never a shell here: `build` must
            // complete unattended (CI takes its first snapshot exactly this
            // way); `run` is the command that connects.
            let media = cmd_build(BuildArgs {
                win_iso,
                arch,
                out,
                force,
                username: username.clone(),
                password: password.clone(),
                locale,
            })
            .await?;
            cmd_install(
                InstallParams {
                    usb_image: Some(media),
                    win_iso: None,
                    screenshots_every_secs:
                        windows_headless::timeouts::DEFAULT_SCREENSHOTS_EVERY_SECS,
                    classify_every_secs: None,
                    username,
                    password,
                    recovery: false,
                    auto_updates: false,
                    install_timeout_secs:
                        windows_headless::timeouts::DEFAULT_INSTALL_SSH_DEADLINE_SECS,
                    memory_mb: 4096,
                    cpus: 4,
                    disk_size_gb: 64,
                    display: windows_headless::Display::Vnc(PROVEN_VNC_DISPLAY.to_string()),
                },
                false,
            )
            .await
        }
        Cmd::Tooling(ToolingCmd::Gen {
            username,
            password,
            locale,
            autologon,
            unattend_dir,
            arch,
        }) => cmd_gen(GenArgs {
            username,
            password,
            locale,
            autologon,
            unattend_dir,
            arch,
        }),
        Cmd::Tooling(ToolingCmd::BuildMedia {
            win_iso,
            arch,
            virtio_iso,
            drivers_dir,
            openssh_zip,
            out,
            force,
            wimlib_bin,
            username,
            password,
            locale,
        }) => {
            cmd_build_media(BuildMediaArgs {
                win_iso,
                arch,
                virtio_iso,
                drivers_dir,
                openssh_zip,
                out,
                wimlib_bin,
                username,
                password,
                locale,
                force,
            })
            .await
        }
        Cmd::Vm(VmCmd::Run {
            disk,
            ssh_port,
            display,
            memory,
            cpus,
            disk_size,
            vm_dir,
            qemu_dir,
            username,
            password,
            shell,
            win_iso,
            install_timeout_secs,
            screenshots_every_secs,
            classify_every_secs,
            live,
        }) => {
            cmd_run(RunArgs {
                disk,
                ssh_port,
                display,
                memory,
                cpus,
                disk_size,
                vm_dir,
                qemu_dir,
                username,
                password,
                shell: want_shell(shell),
                win_iso,
                install_timeout_secs,
                screenshots_every_secs,
                classify_every_secs,
                live,
            })
            .await
        }
        Cmd::Vm(VmCmd::Install {
            usb_image,
            win_iso,
            screenshots_every_secs,
            classify_every_secs,
            username,
            password,
            shell,
            recovery,
            auto_updates,
            install_timeout_secs,
            memory,
            cpus,
            disk_size,
            display,
        }) => {
            cmd_install(
                InstallParams {
                    usb_image,
                    win_iso,
                    screenshots_every_secs,
                    classify_every_secs,
                    username,
                    password,
                    recovery,
                    auto_updates,
                    install_timeout_secs,
                    memory_mb: memory,
                    cpus,
                    disk_size_gb: disk_size,
                    display,
                },
                want_shell(shell),
            )
            .await
        }
        Cmd::Tooling(ToolingCmd::Overlay {
            base,
            overlay,
            qemu_dir,
        }) => cmd_overlay(base, overlay, qemu_dir).await,
        Cmd::Tooling(ToolingCmd::Classify { png }) => cmd_classify(&png),
        Cmd::Vm(VmCmd::Stop { vm_dir, qmp_sock }) => cmd_stop(vm_dir, qmp_sock).await,
        Cmd::Vm(VmCmd::Snapshot {
            vm_dir,
            qemu_dir,
            username,
            password,
            ssh_port,
            live,
        }) => cmd_snapshot(vm_dir, qemu_dir, username, password, ssh_port, live).await,
        Cmd::Vm(VmCmd::Guest {
            op,
            ssh_port,
            username,
            password,
        }) => {
            cmd_guest(GuestArgs {
                op,
                ssh_port,
                username,
                password,
            })
            .await
        }
        Cmd::Tooling(ToolingCmd::Report { log, readme }) => cmd_report(ReportArgs { log, readme }),
        #[cfg(feature = "downloader")]
        Cmd::Provision(ProvisionCmd::Setup {
            virtio_iso_url,
            arch,
        }) => cmd_setup(virtio_iso_url, arch).await,
        #[cfg(feature = "downloader")]
        Cmd::Provision(ProvisionCmd::FetchQemu {
            qemu_tag,
            dir,
            allow_unverified,
        }) => cmd_fetch_qemu(qemu_tag, dir, allow_unverified).await,
        #[cfg(feature = "downloader")]
        Cmd::Provision(ProvisionCmd::Fetch {
            win_iso_url,
            win_iso_sha256,
            virtio_iso_url,
            dir,
            virtio_sha256,
            openssh,
            arch,
            force,
        }) => {
            cmd_fetch(FetchArgs {
                win_iso_url,
                win_iso_sha256,
                virtio_iso_url,
                dir,
                virtio_sha256,
                openssh,
                arch,
                force,
            })
            .await
        }
        #[cfg(feature = "downloader")]
        Cmd::Provision(ProvisionCmd::VerifyPins) => cmd_verify_pins().await,
        #[cfg(feature = "downloader")]
        Cmd::Provision(ProvisionCmd::FetchWimlib {
            wimlib_tag,
            dir,
            allow_unverified,
        }) => cmd_fetch_wimlib(wimlib_tag, dir, allow_unverified).await,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn run_accepts_docker_sizing() {
        // --memory in Docker syntax, --cpus primary, --disk-size in GB syntax.
        let cli = Cli::try_parse_from([
            "wh",
            "run",
            "--memory",
            "8g",
            "--cpus",
            "8",
            "--disk-size",
            "128g",
        ])
        .unwrap();
        let Cmd::Vm(VmCmd::Run {
            memory,
            cpus,
            disk_size,
            ..
        }) = cli.cmd
        else {
            panic!("expected run");
        };
        assert_eq!(memory, 8192);
        assert_eq!(cpus, 8);
        assert_eq!(disk_size, 128);
    }

    #[test]
    fn run_smp_alias_and_defaults() {
        // Legacy --smp still maps to cpus; bare --memory digits are rejected.
        let cli = Cli::try_parse_from(["wh", "run", "--smp", "2"]).unwrap();
        let Cmd::Vm(VmCmd::Run {
            memory,
            cpus,
            disk_size,
            ..
        }) = cli.cmd
        else {
            panic!("expected run");
        };
        assert_eq!((memory, cpus, disk_size), (4096, 2, 64));
        // Bare digits keep the old integer meaning (MB for memory, GB disk);
        // toy sizes hit the floors.
        let cli = Cli::try_parse_from(["wh", "run", "--memory", "4096"]).unwrap();
        let Cmd::Vm(VmCmd::Run { memory, .. }) = cli.cmd else {
            panic!("expected run");
        };
        assert_eq!(memory, 4096);
        assert!(Cli::try_parse_from(["wh", "run", "--memory", "512m"]).is_err());
        assert!(Cli::try_parse_from(["wh", "run", "--disk-size", "8g"]).is_err());
    }

    #[test]
    fn cli_command_invariants() {
        // Unconditional so clap's static assertions (subcommand uniqueness,
        // argument conflicts, help/parser invariants across the flattened
        // hierarchy) run under --no-default-features as well as
        // --all-features — not only in the downloader-gated tests.
        Cli::command().debug_assert();
    }

    #[test]
    fn run_boot_screenshot_cadence_defaults_on() {
        // Boot time-lapse on by default (readable boot, no VNC); 0 opts out.
        // Classification omitted by default: the profile resolves it from
        // the accelerator after detection.
        let cli = Cli::try_parse_from(["wh", "run"]).unwrap();
        let Cmd::Vm(VmCmd::Run {
            screenshots_every_secs,
            classify_every_secs,
            ..
        }) = cli.cmd
        else {
            panic!("expected run");
        };
        assert_eq!(screenshots_every_secs, 60);
        assert_eq!(classify_every_secs, None);
        let cli = Cli::try_parse_from(["wh", "run", "--screenshots-every-secs", "0"]).unwrap();
        let Cmd::Vm(VmCmd::Run {
            screenshots_every_secs,
            ..
        }) = cli.cmd
        else {
            panic!("expected run");
        };
        assert_eq!(screenshots_every_secs, 0);
    }

    #[test]
    fn overlay_takes_bare_overlay_first() {
        // `overlay` (required) precedes `base` (optional): a single
        // positional lands on overlay instead of erroring on a missing one.
        let cli = Cli::try_parse_from(["wh", "overlay", "delta.qcow2"]).unwrap();
        let Cmd::Tooling(ToolingCmd::Overlay { base, overlay, .. }) = cli.cmd else {
            panic!("expected overlay");
        };
        assert_eq!(overlay, PathBuf::from("delta.qcow2"));
        assert_eq!(base, None);
    }

    #[cfg(feature = "downloader")]
    #[test]
    fn build_parses_minimal_args_through_flattened_provision() {
        // The flattened `ProvisionCmd` group parses like the others: only
        // `--win-iso` is required; everything else takes its defaults.
        let cli = Cli::try_parse_from(["wh", "build", "--win-iso", "win.iso"]).unwrap();
        let Cmd::Provision(ProvisionCmd::Build {
            win_iso,
            arch,
            out,
            force,
            username,
            password,
            locale,
        }) = cli.cmd
        else {
            panic!("expected build");
        };
        assert_eq!(win_iso, PathBuf::from("win.iso"));
        assert_eq!(arch, None);
        assert_eq!(out, None);
        assert!(!force);
        assert_eq!(
            (username.as_str(), password.as_str(), locale.as_str()),
            (
                windows_headless::unattend::DEFAULT_USERNAME,
                windows_headless::unattend::DEFAULT_PASSWORD,
                "en-US"
            )
        );
    }
}