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
"""Windows-guest lifecycle for devvm.py: provisioning, reboot, licensing, and interactive-
session-wait logic.
Split out of devvm.py (which keeps the CLI/subcommand glue and Linux-guest logic) because
Windows guests are the only guest kind with anything to license, reboot, or wait for a
session about — Linux guests never touch this module. Imports shared primitives (Guest,
run_vagrant, ...) from devvm_common.py rather than from devvm.py itself, so devvm.py can
import this module without an import cycle.
Most of this module shells out to vagrant/WinRM and is only testable inside a real guest; see
devvm_test.py's module docstring and scripts/README.md. The handful of functions pulled out as
pure logic (should_wait_for_session, parse_reboot_required_marker) are the exception and have
their own unit tests in devvm_test.py.
"""
# Sibling-module import, working whether devvm.py (the only importer of this module) is
# running directly as `__main__` (`uv run scripts/devvm.py ...` puts scripts/ itself on
# sys.path) or loaded as `scripts.devvm` (devvm_test.py's `python -m unittest
# scripts.devvm_test` puts REPO_ROOT on sys.path instead, not scripts/). Inserted
# defensively here too, not just in devvm.py, so this module also imports cleanly if
# something ever imports it before devvm.py has run its own copy of this same snippet.
= .
# Last output line windows-account-and-uac.ps1 prints, telling devvm.py whether an
# EnableLUA/autologon change it just made needs a reboot to take effect (see
# provision_windows_guest).
=
=
# SoftwareLicensingProduct.LicenseStatus: 1 means Licensed. Anything else (5 = Notification is
# what a TIMEBASED_EVAL image reports once its evaluation period elapses, on
# stromweld/windows-10 202503.09.0) means the guest is not currently licensed and needs a
# rearm before it's safe to leave unattended - see ensure_windows_license_current.
= 1
# Rearm proactively within this many minutes of the eval period actually running out, not
# just once it's already hit zero - a guest that dies mid-provisioning run (see
# ensure_windows_license_current's docstring for the incident this is fixing) is worse than
# spending a rearm slightly early. One day's buffer is cheap next to the box's eval window
# (on the order of months) and the two rearms this image ships with.
= 24 * 60
# The human-facing failure bound for reboot_windows_guest_and_wait's post-reboot wait and
# wait_for_windows_session's session wait (reused verbatim by provision_windows_guest for `up`
# or `sync`, whenever this invocation started or rebooted the guest): a guest coming back up, or
# a session appearing, is a genuinely
# external event that might never complete, and this is the same already-configured,
# already-real bound the Windows Vagrantfile itself uses (config.vm.boot_timeout /
# config.winrm.timeout, both 3600s in scripts/devvm/guests/windows-x64/Vagrantfile) — not a
# second, uncoordinated guess.
= 3600
"""Why get_windows_interactive_username found no interactive logon — see that function's
own docstring. devvm.py's cmd_run reports a distinct message per case, rather than
inferring the reason by comparing its own clock against the deadline after the fact (which
both guesses at a cause run_vagrant_winrm_bounded already knows for certain, and races: a
WinRM call that answers just slowly enough can still land after `deadline` has passed even
though it wasn't the timeout that stopped it).
"""
=
=
=
"""Run a Windows provisioning .ps1 script directly over `vagrant winrm`, instead of
through Vagrant's WinRM shell provisioner.
Why: Vagrant's shell provisioner's WinRM path (`provision_winrm` in vagrant 2.4.9's own
plugins/provisioners/shell/provisioner.rb) calls `@machine.guest.capability(:wait_for_reboot)`
UNCONDITIONALLY at the very start of every invocation, before it even uploads the script.
That capability (plugins/guests/windows/cap/reboot.rb, scripts/reboot_detect.ps1) doesn't
just check for a pending reboot — it actively PROBES for one by running a real
`shutdown -f -r -t 60` (a genuine 60-second-out forced restart) and then, if nothing was
already scheduled, immediately `shutdown -a` to cancel it. That is a real, if usually
aborted-in-time, standing restart fuse on every ordinary provisioning step — confirmed via
guest System-log event 1074/1075 pairs lining up with `vagrant provision` runs (see
scripts/README.md's root-cause note). `vagrant winrm -c` never reaches
that capability — confirmed by reading plugins/commands/winrm/command.rb,
communicators/winrm/communicator.rb, and communicators/winrm/shell.rb end to end: none of
them reference `wait_for_reboot` or `reboot_detect` — so driving each script through it
removes the fuse entirely. `-e`/`--elevated` requests the `winrm-elevated` shell type,
matching the shell provisioner's `privileged: true` without going anywhere near
`wait_for_reboot`.
Uploads the script itself via `vagrant upload` (plain WinRM file transfer, no guest
process/command line involved) and runs it with `-File`, rather than inlining its content
as a base64/UTF-16LE `-EncodedCommand`. `-EncodedCommand`'s encoded text becomes part of
the guest-side `powershell.exe` command line, which Windows' CreateProcess caps at 32767
chars total - windows-rust.ps1 alone already encodes to a ~25350-char command line,
comfortably under that limit today but with no margin that's guaranteed to hold as the
script grows, and no PowerShell-side error if it's ever crossed (CreateProcess just fails
on the guest). `-File` sidesteps the limit entirely - the
command line is always the same small, fixed size regardless of script content. The
upload destination is fixed, dedicated scratch space (C:\\Windows\\Temp), deliberately NOT
under C:\\cosca-stage/C:\\cosca: windows-clean-stage.ps1 wipes the former and
windows-mirror-tree.ps1 mirrors-with-deletion into the latter, and either could race an
upload landing there depending on which script is currently running. Env vars are passed
via a `$env:NAME = 'value'; ` prefix ahead of the `-File` invocation.
Returns the combined stdout/stderr so callers (e.g. windows-account-and-uac.ps1's
DEVVM_REBOOT_REQUIRED marker) can scan it. Raises via `run_vagrant_streaming`'s own
check=True on a nonzero exit (and via `run_vagrant`'s own check=True if the upload itself
fails).
"""
= f
=
=
=
+=
, =
return
"""Create a volatile registry key on the guest — one Windows guarantees does NOT survive a
reboot (RegistryOptions.Volatile) — as a reboot-detection marker. Call before issuing the
reboot; reboot_windows_guest_and_wait then polls get_windows_reboot_marker_present for its
absence.
Not a LastBootUpTime comparison: this guest's own clock has been observed to jump by hours
across an ordinary reboot (NTP resync), which would make a wall-clock timestamp comparison
unreliable in either direction.
"""
# $ErrorActionPreference='Stop' plus an explicit trap: PowerShell's default
# ErrorActionPreference is 'Continue', so a failing CreateSubKey (or a failing $k.Close())
# would not by itself stop the script or make it exit nonzero — `vagrant winrm -c` would
# then report success even though no marker was ever created, and
# reboot_windows_guest_and_wait's wait loop would wait out its full deadline for a marker
# that never existed to begin with, misreporting that as "the guest never rebooted" instead
# of "the marker was never set." The trap also writes the caught error before exiting: a
# bare `exit 1` alone would make this fail loudly but silently — `vagrant winrm -c`'s
# nonzero exit would propagate, but without the error text, there's nothing in run_vagrant's
# own failure output to say what actually went wrong.
=
"""Whether set_windows_reboot_marker's key still exists, or None if WinRM isn't answering
right now (the wait loop treats that as "still waiting", not as an answer either way) —
paired with the raw WinRM stdout+stderr, so a caller whose deadline expires while still
getting None can report what the guest was actually saying, not just silence.
Bounded by `deadline` (a time.monotonic() value, the same one reboot_windows_guest_and_wait
already computes from WINDOWS_REBOOT_DEADLINE_SECONDS) via run_vagrant_winrm_bounded — see
its docstring for why a plain `timeout=` isn't safe here.
"""
=
= +
return None,
=
return False,
return True,
return None,
"""Whether `HKLM:\\...\\Winlogon`'s `AutoAdminLogon` is already `1` on the guest right now,
or None if WinRM isn't answering or gave an answer that isn't the explicit SET/UNSET this
prints (the same "don't guess, retry" contract as get_windows_reboot_marker_present) —
paired with the raw WinRM stdout+stderr, for the same reason.
windows-account-and-uac.ps1 is the only thing that sets it, and the value persists across
reboots once set — so this is `True` on any guest that has completed account/UAC
provisioning at least once, even on an `up` that doesn't run that script again.
provision_windows_guest uses this to know whether to wait for an interactive session
before returning, on a guest where autologon was already configured by an earlier `up`.
Bounded by `deadline` (a time.monotonic() value, the caller's own session-wait deadline) via
run_vagrant_winrm_bounded — see its docstring for why a plain `timeout=` isn't safe here.
"""
=
= +
return None,
=
return False,
return True,
return None,
"""The domain-qualified name of the guest's autologon account ("vagrant") if it currently
has a live interactive logon anywhere, paired with `None` for the failure and the raw
WinRM stdout+stderr — or, if it doesn't yet or WinRM isn't answering, `None` for the
username paired with an InteractiveLookupFailure saying which of the three distinct cases
happened (see that enum's own docstring) and the raw output. Used by
wait_for_windows_session to confirm autologon has actually produced a real interactive
session — the thing windows-run-unelevated.ps1's scheduled task borrows a filtered token
from — not just that the kernel has finished booting.
The owner of a running `explorer.exe` (the desktop shell itself) is used rather than
`Win32_ComputerSystem.UserName` (goes blank the moment an RDP logon takes over the console
session, even though the account is still genuinely logged in) or
`Win32_LoggedOnUser`/`Win32_LogonSession` (stays stale after a sign-out instead of
reflecting it): a live desktop shell needs no logon-type enumeration to be
session-type-agnostic across console, RDP, and cached logons, and is proof enough of an
active session on its own. Filtered to the owning account so an explorer.exe belonging to a
different user already logged onto the same box can't be mistaken for 'vagrant's own
session.
devvm.py's cmd_run passes the result of this through as -InteractiveUser to
windows-run-unelevated.ps1, which does not run this WMI query itself — see that script's own
$currentUser assignment.
Bounded by `deadline` (a time.monotonic() value) via run_vagrant_winrm_bounded — see its
docstring for why a plain `timeout=` isn't safe here.
"""
=
=
= +
return None, ,
return None, ,
=
return None, ,
return , None,
"""Raise if the guest is no longer 'running' per vagrant, or if `deadline` (a
time.monotonic() value) has passed. Shared by reboot_windows_guest_and_wait's wait loop and
wait_for_windows_session's wait loop so a powered-off/crashed guest fails immediately
instead of retrying WinRM forever, and so both loops fail on the same kind of monotonic
bound (each call site passes its own `deadline`, not necessarily tied to a reboot).
`last_output`, if given, is the raw stdout+stderr from the loop's most recent WinRM check —
included in the deadline error so a human debugging a timeout sees what the guest was
actually saying right before giving up, not just the bare "didn't finish within Ns."
"""
=
=
+= f
"""Block until the guest reports a real interactive (autologon) session on the console
(session 1) — the thing windows-run-unelevated.ps1's scheduled task needs to borrow a
filtered token from — or `deadline` (a time.monotonic() value) passes.
A reboot's own marker clearing as soon as the kernel finishes booting can still be ahead
of autologon actually producing that session. Callers that know a session is coming (a
reboot that just configured autologon, or a guest that already has autologon configured)
call this explicitly instead of letting the next unelevated probe race it.
No `time.sleep()`: each iteration is a real WinRM round-trip, and failure just means "ask
again immediately," not "nap, then ask again." Bounded by `deadline` and by
`_require_guest_running` failing fast the moment `vagrant status` reports the guest isn't
running any more.
"""
=
, , =
return
"""Issue a real guest reboot ourselves and block until the guest reports the reboot
actually happened: set_windows_reboot_marker's marker, set before the reboot, has gone
missing after it.
Says nothing about sessions. A reboot completing is not the same as autologon having
produced a real interactive session on top of it — callers that need one call
wait_for_windows_session themselves afterward, under their own deadline.
provision_windows_guest calls wait_for_windows_session conditionally — only when this
invocation started or rebooted the guest (and, even then, only if
get_windows_autologon_configured says autologon is set) — once, at the end of its own
provisioning flow. See provision_windows_guest's own comment for why only that invocation,
not merely "autologon is configured" or `create`, is the right gate.
Deliberately does NOT go through Vagrant's named `reboot-if-needed` shell provisioner /
`Reboot.reboot` capability: that path is itself a shell provisioner, so it still runs
through `provision_winrm`'s unconditional `wait_for_reboot` fuse first, and its own
`wait_for_reboot` wait loop (plugins/guests/windows/cap/reboot.rb) is a `sleep 10` poll on
top of that same reboot_detect.ps1 probe. Issuing `shutdown /r` directly (the same command
`Reboot.reboot` itself runs, confirmed by reading cap/reboot.rb) and then waiting for the
reboot marker to clear avoids both.
`shutdown /r /t 0`'s own exit code is NOT trusted as a pass/fail signal: a `/t 0` shutdown
tears down the guest (and its WinRM connection) essentially immediately, so `vagrant winrm`
can report a nonzero exit purely because the connection dropped out from under it
mid-response — not because the reboot failed to schedule. The
wait loop below is the real check that the reboot actually happened; a nonzero exit here
is logged but does not abort early on its own.
No `time.sleep()`, and no chosen retry interval of devvm.py's own: each iteration IS the
wait — a real WinRM round-trip or a real `vagrant status` query — and failure just means
"ask again immediately," not "nap, then ask again." The loop is bounded by one monotonic
deadline (WINDOWS_REBOOT_DEADLINE_SECONDS, reusing the Windows Vagrantfile's own 3600s
boot_timeout/winrm.timeout — a real, already-configured, human-facing failure bound for a
guest reboot genuinely never completing) and by `_require_guest_running` failing fast the
moment `vagrant status` reports the guest isn't running any more, instead of retrying
`vagrant winrm` in a tight loop against a guest that is never answering again (a powered-off
or crashed guest would otherwise burn a host core forever, since `vagrant winrm` itself has
no readiness wait — see get_windows_reboot_marker_present's docstring).
"""
=
= +
=
, =
return
"""Read the guest's Windows license status via WMI/CIM: (LicenseStatus,
GracePeriodRemaining in minutes, RemainingWindowsReArmCount).
Reads the same underlying data `slmgr.vbs /dlv` prints, but structured: no parsing of
slmgr's free-text human-readable output, just the WMI properties behind it
(SoftwareLicensingProduct for the active product entry - the one with a non-null
PartialProductKey - and SoftwareLicensingService for the rearm counter).
"""
=
, =
: =
, =
=
return
"""Rearm the guest's time-based Windows evaluation license if it's expired or within
WINDOWS_LICENSE_NEAR_EXPIRY_MINUTES of expiring, then reboot for the rearm to take effect.
Returns whether it rebooted the guest — provision_windows_guest seeds its own `rebooted`
from this, so the license-rearm reboot (this function's own, distinct from the
windows-account-and-uac.ps1 reboot, which can still set `rebooted = True` again later) also
counts toward the post-provisioning session-wait gate instead of being invisible to it.
Why this exists: the stromweld/windows-10 box's eval image self-terminates once its
evaluation period elapses - the Windows License Manager Service (wlms.exe) issues a
genuine guest-initiated ACPI power-off (System event log ID 1074), not a devvm.py/cosca
command or a crash, ending the whole QEMU process with only a few seconds' warning. It has
taken the guest down mid-provisioning.
Runs on every `up` (create is always True in devvm.py's cmd_up's own call into
provision_windows_guest - `vagrant up` is itself idempotent, so this runs whether the guest
is being created for the first time or merely started again), not on every `sync` -
because Windows evaluation rearms are a limited, consumable resource (this image ships
with 2), not something to spend on every provisioning pass; `sync` (create=False) never
reaches this function at all.
Direct `vagrant winrm -c` (no `-e`/elevated shell) is enough for `slmgr /rearm`, the same
as `reboot_windows_guest_and_wait`'s `shutdown /r`: this box already hands WinRM sessions a
full, unfiltered High-integrity token (LocalAccountTokenFilterPolicy=1 - see devvm.py's
cmd_run comment on the same fact), so no separate elevation request is needed for a
privileged operation issued over WinRM.
"""
, , =
= != or <
return False
# Session-waiting, if needed, happens once at the end of provision_windows_guest (via this
# function's return value, ORed into that gate) — this reboot can run before
# windows-account-and-uac.ps1 has ever configured autologon, on a genuinely fresh box, so
# waiting for a session here unconditionally could hang the full
# WINDOWS_REBOOT_DEADLINE_SECONDS for no reason.
, , =
return True
"""Parse windows-account-and-uac.ps1's own DEVVM_REBOOT_REQUIRED=0/1 marker out of its
combined WinRM output (see REBOOT_MARKER_TRUE/REBOOT_MARKER_FALSE). True/False mirror the
marker's own claim; None means neither marker string appeared at all — a bug in the
provisioner script, not something to silently proceed past. If both somehow appear, True
wins, matching this function's caller checking REBOOT_MARKER_TRUE first. Pulled out as its
own pure function, mirroring should_wait_for_session below, so this parsing has a unit test
independent of a live guest.
"""
return True
return False
return None
"""Whether provision_windows_guest's own invocation just produced a fresh boot, and so
should wait for a real interactive (autologon) session before returning — see that
function's session-wait comment for the full reasoning (AutoAdminLogon only fires a fresh
logon at boot; merely "autologon is configured" is not itself such an event). Pulled out as
its own pure function so this decision has a unit test independent of a live guest.
"""
return or
"""Create (if `create`) and/or provision a Windows guest, driving each provisioning
script directly over `vagrant winrm` (see run_windows_script) instead of Vagrant's WinRM
shell provisioner — see that function's docstring for why.
Order matches the original Vagrantfile-declared provisioner order exactly, since later
steps depend on earlier ones: windows-clean-stage.ps1 must run before the "file"
provisioner (still Vagrant-driven — plugins/provisioners/file/provisioner.rb is confirmed
clean of any wait_for_reboot call, so there's no reason to reimplement WinRM file upload
by hand) re-populates C:\\cosca-stage; windows-mirror-tree.ps1 and windows-lock-tree.ps1
depend on that upload; windows-account-and-uac.ps1 and windows-rust.ps1 are independent of
each other but both come last, with rust installed before the reboot-required check below
is acted on.
The license-rearm check (create only) runs before every other provisioning step,
including windows-clean-stage.ps1: an expired-eval shutdown can land mid-step regardless
of which step it is (it has hit during windows-lock-tree.ps1), so there's
no later step that's actually safer to run first - checking immediately, before spending
any time on the rest, is strictly better than finding out partway through.
"""
# Whether THIS invocation is the one that actually started the guest (as opposed to `up`
# finding it already running and doing nothing) — see the session-wait gating at the
# bottom of this function for why that distinction, not merely `create`, is what matters.
= False
# Set from ensure_windows_license_current's return value below (create only), so a reboot
# the license rearm causes counts toward the session-wait gate exactly like the
# windows-account-and-uac.ps1 reboot does.
= False
= !=
# --no-provision: a fresh `up` would otherwise auto-run the one remaining
# Vagrantfile-declared provisioner (the "file" upload) as part of creation, and then
# the explicit `vagrant provision` call two lines down would run it a second,
# redundant time. Skipping it here makes exactly one invocation happen either way
# (create or not), driven explicitly below.
=
# The lone remaining Vagrantfile-declared provisioner: uploads the staged tree into
# C:/cosca-stage. `run: "always"` on it means a plain `vagrant provision` re-runs it every
# time.
=
=
= True
# A real interactive (autologon) session may not exist yet the moment this returns, and
# windows-run-unelevated.ps1's scheduled task needs one to borrow a filtered token from —
# but AutoAdminLogon (without ForceAutoLogon, which this tool does not set) only fires a
# fresh logon at BOOT. So waiting for one is only ever correct when THIS invocation is what
# just produced a boot: either it started the guest itself (`started_guest`, only ever True
# under `create`) or it rebooted the guest — via the license rearm above (create-only) or via
# the windows-account-and-uac.ps1 reboot just above, which `sync` can trigger too
# (create=False): that script re-runs on every `sync`, and can still decide a reboot is
# needed. Merely "autologon is configured" (true on every subsequent `up`/`sync` once
# windows-account-and-uac.ps1 has ever succeeded, regardless of whether a human RDP'd in and
# signed out since) is not such an event — waiting on that alone would block for up to
# WINDOWS_REBOOT_DEADLINE_SECONDS for a session that will not spontaneously reappear.
# `run --unelevated` needs no proactive wait either — devvm.py's cmd_run's own
# get_windows_interactive_username call already fails immediately when there is no session
# to borrow.
#
# No `create` gate: `sync` (create=False) can also reboot the guest via
# windows-account-and-uac.ps1, and needs the same wait `up` does.
# A None (WinRM not answering this particular check yet, even though every script above
# just succeeded over it) is retried, not guessed at or treated as fatal on the first
# occurrence — the same "ask again immediately, fail only once the guest is gone or the
# deadline passes" contract wait_for_windows_session and reboot_windows_guest_and_wait's
# own loops use, via the same _require_guest_running and one shared deadline (also
# reused below for wait_for_windows_session itself, if it turns out to be needed).
= +
=
, =
break