cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
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
# devvm — throwaway VMs for local system-affecting tests

cosca's subject matter — elevation, cgroups, Windows Job Objects, process trees — means its
most interesting tests change real system state: cgroups and cgroup leaves, Job Objects,
elevation and `ShellExecuteEx`, process trees, process-group signals, `pidfd`/`kqueue` waits
and reaping all reach outside a single process. **Those tests must never run against your own
machine.** `scripts/devvm.py` provisions throwaway VMs for that purpose, so the blast radius
of a scratch script bug is a disposable VM, not your laptop.

The only exemption is a test that spawns this repo's own short-lived children and signals them
only through the `Child` handle cosca returned for each, before that handle reaps the child;
process-group and session signals, PIDs the test computed, and tree teardown are not exempt.
macOS and Windows lanes run on CI. See
[principle 10](../docs/principles.md#10-system-affecting-tests-run-in-a-sandbox).

This is developer tooling, not shipped code and not a CI replacement — CI keeps the
regression probes; this is for the tests CI structurally cannot run (see
[Windows guests](#windows-guests) below).

## Prerequisites

Install on the host yourself — this tool does not install anything for you:

- [QEMU]https://www.qemu.org/: `brew install qemu`
- [Vagrant]https://www.vagrantup.com/: `brew install --cask hashicorp-vagrant` (the
  Homebrew cask; the Vagrant.app installer works too)
- The [vagrant-qemu]https://github.com/ppggff/vagrant-qemu plugin, pinned to exactly the
  version `fix_qemu_loopback_only.rb` is verified against (see that file's own comment for
  why an "equivalent" provider or a different version isn't a safe substitute here):
  `vagrant plugin install vagrant-qemu --plugin-version 0.6.3`
- `rsync` (ships with macOS)
- [`uv`]https://docs.astral.sh/uv/: `brew install uv` — runs `devvm.py` without a separate
  install step

Verify with `vagrant plugin list` (expect `vagrant-qemu`) and
`qemu-system-x86_64 --version` / `qemu-system-aarch64 --version`.

## Usage

```sh
uv run scripts/devvm.py list
uv run scripts/devvm.py up linux-x64
uv run scripts/devvm.py run linux-x64 -- cargo --version
uv run scripts/devvm.py ssh linux-x64
uv run scripts/devvm.py sync linux-x64      # after local changes, before the next `run`
uv run scripts/devvm.py halt linux-x64      # shut down, keep the disk
uv run scripts/devvm.py destroy linux-x64   # delete the VM and its state entirely
```

`run` executes one command; anything after `--` is passed through verbatim, e.g.:

```sh
uv run scripts/devvm.py run linux-x64 -- cargo test --features pty
```

Always `destroy` (or at least `halt`) guests you're done with — nothing here auto-expires a
running VM.

**On a Windows guest, `run`'s own exit code only distinguishes success from failure, not the
command's actual exit code.** Both the direct and `--unelevated` routes go through
`vagrant winrm -c`, which collapses any nonzero remote exit code to exactly `1` — the real
value doesn't survive to `devvm.py`'s own process exit. When the command itself actually ran
and returned nonzero, the guest-side script prints the real code (`devvm: command exited N`)
into the output `devvm.py` relays before it exits 1 — look for that line rather than relying
on the shell's `%ERRORLEVEL%`. That line is specific to a command that ran to completion: it
does not appear on either of `--unelevated`'s two other, deterministic failure paths, which
print their own diagnostic instead — a trap-caught error if `--unelevated` itself fails before
the command ever runs (e.g. no interactive session to borrow, or a Task Scheduler RPC that
never completes), or, if the command runs past `--timeout` while executing, the wrapper's own
"did not finish within its deadline" message. Linux guests use `vagrant ssh -c` instead, which
forwards the remote command's real exit code as-is.

## Guests

| Guest           | Box                                      | Provider arch | Host arch it's native on |
| --------------- | ---------------------------------------- | ------------- | ------------------------ |
| `linux-x64`     | `cloud-image/ubuntu-24.04` (qemu, amd64) | x86-64        | x86-64                   |
| `linux-arm64`   | `perk/ubuntu-24.04-arm64` (qemu, arm64)  | arm64         | arm64 (Apple Silicon)    |
| `windows-x64`   | `stromweld/windows-10` (qemu, amd64)     | x86-64        | x86-64                   |
| `macos-arm64`   | Tart, `macos-tahoe-base` (Cirrus)        | arm64         | arm64 (Apple Silicon)    |
| `windows-arm64` | _(none — see below)_                     | —             | —                        |

Both Linux boxes run Ubuntu 24.04; systemd 255 there defaults to the unified cgroup v2
hierarchy, which is why they're the guests for cosca's cgroup lanes, and its polkit (124) reads
JavaScript rules, so the ELEVATION group's Linux tests run in them (see
[Unattended GUI elevation](#unattended-gui-elevation)). Provisioning installs `polkitd`, `pkexec`
and `opendoas` for that.

Each Vagrant guest's box, version and sha512 are pinned in its `box.json`, which the Vagrantfile
uses as `box_url`: Vagrant checks a download only against the checksum in the metadata it was
added from, so a pin in the Vagrantfile, or a box named from the catalog, would go unchecked. A
box already in `~/.vagrant.d/boxes` is reused without being hashed again, so after changing a
pin run `vagrant box remove <old box name>` (`vagrant box list` shows the names).

On the emulated architecture, QEMU falls back to TCG (software emulation) instead of
HVF/KVM, which is dramatically slower — see [Windows guests](#windows-guests) for measured
numbers on this host.

### `macos-arm64`

A throwaway macOS 26 (Tahoe) arm64 VM via [Tart](https://tart.run), for fast local macOS
RED/GREEN iterations and pre-checks. **CI stays the merge gate.** The image is Cirrus Labs'
`ghcr.io/cirruslabs/macos-tahoe-base`, not GitHub's `macos-latest` runner image: same macOS
major (26) and arm64 as CI's `darwin/arm64` lane, but different preinstalled tools and no Xcode.

Prerequisites: Tart (`brew install cirruslabs/cli/tart`, or the release tarball), found via
`$TART` or `PATH`; and the base image pulled once, about 30 GB (`tart pull
ghcr.io/cirruslabs/macos-tahoe-base@sha256:<digest>`; check free disk first).

```sh
uv run scripts/devvm.py up macos-arm64 [--rev <git rev>] [--rosetta]   # clone, boot headless, copy `git archive <rev>`, provision
uv run scripts/devvm.py run macos-arm64 -- cargo nextest run --lib -E 'test(/await_reapable/)'
uv run scripts/devvm.py run macos-arm64 -- sudo -n env PATH=/Users/admin/.cargo/bin:/usr/bin:/bin:/usr/sbin:/sbin CARGO_HOME=/Users/admin/cargo-home-root CARGO_TARGET_DIR=/Users/admin/cargo-target-root RUSTUP_HOME=/Users/admin/.rustup cargo nextest run --locked ...   # root lane
uv run scripts/devvm.py sync macos-arm64 --rev <rev>                  # replace the guest's source with another rev
uv run scripts/devvm.py fetch macos-arm64 '~/cargo-target/nextest' ./out   # copy results out; absolute or ~/ paths, quote the ~
uv run scripts/devvm.py destroy macos-arm64                           # stop and delete the VM
```

- Each worktree has one guest, a fresh copy-on-write clone of the base; the base is never
  modified. A failed `up` deletes its clone and exits 1. An interrupted one (SIGINT, SIGTERM or SIGHUP, once or repeatedly) does the same and exits 128+signal; a signal
  ignored on entry (`nohup`) stays ignored; a signal that arrives after `up` or `destroy` finished still gives the 128+signal exit code. If the deletion fails, the state is kept and the message names the VM and points to `destroy`.
- `destroy` deletes only the VM this worktree created and refuses anything it cannot verify.
  There is no `halt`: destroy the guest and `up` a new one.
- At most 2 macOS VMs run at once on a Mac (Apple's licence); `up` counts every running local
  Tart VM and refuses a third.
- Only committed state is copied (`git archive <rev>`). The provision script always comes from
  this checkout, so `--rev` may name an older commit.
- Root-lane runs use their own `CARGO_HOME` and `CARGO_TARGET_DIR` (recipe above, with
  `--locked`), so `sync` and unprivileged builds keep working afterwards.
- CI's `darwin/amd64` lane is also arm64 plus Rosetta (a `macos-15` runner building
  x86_64), so `--rosetta` matches its mechanism; the macOS major differs (26 versus 15). The
  base already ships Rosetta; the flag ensures it and adds the `x86_64-apple-darwin` target for
  `cargo nextest run --target x86_64-apple-darwin`.
- The base image is pinned by digest; Renovate moves `BASE_IMAGE_DIGEST` in
  `scripts/devvm_macos.py`, after which pull the new digest.
- Host-side tests, run by CI's Lint job: `python3 -m unittest scripts.devvm_macos_gate_test scripts.devvm_macos_gateio_test scripts.devvm_macos_tart_test scripts.devvm_test scripts.devvm_macos_test scripts.devvm_macos_signals_test scripts.devvm_macos_realtart_test`. A regression fails a test by assertion rather than hanging it, in any module order.

### `windows-arm64`

No publicly available Vagrant box for Windows on arm64 targets the `qemu` or `libvirt`
provider this tool uses (checked 2026-09-23 on Vagrant Cloud — every arm64 Windows box found
there ships only `parallels`/`vmware_desktop`/`utm`). `devvm.py` refuses this guest with that
explanation rather than silently doing nothing useful.

If you need this lane: build a qcow2 image yourself from a Windows-on-ARM evaluation VHDX
(Microsoft ships these for Windows 11 ARM64) and point `qe.image_path` at it in a new
`scripts/devvm/guests/windows-arm64/Vagrantfile` (see the vagrant-qemu README's "local
qcow2" example) — this tool has no automation for that conversion.

### Windows guests

**Licensing.** `stromweld/windows-10` is a "vanilla Windows 10" box built with
[Bento](https://github.com/chef/bento) from Microsoft's free evaluation media. Evaluation
Windows installs activate on a timer and _expire_ (Windows 10 Enterprise eval is commonly 90
days from the image's build date) — and expiry is not benign: once the eval period elapses,
`wlms.exe` (Windows License Manager Service, running as `NT AUTHORITY\SYSTEM`) issues a real
ACPI shutdown on its own (guest System-log event 1074, "The license period for this
installation of Windows has expired. The operating system is shutting down."), which takes
the whole QEMU process down with it — mid-provisioning, if that's when it fires, with no
crash report on the host side.

`devvm.py up` guards against this itself: on every `up` (not on `sync` or a plain `provision`
against an existing guest, which never reach this check — evaluation rearms are a limited,
consumable resource, not something to spend every pass), before any other provisioning step,
it reads the guest's license state via WMI
(`SoftwareLicensingProduct.LicenseStatus`/`GracePeriodRemaining`,
`SoftwareLicensingService.RemainingWindowsReArmCount` —
`get_windows_license_state`/`ensure_windows_license_current` in `scripts/devvm_windows.py`; no
parsing of `slmgr`'s free-text output). If the license is expired or within a day of
expiring, it runs `slmgr /rearm` and reboots (via `reboot_windows_guest_and_wait`) for the
rearm to take effect, then re-checks via WMI and fails loudly if the license still isn't
current. `stromweld/windows-10` 202503.09.0 ships with 2 rearms; once those are spent,
`devvm.py` refuses to proceed with a clear error rather than silently leaving a guest that
can die mid-run — at that point the fix is bumping the box in
`scripts/devvm/guests/windows-x64/` (the `config.vm.box` name and `box.json`) to a newer
build, not disabling activation checks. This is throwaway dev tooling; don't rely on this VM outliving a single
investigation.

**No Vagrant shell provisioner — a real restart fuse, removed.** `windows-x64`'s Vagrantfile
declares exactly one provisioner (the WinRM `file` upload). Every other Windows provisioning
step (`windows-clean-stage.ps1`, `windows-mirror-tree.ps1`, `windows-lock-tree.ps1`,
`windows-account-and-uac.ps1`, `windows-rust.ps1`) is driven directly by `devvm.py` over
`vagrant winrm` (`provision_windows_guest`/`run_windows_script` in `scripts/devvm_windows.py`), not
through Vagrant's `config.vm.provision "shell", ...`. This was a deliberate fix, not a style
choice: vagrant 2.4.9's shell-provisioner WinRM path (`provision_winrm`) calls the guest's
`wait_for_reboot` capability **unconditionally**, at the start of every single shell-
provisioner invocation, before it even uploads the script. That capability's actual "is a
reboot pending?" test (`reboot_detect.ps1`, vendored inside the `vagrant` gem) doesn't just
check — it _schedules a real forced restart_ (`shutdown -f -r -t 60`) and then, if nothing was
already pending, immediately cancels it (`shutdown -a`). That's a genuine, if normally
self-cancelled, 60-second restart fuse on every ordinary `up`/`sync`, once per shell provisioner.
Every
`vagrant provision` against this guest produced a matching guest System-log event 1074
("wininit.exe has initiated restart") followed by event 1075 ("aborted") — the owner watching
the guest's console twice saw the real "you're about to be signed out" sign-off splash flash
during an otherwise-ordinary `devvm.py sync`, which is exactly what a scheduled-then-cancelled
restart looks like from the console. `vagrant winrm -c` (with or without `-e`/`--elevated`)
never reaches that capability — confirmed by reading vagrant's
`plugins/commands/winrm/command.rb` and `plugins/communicators/winrm/{communicator,shell}.rb`
end to end — so driving each script that way removes the fuse entirely. The one legitimate
reboot this guest ever needs (`EnableLUA`/autologon changes only take effect at the next boot)
is issued and waited on directly by `reboot_windows_guest_and_wait` in `scripts/devvm_windows.py` (a
real `shutdown /r`, then a bounded wait for a volatile registry marker — set before the
reboot, guaranteed by Windows not to survive one — to clear). Separately,
`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` reports autologon is set) — once, at the end of
provisioning. `sync` (which never starts the guest) can still trigger this: if
windows-account-and-uac.ps1 decides a reboot is needed, `sync` waits for the session that
reboot just invalidated, the same as `up` would. Merely having autologon already configured
from an earlier run is not enough on its own to wait — an RDP sign-out elsewhere, for
instance, must never turn the next `sync`/`up` into a silent up-to-an-hour wait for a session
that was never going away. Both waits: no `sleep`, no arbitrarily-chosen poll interval, just an
immediate retry, bounded by `vagrant status` failing fast the moment the guest stops running
and by one monotonic deadline reusing the Vagrantfile's own 3600s
`boot_timeout`/`winrm.timeout`. Neither goes through Vagrant's own
`reboot-if-needed`/`Reboot.reboot` capability, which carries the exact same fuse plus its own
`sleep 10` wait loop. `vagrant winrm -c` itself has no readiness wait of its own (same source
read as above), which is why these wait loops need their own deadline rather than relying on
one baked into `vagrant winrm`.

**Account and UAC.** The box's default `vagrant` account is an ordinary `Administrators`
member — not the built-in Administrator (SID ending `-500`), which Windows elevates
_without_ a UAC prompt regardless of settings. Every `up`/`provision` run verifies this (and
fails loudly, not silently, if it's ever untrue) and resets UAC (`EnableLUA`) to on, via
`scripts/devvm/provision/windows-account-and-uac.ps1`.

By default, `runas` elevation prompts for consent exactly like a real desktop
(`ConsentPromptBehaviorAdmin=5`, the Windows default). For unattended probe runs where a
human isn't there to click through the prompt, pass `--allow-elevation` to `up`:

```sh
uv run scripts/devvm.py up windows-x64 --allow-elevation
```

This sets `ConsentPromptBehaviorAdmin=0` (auto-approve, still logged, UAC still nominally
on) — **opt-in only**, never the default, and the tool prints a note every time it's active.

**Headless by default, and how `run --unelevated` measures the real UAC path anyway.** The
guest boots with no display (`-display none`, vagrant-qemu's default) and is normally reached
over WinRM/PowerShell remoting. A WinRM session is a network logon in session 0 with (this
box has `LocalAccountTokenFilterPolicy=1`) a full, unsplit High-integrity token — so a probe
run over plain `devvm.py run`/`ssh` that calls `ShellExecuteExW("runas")` already has full
rights and elevates trivially, measuring elevated-to-elevated, not the real desktop
unelevated-user-clicks-through-UAC path this guest exists to probe.

`devvm.py run <guest> --unelevated -- <cmd>` (Windows only) measures the real path instead,
with no display or UI automation needed: `scripts/devvm/provision/windows-account-and-uac.ps1`
configures the `vagrant` account to autolog in at boot, giving the guest a genuine active
interactive (session 1, console) logon; `windows-run-unelevated.ps1` then runs the command via
a scheduled task (`Register-ScheduledTask` with a `New-ScheduledTaskPrincipal -LogonType
Interactive -RunLevel Limited` principal), which borrows that logon's actual filtered token
at the LIMITED (non-elevated) run level even though the account is itself an Administrators
member.
Combined with `--allow-elevation` (`ConsentPromptBehaviorAdmin=0`), a `runas` child launched
from that probe takes the consent path with no click required. Verify this is measuring what
it claims to by running the probe's own integrity check:

```sh
uv run scripts/devvm.py run windows-x64 --unelevated -- whoami /groups
```

Look for `Mandatory Label\Medium Mandatory Level` in the output — that's the unelevated probe
itself, not a `runas` child. To confirm a `runas`-elevated child of that probe actually reaches
High integrity, run the same command against a script that shells out via `runas`/
`ShellExecuteEx` and checks its own `whoami /groups`; look for `Mandatory Label\High Mandatory
Level` in its output instead.

**A `--unelevated` command that itself starts `powershell.exe` is fine — the wrapper already
routes around a PowerShell 5.1 quirk for you.** PowerShell 5.1 parses a native child's stderr
through its own stream reader regardless of the redirection operator used (`*>`, `2>&1`, even a
plain `2>` alone) or `-OutputFormat`, and treats a `#< CLIXML` prefix (written by a nested
non-interactive powershell.exe with redirected output) as serialized records to deserialize —
throwing `Cannot process the XML from the 'Error' stream of '...': Data at the root level is
invalid` if what follows isn't well-formed CLIXML. `windows-run-unelevated.ps1` avoids this by
running the caller's command as a `cmd.exe` child (via
`[System.Diagnostics.Process]::Start`, not PowerShell's `Start-Process` —
`Start-Process -PassThru`, without `-Wait`, leaves `.ExitCode` unreadable even after
`WaitForExit()` returns) with `cmd.exe`'s own `1>`/`2>` redirection to files: those are real
OS-level file handles `cmd.exe` opens itself, so PowerShell's stream reader never sees the
stream. The actual command text is written to a file first and run via `-File`, not passed
inline on `cmd.exe`'s command line — `cmd.exe` caps its own command line at roughly 8191
characters, well under what a longer command can reach once encoded. If you write your own
variant of this wrapper, or invoke `powershell.exe`/`pwsh.exe` as a direct child of another
PowerShell process elsewhere in this tooling, use the same `cmd.exe`-redirection-to-a-file
approach rather than a PowerShell redirection operator or `Start-Process`.

If a probe genuinely needs a human (or UI automation) to see and answer the secure-desktop
prompt itself — rather than just observing its outcome — give the guest a display instead:

```sh
uv run scripts/devvm.py up windows-x64 --display
```

This opens a real, local QEMU window on this Mac (`-display cocoa -vga std`) — not VNC or any
other network-exposed display, so it doesn't touch the loopback-only port-forwarding guarantee
above. Off by default; pass it again on every `up` that needs it (not persisted). RDP into the
guest is the other option if a window on this Mac specifically isn't what's needed.

RDP-ing into `vagrant` takes over its console (session 1) logon rather than opening a second,
independent one — the account stays genuinely logged in, and both the session-wait `sync`/`up`
conditionally run (see below) and `run --unelevated` detect that logon by its running
`explorer.exe`'s ownership, not `Win32_ComputerSystem.UserName`
(which goes blank the moment RDP takes the console over) and not `Win32_LoggedOnUser`/
`Win32_LogonSession` (live-verified stale after a genuine sign-out — see
`get_windows_interactive_username`'s docstring), so both keep working through an active RDP
session. Signing out of RDP elsewhere doesn't make the next `sync`/`up` sit waiting for a fresh
session either: that wait only runs when this invocation itself started or rebooted the
guest, never merely because a session might currently be missing. If `run --unelevated`'s
scheduled task still fails to run — the account is logged on but its session is _disconnected_, not merely
redirected, e.g. an RDP client that was closed without logging off — the error names this and
gives the recovery: from inside the guest, `query session` lists session IDs and `tscon <id>
/dest:console` reattaches a disconnected session to the console; otherwise reboot the guest.

**If a `run --unelevated` (or any `devvm.py run`) hangs.** This is a developer tool with a human
watching it run, not an unattended job: a suspended wrapper or a WER "... has stopped working"
dialog leaves the completion pipe genuinely open, with nothing wrong for the OS to report, so no
timeout can tell "still working" apart from "wedged forever" — that residual case is handled by
the human, not by guessing a second timeout. Ctrl-C the `devvm.py run` invocation, then clean up
the guest by hand, going through `devvm.py` (a bare `vagrant winrm` runs outside its own
environment — `DEVVM_STAGE_DIR`, `VAGRANT_DOTFILE_PATH`, its working directory — and would fail or
target the wrong guest). Only run this when no other `run --unelevated` is in flight — the
wildcard below matches every `DevvmUnelevatedRun-*` task, not just the hung one, so it would
stop/unregister a concurrent healthy run's task too:

```sh
uv run scripts/devvm.py run windows-x64 -- powershell -NoProfile -Command 'Get-ScheduledTask DevvmUnelevatedRun-* | ForEach-Object { $_ | Stop-ScheduledTask; $_ | Unregister-ScheduledTask -Confirm:$false }'
```

This removes the task(s) and, since `Stop-ScheduledTask` kills its action process, the stuck
wrapper with it. If a WER dialog is what's actually holding it, clear that first:

```sh
uv run scripts/devvm.py run windows-x64 -- powershell -NoProfile -Command 'Get-Process | Where-Object Name -eq WerFault | Stop-Process -Force'
```

**Measured timings on this host** (Apple Silicon Mac, so `windows-x64` runs under TCG
cross-arch emulation; one-time data point on 2026-09-23, not a guarantee):

| Guest                      | `up` (import → provisioned)                                                                                                                                                    | trivial command | `destroy` |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------- | --------- |
| `linux-arm64` (native HVF) | ~75s                                                                                                                                                                           | <1s             | ~5s       |
| `windows-x64` (TCG)        | ~13.5 min (import + first boot + WinRM ready + full provisioning: file upload plus the 5 devvm.py-driven scripts — clean-stage, mirror-tree, lock-tree, account-and-uac, rust) | ~30s            | ~1 min    |

`windows-x64`'s `boot_timeout`/`winrm.timeout` are set to 3600s to give real headroom for a
slower host or a colder box cache; in practice first boot under TCG on this host landed
nowhere near that ceiling.

## Read-only working tree

`up` and `sync` get a copy of the working tree into the guest without letting the guest write
back into your actual source tree. The copy is an allow-list, not an exclude-list: it's exactly
the files `git ls-files` reports as tracked, filtered to those that still exist on disk — so
untracked files (`CLAUDE.local.md`, `.claude/`, build output, etc.) and `.git` itself never
reach the guest, without needing to enumerate what to leave out.

- **Linux guests** (`linux-x64`, `linux-arm64`): a one-shot `rsync` push to
  `~/cosca`, files landing mode `444` (directories stay `755` so later syncs can still
  add/remove files). This is `vagrant`'s built-in `rsync` synced-folder type, not a live
  mount — the guest never writes through to the host.
- **Windows guest** (`windows-x64`): no rsync binary on the box, and Vagrant's SMB synced
  folder needs a one-time macOS _System Settings → Sharing → File Sharing_ toggle plus a
  password prompt on every mount — too much friction for a throwaway VM. Instead, the pipeline
  is four steps, always run in this order (see [Windows guests]#windows-guests above for why
  only the second is an actual Vagrant provisioner, not a `devvm.py`-driven `vagrant winrm`
  call): `windows-clean-stage.ps1` wipes the guest's scratch staging directory
  (`C:\cosca-stage`); Vagrant's `file` provisioner uploads `scripts/devvm.py sync`'s host-side
  staged copy (`.tmp/devvm/windows-x64/tree/`, see above) into that staging directory over
  WinRM; `windows-mirror-tree.ps1` robocopy-`/MIR`s it from there into `C:\cosca`;
  `windows-lock-tree.ps1` strips write access from `C:\cosca` with `icacls`. Wiping the
  staging directory first (rather than mirroring the upload straight into `C:\cosca`) keeps a
  file deleted on the host from lingering in the guest after an upload,
  since `file` itself only adds/overwrites, and `/MIR` needs a clean source to mirror from.

Either way this is a **convention, not a security boundary**: the connecting account is an
administrator (Linux: passwordless `sudo`; Windows: `Administrators` membership) and can
always grant itself write access back. It exists so an accidental `cargo test` writing into
its own source tree, or a stray `rm`, doesn't silently succeed.

Cargo builds need a writable output directory, since the synced tree isn't one — `devvm.py
run` sets `CARGO_TARGET_DIR` to a per-guest home directory automatically (`~/cargo-target`
on Linux, `%USERPROFILE%\cargo-target` on Windows), so `devvm.py run linux-x64 -- cargo
test` just works.

## State directories

The state this tool creates per-guest — the QEMU disk overlay, Vagrant's per-guest machine
metadata, the staged tree copy — lives under `.tmp/devvm/<guest>/` in this worktree
(gitignored via the repo's existing `.tmp/` rule). `devvm.py` arranges this by pointing
`VAGRANT_DOTFILE_PATH` at `.tmp/devvm/<guest>/.vagrant` for every `vagrant` invocation it
makes, and `devvm.py destroy` removes it — but only once `vagrant destroy` itself actually
succeeds; if it fails (a stuck lock, a QEMU process it can't reach), `devvm.py` leaves
`.tmp/devvm/<guest>/` in place instead of deleting state out from under a VM that may still
be running, and exits non-zero so the failure isn't silent.

**Not true home-dir isolation, though — Vagrant and vagrant-qemu keep their own state in
`~/.vagrant.d/` regardless, same as any other Vagrant project on the machine, and `devvm.py`
does not redirect or clean any of it:**

- **Box images and plugins** (several GB each): `~/.vagrant.d/{boxes,gems}`. Vagrant ties
  plugin installation and box storage to the same `VAGRANT_HOME`; redirecting it per-project
  would mean reinstalling `vagrant-qemu` (and re-downloading every box) per worktree, which is
  worse than the alternative. Manage this directly with `vagrant box list` / `vagrant box
remove <name>` when you're done with a box.
- **vagrant-qemu's own per-VM runtime files** — a QEMU pid file, its QMP monitor socket, and
  an `options.yml` — under `~/.vagrant.d/tmp/vagrant-qemu/<id>/` while a guest is running.
  `devvm.py destroy`/`vagrant destroy` clean up the VM they belong to; if `destroy` is ever
  skipped, or fails partway (see above), these can be left behind.
- **Vagrant's global machine index**, `~/.vagrant.d/data/machine-index/index` — a manifest of
  every machine Vagrant knows about on this host, across all projects, not per-worktree state.

None of this is huge (unlike the box images), but it means `rm -rf` on this worktree, or even
`devvm.py destroy` for every guest, does not fully return `~/.vagrant.d/` to its pre-devvm
state. If that matters, `vagrant global-status` lists every machine Vagrant's index knows
about, including ones no longer backed by an actual `.tmp/devvm/` directory.

**Disk is usually the constraint, not the tool.** Windows boxes run several GB; check `df -h`
before `up`-ing a Windows guest, and don't keep more than one Windows box downloaded at a
time (`vagrant box list`, then `vagrant box remove` the one you're done with) if space is
tight.

## Forwarded ports are loopback-only, always

Every guest's forwarded ports (WinRM, RDP, SSH) are bound to `127.0.0.1` on the host, never
`0.0.0.0`/every interface — nothing here is meant to be reachable from your LAN. This is
enforced, not just configured: `scripts/devvm/guests/_shared/fix_qemu_loopback_only.rb` is
loaded unconditionally by every guest Vagrantfile and patches
`VagrantPlugins::QEMU::Driver#execute` to rewrite any empty-hostaddr `hostfwd=` clause in the
constructed QEMU command line to loopback before QEMU ever starts — needed because
vagrant-qemu 0.6.3 hardcodes the SSH forward with no `host_ip` seam a Vagrantfile can reach at
all, so `host_ip: "127.0.0.1"` in the Vagrantfile alone doesn't cover SSH.

Because this reaches into a private method by name, it's pinned to exactly vagrant-qemu
`0.6.3` (checked inside the patched `execute` itself, so only starting a new QEMU process —
`vagrant up`/`vagrant reload` when the guest isn't already running — or an `export`/`package`
`qemu-img` call refuses to run against any other installed version; `vagrant provision` on
its own never reaches `Driver#execute` at all, running or not — confirmed by reading
vagrant-qemu's `action.rb`, whose standalone `action_provision` goes straight to the
`Provision` action and never touches `StartInstance` — and `destroy`/`halt` don't either, so
neither can ever leave a running QEMU process unstoppable after a plugin upgrade) and fails
closed with a hard error if a rewritten forward is ever found still bound to a non-loopback
address, rather than silently starting QEMU with a port exposed to the LAN.

## Known host issue: forwarded-port collisions on some macOS hosts

On at least one Apple Silicon host (confirmed: macOS, Vagrant 2.4.9, both system Ruby 2.6.10
and Vagrant's bundled Ruby 3.3.8), `vagrant up` can fail with `ForwardPortCollision` or
`ForwardPortAutolistEmpty` for a port nothing is actually listening on. Root cause: Vagrant's
own `Vagrant::Util::IsPortOpen.is_port_open?` uses `Socket.tcp(host, port, connect_timeout:
...)`, and that non-blocking-connect code path reports every port as "open" (in use) on this
host regardless of whether anything is bound — reproduced directly against both Rubies, with
both `"0.0.0.0"` and `"127.0.0.1"`, at multiple timeout values; a plain blocking
`TCPSocket.new` against the same ports correctly raises `ECONNREFUSED`. Because the check is
wrong, the auto-correction loop burns through the entire usable port range on the first
collision and has nothing left for the second.

Each guest Vagrantfile works around this by loading
`scripts/devvm/guests/_shared/fix_macos_port_check.rb`, which monkeypatches
`is_port_open?` to use a blocking connect instead, before `vagrant up`'s port-collision
middleware runs. This is loaded unconditionally (harmless on hosts where the bug doesn't
reproduce) rather than gated behind a host check, since the same code path is used by every
provider's forwarded-port handling, not just this tool's guests.

## Unattended GUI elevation

Tests of graphical elevation (`pkexec` with `Auth::Gui`, `osascript ... with administrator privileges`) wait
for a person unless the machine is set up to approve them. CI's ELEVATION lanes call
`.github/scripts/unattended-gui-elevation.py` for that. A developer can run the same setup in a devvm guest,
never on their own machine: the script refuses unless the flag `--this-machine-is-disposable` is given and
the machine is a GitHub-hosted runner or a devvm guest (marker file `/etc/cosca-devvm-guest`, written by the devvm
driver when the guest is provisioned). Both are virtual machines. A container is not evidence of disposability: it is
only as isolated as its mounts (a bind-mounted `/run/systemd/private`, `/etc/sudoers.d`, `/etc/polkit-1/rules.d`
would reach the host), which a script cannot prove. One passes only on a disposable host (a job `container:` on a
hosted runner inherits the runner's variables). On Linux and macOS the script must run as root and refuses otherwise.

On Linux the script needs systemd as PID 1 and polkit 0.106 or later (JavaScript `rules.d`), and a `--user` that
exists and is not root (polkit always authorizes root). It restarts `polkit.service`, then checks that the user can
run `pkexec` with no agent; it refuses anything else before writing anything, and runs its commands with a scrubbed
environment (no `SYSTEMCTL_FORCE_BUS` or `DBUS_*` from the caller). CI and the devvm Linux guests qualify.

```sh
# Linux guest: a polkit rule authorizes one account for every polkit action
sudo python3 .github/scripts/unattended-gui-elevation.py --this-machine-is-disposable --user vagrant
# macOS guest
sudo python3 .github/scripts/unattended-gui-elevation.py --this-machine-is-disposable
```

On macOS this writes `system.privilege.admin allow`: **every account and process on the guest** gets
administrator rights without authentication, not just one user.

On a Windows guest do not use the script: provisioning resets the consent policy on every `up`, so use
`devvm.py up windows-x64 --allow-elevation` (see [Windows guests](#windows-guests)), which sets
`ConsentPromptBehaviorAdmin=0` and re-applies it each time.