import Foundation
import NucleicMDM
import os
#if arch(arm64)
import Virtualization
#endif

/// Diagnostics for the provisioning passes (the guest's own log lands on the share; this is the
/// host-side narration that explains what the engine did with it).
private let provisionLog = Logger(subsystem: "com.nucleic", category: "macvm.provision")

/// Three-stage provisioning of the golden macOS base: a minimal automount/HID boot installs nash and
/// the native vsock agent; a direct-instance boot enrolls the lightweight MDM and verifies policy;
/// only then does a final automount/HID boot run `provision-macos-guest.sh` for the toolchain, apps,
/// packages, and optional SIP-off semantic-AX grants. The recipe stamp follows a production-shaped
/// agent/custom-mount readiness probe, so incomplete bases never become clone sources.
///
/// The full provisioner's optional semantic-AX TCC writes still need SIP disabled in the guest
/// (docs/MACOS_VM.md §12.5); Phase 7 detects SIP and skips those rows safely when it is on. Ordinary
/// pixel computer use remains host-side and needs none of them. MDM supplies the required FDA,
/// Network Volumes, and notification policy in either SIP posture.
extension MacVMEngine {
    /// What the provisioning pass achieved, folded into the base's `bundle.json`.
    struct ProvisionResult: Sendable {
        var provisioned: Bool        // the toolchain script ran to completion (exec-ready)
        var agentInstalled: Bool     // NucleicVMAgent.app + LaunchAgent present in the guest
        var sipDisabled: Bool        // SIP off (⇒ the AX agent's TCC grants could be written)
        var axAgentReady: Bool       // AX agent installed AND its TCC grants are in place
        // The user apps / common packages actually staged into the base this pass (settings ∪ any
        // carried forward from a base being replaced) — recorded into `bundle.json` so a later rebuild
        // carries them forward in turn. Default empty for the early boot-failure return.
        var installedAppPaths: [String] = []
        var installedPackageIDs: [String] = []
    }

    /// Parsed readback of the `CODE=… SIP=… APP=… LA=… TCC=… CA=…` line the guest bootstrap writes to
    /// the STATUS file on the shared directory after provisioning (docs/MACOS_VM.md §4.4).
    struct ProvisionStatusFlags: Sendable, Equatable {
        var exitCode: Int32 = -1
        var sipDisabled = false
        var agentApp = false
        var launchAgent = false
        var tccCount = 0
        /// The guest's own answer to "does this machine trust the Nucleic MDM root for SSL?", written
        /// only by the minimal-agent pass. Defaults to `false` so an older bootstrap that predates the
        /// token is treated as untrusted rather than silently passing the gate.
        var caTrusted = false
        /// Whether the admin trust domain was installed and the CA imported — everything the
        /// minimal-agent boot actually controls. Separate from ``caTrusted`` because trust settings are
        /// read when trustd starts, so a boot that ends in a shutdown can install them correctly and
        /// still evaluate as untrusted until the next boot.
        var caTrustFileInstalled = false
    }

    /// Parse the `CODE=0 SIP=1 APP=1 LA=1 TCC=3 CA=1` readback line (order-independent, noise-tolerant).
    static func parseProvisionStatus(_ output: String) -> ProvisionStatusFlags {
        var flags = ProvisionStatusFlags()
        for token in output.split(whereSeparator: { $0 == " " || $0.isNewline }) {
            let parts = token.split(separator: "=", maxSplits: 1)
            guard parts.count == 2 else { continue }
            let value = String(parts[1]).trimmingCharacters(in: .whitespaces)
            switch parts[0] {
            case "CODE": flags.exitCode = Int32(value) ?? -1
            case "SIP": flags.sipDisabled = (value == "1")
            case "APP": flags.agentApp = (value == "1")
            case "LA": flags.launchAgent = (value == "1")
            case "TCC": flags.tccCount = Int(value) ?? 0
            case "CA": flags.caTrusted = (value == "1")
            case "CAFILE": flags.caTrustFileInstalled = (value == "1")
            default: break
            }
        }
        return flags
    }

    // MARK: - Provisioning-asset resolution (bundled in the app; dev fallback to the source tree)

    /// The staged `scripts/provision-macos-guest.sh` — bundled into the app under `Resources/macvm/`
    /// (`scripts/package-app.sh`), or, for a dev/SwiftPM run, the copy in the source tree.
    func resolveProvisionScript() -> URL? {
        if let bundled = Bundle.main.resourceURL?
            .appendingPathComponent("macvm/provision-macos-guest.sh"),
            FileManager.default.fileExists(atPath: bundled.path)
        {
            return bundled
        }
        return Self.devRepoRoot()?.appendingPathComponent("scripts/provision-macos-guest.sh")
    }

    /// The signed `NucleicVMAgent.app` to bake in — bundled under `Resources/macvm/`, or, for a dev
    /// run, the `scripts/build-vm-agent.sh` output (built on demand if absent). `nil` is fatal to a
    /// recipe-v8 base: this agent is the control plane used for mandatory Mode A enrollment.
    func resolveVMAgentApp() -> URL? {
        if let bundled = Bundle.main.resourceURL?
            .appendingPathComponent("macvm/NucleicVMAgent.app"),
            FileManager.default.fileExists(atPath: bundled.path)
        {
            return bundled
        }
        guard let root = Self.devRepoRoot() else { return nil }
        let dist = root.appendingPathComponent("guest/NucleicVMAgent/dist/NucleicVMAgent.app")
        if FileManager.default.fileExists(atPath: dist.path) { return dist }
        // Dev convenience: build it once via the same script the packaging step uses.
        let build = Process()
        build.executableURL = URL(fileURLWithPath: "/bin/bash")
        build.arguments = [root.appendingPathComponent("scripts/build-vm-agent.sh").path]
        build.standardOutput = Pipe()
        build.standardError = Pipe()
        try? build.run()
        build.waitUntilExit()
        return FileManager.default.fileExists(atPath: dist.path) ? dist : nil
    }

    /// The universal `nash` binary to bake into the guest (docs/NASH.md §7.5) — bundled under
    /// `Resources/macvm/` (`scripts/package-app.sh`, which now *fails* rather than shipping without
    /// it), or, for a dev run, the `scripts/build-nash-macos.sh` output.
    ///
    /// `nil` is a **fatal** condition for a base build, not a degradation: nash is the only shell
    /// the guest exec surface runs (§7.5 — locked), so a base without it has a dead exec surface and
    /// `provisionBase` refuses to provision one (the provisioner's Phase 5⅓ aborts in-guest for the
    /// same reason). The superseded "no binary, no swap" posture silently produced zsh guests.
    /// Unlike the VM agent there is deliberately no build-on-demand fallback: a silent multi-minute
    /// cargo build inside provisioning (on hosts that mostly have no Rust toolchain) is worse than
    /// failing fast with a message that names the fix.
    func resolveNashBinary() -> URL? {
        if let bundled = Bundle.main.resourceURL?.appendingPathComponent("macvm/nash"),
            FileManager.default.isExecutableFile(atPath: bundled.path)
        {
            return bundled
        }
        guard let root = Self.devRepoRoot() else { return nil }
        let dist = root.appendingPathComponent("shell/dist/macos/nash")
        return FileManager.default.isExecutableFile(atPath: dist.path) ? dist : nil
    }

    /// The LaunchAgent plist that rides alongside the agent app (same directory as `resolveVMAgentApp`).
    func resolveVMAgentPlist(near app: URL) -> URL? {
        let plist = app.deletingLastPathComponent()
            .appendingPathComponent("xyz.blakeslee.nucleic.vmagent.plist")
        return FileManager.default.fileExists(atPath: plist.path) ? plist : nil
    }

    /// Locate the repo root from this source file (dev/SwiftPM runs only): ascend until
    /// `scripts/provision-macos-guest.sh` is found. `nil` from a shipped app (no source tree).
    static func devRepoRoot() -> URL? {
        var dir = URL(fileURLWithPath: #filePath).deletingLastPathComponent()
        for _ in 0..<6 {
            if FileManager.default.fileExists(
                atPath: dir.appendingPathComponent("scripts/provision-macos-guest.sh").path)
            {
                return dir
            }
            dir = dir.deletingLastPathComponent()
        }
        return nil
    }
}

#if arch(arm64)
extension MacVMEngine {
    /// Run the account + toolchain + agent provisioning pass on a freshly installed (or already
    /// account-provisioned) base and fold the result into its `bundle.json`. Best-effort on *content*
    /// — a SIP-on guest yields an exec-ready-but-not-AX base — and throws only when the guest never
    /// became drivable, leaving the published base intact for a retry (the reentrant "Build again").
    ///
    /// `declarativeFirstBoot` (macOS 27 fresh install) makes this the first boot after restore, so it
    /// carries `VZMacGuestProvisioningOptions` to create the `agent` account + auto-login.
    ///
    /// `carryAppPaths` / `carryPackageIDs` are the user apps / packages recorded on the base being
    /// (re)provisioned — the same base on a reentrant re-provision, or the *old* base a from-scratch
    /// rebuild is replacing. They're unioned with the current Settings selections when staging so apps
    /// the user had installed here survive a rebuild that replaces the base (docs/MACOS_VM.md §9.1).
    func provisionAndFinalize(
        bundle: MacVMBundle, base: MacVMBaseStatus, declarativeFirstBoot: Bool,
        carryAppPaths: [String] = [], carryPackageIDs: [String] = []
    ) async throws {
        var status = base
        startBuildHostLog(bundle: bundle, label: "macOS provision (lane=\(MacVMSettings.policyLane))")
        defer { hostLog("── provisionAndFinalize returned ──"); buildLogURL = nil }

        // Phase 1: create/reuse the account and land only the control plane needed by Mode A. No
        // protected custom mount or heavyweight network/toolchain work occurs before MDM policy.
        hostLog("Phase 1: installing the minimal exec agent (declarativeFirstBoot=\(declarativeFirstBoot))")
        baseProgress = MacVMBaseProgress(
            phase: declarativeFirstBoot ? .firstBootSetup : .installingAgent, fraction: nil)
        let minimal: ProvisionResult
        do {
            minimal = try await installMinimalAgent(
                bundle: bundle, declarativeFirstBoot: declarativeFirstBoot)
        } catch {
            hostLog("Phase 1 FAILED: \(error)")
            baseProgress = nil
            throw MacVMError.provisionFailed(
                "the minimal exec-agent pass failed before MDM enrollment: \(error)")
        }
        hostLog("Phase 1 OK: account+agent installed (sipDisabled=\(minimal.sipDisabled))")
        status.accountProvisioned = minimal.provisioned
        status.agentInstalled = minimal.agentInstalled
        status.sipDisabled = minimal.sipDisabled
        status.axAgentReady = false
        writeBaseStatus(bundle, status)
        guard minimal.provisioned, minimal.agentInstalled else {
            baseProgress = nil
            throw MacVMError.provisionFailed(
                "the minimal pass did not install a reachable in-guest agent; MDM enrollment cannot "
                    + "run and the base was not published")
        }

        // Phase 2: deliver the base's baked-in policy. Lane B (datastore, default) writes the grants
        // straight into the system TCC.db under a transient SIP-off Recovery toggle and confirms they
        // survive re-enabling SIP; Lane A (MDM) enrolls in the local User-Approved MDM and installs the
        // PPPC/notification profiles. Either way a partial/failed pass is fatal: the recipe stamp is
        // withheld and the base is left retry-stale. (docs/MACOS_VM_POLICY_ALTERNATIVE.md.)
        let policyLane = MacVMSettings.policyLane
        hostLog("Phase 2: applying base policy (lane=\(policyLane))")
        switch policyLane {
        case .datastore:
            do {
                // policyGrantsPass reports its own fine-grained phases (disabling SIP → writing grants
                // → re-enabling SIP → verifying), so the settings checklist shows each step.
                let readback = try await policyGrantsPass(bundle: bundle)
                hostLog("Phase 2 OK (Lane B): \(readback.summary)")
                status.policyGrantsVerified = true
                status.axAgentReady = true      // Lane B grants Accessibility + Screen Recording + PostEvent
                status.sipDisabled = false       // re-enabled before the base is sealed
                writeBaseStatus(bundle, status)
            } catch {
                hostLog("Phase 2 FAILED (Lane B): \(error)")
                baseProgress = nil
                throw MacVMError.provisionFailed(
                    "Lane B datastore policy grants failed: \(error). The recipe stamp was withheld; "
                        + "fix the cause (or set nucleic.macvm.policyLane=mdm to use the MDM lane) and "
                        + "rebuild.")
            }
        case .mdm:
            baseProgress = MacVMBaseProgress(phase: .applyingPolicy, fraction: nil)
            do {
                let outcome = try await mdmPolicyPass(bundle: bundle)
                guard let verifiedStatus = Self.baseStatus(byApplying: outcome, to: status) else {
                    throw MacVMError.provisionFailed(
                        "MDM returned incomplete state (enrolled=\(outcome.enrolled), "
                            + "profiles=\(outcome.profilesInstalled)/"
                            + "\(Self.builtInMDMPolicyProfileNames.count))")
                }
                status = verifiedStatus
                writeBaseStatus(bundle, status)
            } catch {
                baseProgress = nil
                throw MacVMError.provisionFailed(
                    "mandatory MDM enrollment/policy verification failed: \(error). The recipe stamp "
                        + "was withheld; inspect the base's Diagnostics/MDM bundle, if present, before "
                        + "retrying.")
            }
        }

        // Phase 3: only after policy exists, run the full toolchain/apps/packages provisioner. This
        // second HID boot is no longer the account-creation boot, so never replay declarative setup.
        hostLog("Phase 3: running the full toolchain provisioner (HID boot)")
        baseProgress = MacVMBaseProgress(phase: .provisioning, fraction: nil)
        let result: ProvisionResult
        do {
            result = try await provisionBase(
                bundle: bundle,
                carryAppPaths: carryAppPaths, carryPackageIDs: carryPackageIDs)
        } catch {
            hostLog("Phase 3 FAILED: \(error)")
            baseProgress = nil
            throw MacVMError.provisionFailed(String(describing: error))
        }
        hostLog(
            "Phase 3 OK: provisioned=\(result.provisioned) agent=\(result.agentInstalled) "
                + "sipDisabled=\(result.sipDisabled)")
        status.provisioned = result.provisioned
        status.agentInstalled = result.agentInstalled
        status.sipDisabled = result.sipDisabled
        // The toolchain pass runs with SIP on (Lane B re-enabled it in Phase 2), so its own SIP-off AX
        // probe reads false — but the AX grants ARE in place if Lane B verified them, so preserve that.
        status.axAgentReady = result.axAgentReady || status.policyGrantsVerified
        status.installedAppPaths = result.installedAppPaths
        status.installedPackageIDs = result.installedPackageIDs
        writeBaseStatus(bundle, status)
        guard result.provisioned, result.agentInstalled else {
            baseProgress = nil
            throw MacVMError.provisionFailed(
                "the full pass did not complete with the in-guest agent installed — clones would be "
                    + "incomplete or unreachable. Check the build monitor/provision log and rebuild.")
        }

        // The old consent click is not allowed to rescue a broken policy. Boot the finished base and
        // require the exact production-shaped custom mount, nash, and an exec round-trip to succeed
        // immediately; a prompt or a dead exec surface is failure.
        hostLog("Phase 4: booting the finished base to verify readiness (mount + nash + exec)")
        baseProgress = MacVMBaseProgress(phase: .verifyingReadiness, fraction: nil)
        do {
            try await networkVolumesConsentPass(bundle: bundle)
        } catch {
            hostLog("Phase 4 FAILED (readiness): \(error)")
            baseProgress = nil
            throw MacVMError.provisionFailed(
                "the base's policy was installed, but the production-shaped network-volume readiness "
                    + "probe failed without interactive fallback: \(error) The recipe stamp was withheld.")
        }
        hostLog("Phase 4 OK: base readiness verified")
        // The MDM lane additionally requires the persisted host MDM identity on disk; the datastore
        // lane has no such artifact — its invariant is the verified TCC grants (checked above).
        baseProgress = MacVMBaseProgress(phase: .sealing, fraction: nil)
        guard Self.baseStatusReadyForRecipe(status, lane: policyLane),
              policyLane == .datastore
                || FileManager.default.fileExists(atPath: bundle.mdmStateURL.path)
        else {
            baseProgress = nil
            throw MacVMError.provisionFailed(
                "the base passed its functional probe but its persisted agent/policy/toolchain status "
                    + "or host MDM identity is incomplete; refusing to stamp the recipe")
        }
        status.provisioningRecipe = Self.macOSProvisioningRecipe
        writeBaseStatus(bundle, status)
        hostLog("SEALED: recipe v\(Self.macOSProvisioningRecipe) stamped — base is ready")
        baseProgress = MacVMBaseProgress(phase: .ready, fraction: 1)
    }

    /// Surface/VM label for the account + minimal exec-agent boot that precedes Mode A.
    public static let baseMinimalAgentSurfaceName = "base-minimal-agent"

    /// Canonical LaunchAgent used when a development agent build did not emit a sibling plist.
    static let minimalAgentLaunchAgentPlist = """
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>xyz.blakeslee.nucleic.vmagent</string>
        <key>ProgramArguments</key>
        <array>
            <string>/Applications/NucleicVMAgent.app/Contents/MacOS/NucleicVMAgent</string>
        </array>
        <key>RunAtLoad</key><true/>
        <key>KeepAlive</key><true/>
        <key>LimitLoadToSessionType</key><string>Aqua</string>
        <key>AssociatedBundleIdentifiers</key><string>xyz.blakeslee.nucleic.vmagent</string>
        <key>StandardOutPath</key><string>/tmp/nucleic-vmagent.log</string>
        <key>StandardErrorPath</key><string>/tmp/nucleic-vmagent.log</string>
    </dict>
    </plist>
    """

    /// The staged filename of the MDM CA root this pass must make the guest trust.
    static let minimalAgentCACertName = MDMServerController.Artifact.caCert
    /// The staged admin-domain trust settings installed when no API can establish trust
    /// non-interactively (``MDMAdminTrustSettings``).
    static let minimalAgentTrustSettingsName = "nucleic-mdm-trust-admin.plist"

    /// The only pre-MDM guest mutation: durable sudo, nash, auto-login, the native vsock agent, and
    /// system trust for the MDM CA. It deliberately performs no toolchain download, custom mount, TCC
    /// write, or optional app copy.
    static func minimalAgentBootstrapScript(user: String) -> String {
        let entry = guestSharePath(os: .macOS, name: provisionShareName)
        let plist = "/Library/LaunchAgents/xyz.blakeslee.nucleic.vmagent.plist"
        let tccDB = "/Library/Application Support/com.apple.TCC/TCC.db"
        return """
        #!/bin/bash
        SHARE="\(entry)"
        exec > >(/usr/bin/tee "$SHARE/provision.log") 2>&1
        touch "$SHARE/STARTED" 2>/dev/null || true
        PW="$(cat "$SHARE/password")"
        CODE=0
        run_required() {
          "$@"
          RESULT=$?
          if [ "$RESULT" -ne 0 ]; then
            echo "✗ minimal-agent command failed (exit $RESULT): $*" >&2
            CODE=1
          fi
          return 0
        }

        printf '%s\\n' "$PW" | sudo -S sh -c 'grep -q "includedir /private/etc/sudoers.d" /etc/sudoers || printf "%s\\n" "@includedir /private/etc/sudoers.d" >> /etc/sudoers; mkdir -p /etc/sudoers.d; printf "%s\\n" "\(user) ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/nucleic-agent; chmod 0440 /etc/sudoers.d/nucleic-agent' 2>/dev/null || CODE=1

        run_required sudo /bin/mkdir -p /usr/local/bin
        run_required sudo /bin/cp "$SHARE/nash" /usr/local/bin/nash
        run_required sudo /bin/chmod 0755 /usr/local/bin/nash
        run_required sudo /usr/bin/dscl . -create "/Users/\(user)" UserShell /usr/local/bin/nash

        run_required sudo /bin/rm -rf /Applications/NucleicVMAgent.app
        run_required sudo /bin/cp -R "$SHARE/NucleicVMAgent.app" /Applications/NucleicVMAgent.app
        sudo /usr/bin/xattr -dr com.apple.quarantine /Applications/NucleicVMAgent.app 2>/dev/null || true
        run_required sudo /bin/cp "$SHARE/xyz.blakeslee.nucleic.vmagent.plist" "\(plist)"
        run_required sudo /usr/sbin/chown root:wheel "\(plist)"
        run_required sudo /bin/chmod 0644 "\(plist)"

        # Declarative first boot already requests auto-login. Reapplying it is useful for an older
        # re-provisioned base, but sysadminctl is not an authoritative readiness signal: it can return
        # nonzero when the requested state already exists. The next MDM boot's agent probe is the
        # authoritative proof that an Aqua auto-login session came back.
        if sudo /usr/sbin/sysadminctl -autologin set -userName "\(user)" -password "$PW" 2>/dev/null; then
          echo "✓ Auto-login configured for \(user)."
        else
          echo "⚠ Auto-login refresh reported an error; the next-boot agent probe will verify it." >&2
        fi
        AGENT_UID="$(/usr/bin/id -u "\(user)")"
        sudo /bin/launchctl bootout "gui/$AGENT_UID/xyz.blakeslee.nucleic.vmagent" 2>/dev/null || true
        # bootstrap may race launchd's automatic /Library/LaunchAgents load. Its exit status is not
        # authoritative; the final service lookup below is.
        sudo /bin/launchctl bootstrap "gui/$AGENT_UID" "\(plist)" 2>/dev/null || true
        /bin/sleep 2
        run_required sudo /bin/launchctl print "gui/$AGENT_UID/xyz.blakeslee.nucleic.vmagent"

        # ── System trust for the Nucleic MDM CA ───────────────────────────────────────────────────
        # This boot is the ONLY place the guest can gain trust in our CA, and it must happen before
        # any profile is opened (docs/MACOS_VM_MDM.md §2.3). Both of the obvious alternatives are
        # closed by Apple, for different reasons:
        #
        #   * Since Big Sur, an admin-domain trust change requires interactive admin authorization, so
        #     `add-trusted-cert` raises a SecurityAgent sheet owned by a root CLI with no GUI app. That
        #     sheet never becomes key and defeated five consecutive automated attempts.
        #   * Since Ventura, a root delivered by a MANUALLY installed configuration profile is no
        #     longer auto-trusted for TLS — it lands in the keychain with SSL trust "no value
        #     specified" — so the profile route cannot bootstrap trust either. (Auto-trust survives
        #     only for roots delivered BY an MDM, which is the thing we are trying to enrol into.)
        #
        # So the authorization right that gates the change is relaxed for the length of this boot, the
        # change is made, and the right is put back. The relaxation is READ BACK before it is relied
        # on: `authorizationdb write` itself needs `system.right.write`, so it can silently no-op and
        # leave the prompt exactly where it was — the most likely reason an earlier attempt at this
        # route was recorded as "does not work".
        # `security add-trusted-cert` is NEVER called here, and must not be re-added. It raises a
        # SecurityAgent authorization sheet that has now wedged this build three separate times. The
        # sheet is a GUI dialog raised by a root CLI with no GUI app: it never becomes key, so it
        # cannot be driven, and it is not a terminal read, so redirecting stdin does not dismiss it.
        # The command simply blocks until the whole boot times out. Relaxing the gating right first
        # does not help either — `security authorizationdb write com.apple.trust-settings.admin allow`
        # silently no-ops on macOS 27 (a live run read the rule straight back and found it unchanged).
        #
        # What is left is the file the API would have written. `/Library/Security/Trust Settings` is
        # root-owned and carries no SIP `restricted` flag, and trustd reads the admin trust domain from
        # there — so a plain `cp` establishes the same trust while calling no authorization-gated API
        # at all, and `cp`/`chown`/`chmod` cannot prompt.
        CA_CERT="$SHARE/\(minimalAgentCACertName)"
        CA_TRUST_PLIST="$SHARE/\(minimalAgentTrustSettingsName)"
        ADMIN_TRUST="/Library/Security/Trust Settings/Admin.plist"
        CA=0
        CAFILE=0

        # Hard deadline for anything that could conceivably block. macOS ships no timeout(1), and this
        # boot has no way to answer a prompt, so an unbounded command turns a diagnosable failure into
        # a silent 15-minute stall. Every `security` invocation below goes through this.
        run_bounded() {
          SECS="$1"; shift
          "$@" &
          BPID=$!
          WAITED=0
          while kill -0 "$BPID" 2>/dev/null; do
            if [ "$WAITED" -ge "$SECS" ]; then
              kill -9 "$BPID" 2>/dev/null || true
              # sudo does not forward the kill to its child, and the only `security` this boot runs is
              # the one we just gave up on.
              sudo /usr/bin/killall -9 security 2>/dev/null || true
              echo "  ⚠ timed out after ${SECS}s (likely an unanswerable prompt): $*"
              return 124
            fi
            /bin/sleep 1
            WAITED=$((WAITED + 1))
          done
          wait "$BPID"
        }

        # Deliberately unredirected: verify-cert's own words are the most useful line in this log when
        # trust does not land, and a `>/dev/null` here would also swallow run_bounded's timeout notice.
        ca_verified() {
          sudo /usr/bin/killall trustd 2>/dev/null || true
          /bin/sleep 2
          run_bounded 30 sudo /usr/bin/security verify-cert -c "$CA_CERT" -p ssl 2>&1
        }

        if [ ! -f "$CA_CERT" ] || [ ! -f "$CA_TRUST_PLIST" ]; then
          echo "✗ CA trust: the CA root and/or its trust-settings file were never staged."
        else
          # The certificate itself still has to live in a keychain trustd searches — the trust entry
          # references it by fingerprint and does not carry it. `add-certificates` only imports (it
          # sets no trust), which is the part that historically does not prompt; it is bounded anyway,
          # and a timeout here is reported rather than fatal, because the file write below is the step
          # that actually establishes trust.
          echo "── importing the CA into the System keychain (no trust change) ──"
          run_bounded 60 sudo /usr/bin/security add-certificates \\
            -k /Library/Keychains/System.keychain "$CA_CERT" 2>&1 || true

          echo "── writing the admin trust domain directly ──"
          sudo /bin/mkdir -p "$(dirname "$ADMIN_TRUST")" 2>&1 || true
          if [ -f "$ADMIN_TRUST" ]; then
            echo "  NOTE: an Admin.plist already exists and is being replaced; prior admin trust"
            echo "  settings (there should be none on a fresh base) would be lost."
          fi
          sudo /bin/cp "$CA_TRUST_PLIST" "$ADMIN_TRUST" 2>&1 || true
          sudo /usr/sbin/chown root:wheel "$ADMIN_TRUST" 2>&1 || true
          # 0644, not 0600: trustd does not run as root, and trust settings are public information
          # (certificates plus a trust flag) — an unreadable file would simply be ignored.
          sudo /bin/chmod 0644 "$ADMIN_TRUST" 2>&1 || true
          # Two facts, reported separately, because they fail for different reasons and only one of
          # them is actionable from this boot. CAFILE says the trust domain is on disk and the
          # certificate is in the keychain — everything this boot controls. CA says the running system
          # already honours it, which it may not until a restart: the settings are read at trustd
          # start-up, and `killall trustd` is not obviously equivalent to a boot.
          if sudo /bin/test -s "$ADMIN_TRUST"; then CAFILE=1; fi
          if run_bounded 30 sudo /usr/bin/security find-certificate \\
            -c "Nucleic MDM Root CA" /Library/Keychains/System.keychain >/dev/null 2>&1
          then
            echo "  the CA is present in the System keychain"
          else
            echo "  ⚠ the CA is NOT in the System keychain — add-certificates did not import it, so"
            echo "    no trust setting can apply to it"
            CAFILE=0
          fi
          if ca_verified; then CA=1; fi
        fi

        if [ "$CA" -eq 1 ]; then
          echo "✓ CA trust: the Nucleic MDM root verifies for SSL in this guest."
        elif [ "$CAFILE" -eq 1 ]; then
          echo "⚠ CA trust: the trust domain is installed and the CA is in the System keychain, but"
          echo "  this running system does not honour it yet. Trust settings are read when trustd"
          echo "  starts, and this boot ends in a shutdown — so the next boot's pre-flight is the"
          echo "  authoritative answer. Continuing rather than failing on a possibly stale verdict."
          echo "── security dump-trust-settings -d ──"
          run_bounded 30 sudo /usr/bin/security dump-trust-settings -d 2>&1 || true
        elif [ -f "$CA_CERT" ]; then
          # Distinguish "no trust at all" from "trusted, but not for SSL" — the latter is the Ventura
          # symptom and needs a different fix from the former.
          if run_bounded 30 sudo /usr/bin/security verify-cert -c "$CA_CERT" -p basic 2>&1; then
            echo "✗ CA trust: the root verifies for BASIC but NOT for SSL — an SSL-scoped trust"
            echo "  setting is missing, not the trust record itself."
          else
            echo "✗ CA trust: the root does not verify at all; no admin-domain trust was recorded."
          fi
          echo "── security dump-trust-settings -d ──"
          run_bounded 30 sudo /usr/bin/security dump-trust-settings -d 2>&1 || true
          echo "── $ADMIN_TRUST ──"
          sudo /bin/ls -l "$ADMIN_TRUST" 2>&1 || true
          sudo /usr/bin/plutil -p "$ADMIN_TRUST" 2>&1 | /usr/bin/head -40 || true
        fi

        test -x /usr/local/bin/nash || CODE=1
        test -d /Applications/NucleicVMAgent.app || CODE=1
        test -f "\(plist)" || CODE=1
        SIP=$(csrutil status 2>/dev/null | grep -qi disabled && echo 1 || echo 0)
        APP=$(test -d /Applications/NucleicVMAgent.app && echo 1 || echo 0)
        LA=$(test -f "\(plist)" && echo 1 || echo 0)
        TCC=$(sudo sqlite3 "\(tccDB)" "SELECT count(*) FROM access WHERE service IN ('kTCCServiceScreenCapture','kTCCServiceAccessibility','kTCCServicePostEvent') AND auth_value=2;" 2>/dev/null || echo 0)
        printf 'CODE=%s SIP=%s APP=%s LA=%s TCC=%s CA=%s CAFILE=%s\\n' \\
          "$CODE" "$SIP" "$APP" "$LA" "$TCC" "$CA" "$CAFILE" > "$SHARE/STATUS"
        sync
        if [ "$CODE" -eq 0 ]; then
          echo "✓ Minimal exec agent ready; shutting down for the MDM policy boot."
        else
          echo "✗ Minimal exec-agent pass failed; status and log were synced before shutdown." >&2
        fi
        sudo shutdown -h now
        """
    }

    /// First writable boot after restore: create the account when needed and install only the native
    /// control plane that the mandatory MDM pass needs on the following boot.
    func installMinimalAgent(
        bundle: MacVMBundle, declarativeFirstBoot: Bool
    ) async throws -> ProvisionResult {
        guard let surface = surfaceHost else {
            throw MacVMError.provisionFailed(
                "minimal agent installation needs the app's display surface")
        }
        guard let app = resolveVMAgentApp() else {
            throw MacVMError.provisionFailed(
                "the signed NucleicVMAgent.app could not be located")
        }
        guard let nash = resolveNashBinary() else {
            throw MacVMError.provisionFailed(
                "no darwin nash binary is available for the minimal exec-agent pass")
        }
        let user = MacVMSettings.sshUser
        let password = try resolveAgentPassword()
        let fm = FileManager.default
        let stageDir = fm.temporaryDirectory
            .appendingPathComponent("nucleic-minimal-agent-\(UUID().uuidString)", isDirectory: true)
        try fm.createDirectory(at: stageDir, withIntermediateDirectories: true)
        defer {
            try? fm.removeItem(at: stageDir)
            baseMaintenance = nil
        }

        try password.write(
            to: stageDir.appendingPathComponent("password"), atomically: true, encoding: .utf8)
        try fm.setAttributes(
            [.posixPermissions: 0o600],
            ofItemAtPath: stageDir.appendingPathComponent("password").path)
        try fm.copyItem(at: app, to: stageDir.appendingPathComponent("NucleicVMAgent.app"))
        try fm.copyItem(at: nash, to: stageDir.appendingPathComponent("nash"))
        let stagedPlist = stageDir.appendingPathComponent(
            "xyz.blakeslee.nucleic.vmagent.plist")
        if let sourcePlist = resolveVMAgentPlist(near: app) {
            try fm.copyItem(at: sourcePlist, to: stagedPlist)
        } else {
            try Self.minimalAgentLaunchAgentPlist.write(
                to: stagedPlist, atomically: true, encoding: .utf8)
        }
        let bootstrapURL = stageDir.appendingPathComponent(Self.bootstrapScriptName)
        try Self.minimalAgentBootstrapScript(user: user).write(
            to: bootstrapURL, atomically: true, encoding: .utf8)
        try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bootstrapURL.path)
        // Stage the CA root so this boot can put it in the guest's admin trust domain, plus the
        // ready-made trust-settings file for the case where no API will do it non-interactively. The
        // controller is created here rather than in the MDM pass so the base's CA exists — and is
        // persisted — before the guest that must trust it ever boots; the MDM pass loads the same one.
        let mdm = try loadOrCreateMDMController(for: bundle)
        try mdm.caCertificateDER().write(
            to: stageDir.appendingPathComponent(Self.minimalAgentCACertName))
        try mdm.adminTrustSettingsPlist().write(
            to: stageDir.appendingPathComponent(Self.minimalAgentTrustSettingsName))

        let mount = MacVMSpec.Mount(
            host: stageDir.path, name: Self.provisionShareName, readOnly: false,
            recreateHostPath: false)
        let config = try Self.makeConfiguration(
            bundle: bundle, cpus: MacVMSettings.vmCPUs, memoryGiB: MacVMSettings.vmMemoryGiB,
            mac: Self.randomMAC(), mounts: [mount])
        let instance = MacVMInstance(
            configuration: config, label: Self.baseMinimalAgentSurfaceName)
        baseMaintenance = MacVMMaintenanceInfo(
            name: Self.baseMinimalAgentSurfaceName, os: .macOS,
            activity: "Installing minimal exec agent…", booting: true)
        if declarativeFirstBoot, #available(macOS 27.0, *) {
            try await instance.startWithProvisioning(
                fullName: "Nucleic Agent", username: user, password: password)
        } else {
            try await instance.start()
        }
        await surface.attach(
            name: Self.baseMinimalAgentSurfaceName,
            virtualMachine: UncheckedSendableBox(value: instance.vm as AnyObject))
        if baseObserverRequested {
            await surface.setObserverVisible(
                name: Self.baseMinimalAgentSurfaceName, visible: true)
        }
        let statusURL = stageDir.appendingPathComponent("STATUS")
        let logURL = stageDir.appendingPathComponent("provision.log")
        let flags = await driveHIDBootstrap(
            surface: surface, name: Self.baseMinimalAgentSurfaceName,
            phase: declarativeFirstBoot ? .firstBootSetup : .installingAgent,
            startedURL: stageDir.appendingPathComponent("STARTED"),
            statusURL: statusURL, logURL: logURL,
            timeout: 900, maintenanceActivity: "Installing minimal exec agent…",
            // The declarative first boot lands on Setup Assistant → first login and is the slowest to
            // present a usable desktop; give it a longer settle before the first Terminal launch.
            initialLaunchDelay: declarativeFirstBoot ? 20 : 8)
        await surface.detach(name: Self.baseMinimalAgentSurfaceName)
        guard let flags else {
            let diagnostic = preserveProvisioningDiagnostics(
                bundle: bundle, phase: "minimal-agent", statusURL: statusURL, logURL: logURL)
            await instance.stop()
            var message = "the minimal agent bootstrap never wrote its STATUS readback"
            if let diagnostic { message += "; diagnostic: \(diagnostic.path)" }
            throw MacVMError.agentUnavailable(message)
        }
        await instance.awaitStopped(timeout: 120)
        guard flags.exitCode == 0, flags.agentApp, flags.launchAgent else {
            let diagnostic = preserveProvisioningDiagnostics(
                bundle: bundle, phase: "minimal-agent", statusURL: statusURL, logURL: logURL)
            let detail = Self.provisionLogTail(at: logURL)
            var message = "minimal exec-agent bootstrap failed (exit \(flags.exitCode), "
                + "app=\(flags.agentApp), launchAgent=\(flags.launchAgent))"
            if let detail { message += "; guest log:\n\(detail)" }
            if let diagnostic { message += "; diagnostic: \(diagnostic.path)" }
            throw MacVMError.provisionFailed(message)
        }
        // CA trust is NOT gated, and no longer needs to be. The enrollment profile pins its own CA
        // (`ServerURLPinningCertificateUUIDs`), so `mdmclient` anchors on the root carried in the
        // profile rather than on the guest's trust store — which is the only reason this pipeline is
        // viable at all, since macOS 27 offers no non-interactive way to put a self-issued root in
        // that store (five routes tried and closed: docs/MACOS_VM_MDM_DEBUG_LOG.md, runs 10–18).
        //
        // The boot's trust attempt is kept as best-effort because it is cheap, harmless, and makes the
        // certificate present in the System keychain — but its verdict is recorded, never enforced.
        // Gating on it would fail every build for a condition the design deliberately does not need.
        if !flags.caTrusted {
            provisionLog.info(
                """
                minimal-agent boot: the CA is not in the guest's system trust store (expected on \
                macOS 27) — enrollment relies on the profile's certificate pinning instead
                """)
        }
        // Preserve the log on SUCCESS too, not just on the failure paths above. This boot is where CA
        // trust is established, and its verdict is needed to interpret a failure that surfaces one
        // boot later in the MDM pre-flight — but a successful boot used to write nothing, so the run
        // that actually mattered left no record of what its trust step reported.
        _ = preserveProvisioningDiagnostics(
            bundle: bundle, phase: "minimal-agent", statusURL: statusURL, logURL: logURL)
        return ProvisionResult(
            provisioned: true,
            agentInstalled: true,
            sipDisabled: flags.sipDisabled,
            axAgentReady: false)
    }

    /// Run the full post-policy guest provisioning pass via the safe VirtioFS automount:
    ///   1. stage the provisioner, the signed agent app, the account password, and a host-composed
    ///      bootstrap into ONE read-write virtiofs share;
    ///   2. boot the already-accounted, MDM-managed base with a host-side display surface;
    ///   3. drive the surface's synthesized keyboard to open Terminal and launch the staged bootstrap
    ///      — which primes sudo, runs `provision-macos-guest.sh` (dev toolchain + the native agent +,
    ///      when SIP is off, its TCC grants), writes a `STATUS` readback to the share, and powers off;
    ///   4. poll the share for `STATUS` (which also proves the desktop came up), then await shutdown.
    ///
    /// A missing readback or a nonzero guest result is fatal in ``provisionAndFinalize``. SIP-on may
    /// omit only the optional semantic-AX rows; MDM-backed file/network policy is already installed.
    func provisionBase(
        bundle: MacVMBundle,
        carryAppPaths: [String] = [], carryPackageIDs: [String] = []
    ) async throws -> ProvisionResult {
        let user = MacVMSettings.sshUser
        let password = try resolveAgentPassword()
        guard let scriptURL = resolveProvisionScript() else {
            throw MacVMError.provisionFailed(
                "the bundled provision-macos-guest.sh could not be located")
        }
        guard let surface = surfaceHost else {
            throw MacVMError.provisionFailed(
                "base provisioning drives the guest through the host-side display surface, which "
                    + "isn't available in this context (headless/spike). Build the base from the app.")
        }

        // ── 1. Stage everything into one READ-WRITE virtiofs share (the guest writes STATUS back).
        let fm = FileManager.default
        let stageDir = fm.temporaryDirectory
            .appendingPathComponent("nucleic-provision-\(UUID().uuidString)", isDirectory: true)
        try fm.createDirectory(at: stageDir, withIntermediateDirectories: true)
        defer { try? fm.removeItem(at: stageDir) }
        // Surface the provisioning base as a system-managed VM in the Control panel's Virtual Machines
        // section (mirrors the app/package-injection boots), so the running base is visible while it's
        // being built — with a live activity note that tracks the provisioning phase. Cleared on every
        // exit path. The row is otherwise absent for a base build, which reads as "nothing is happening"
        // when a long provisioning pass (or a wedged one) is actually in flight.
        defer { baseMaintenance = nil }

        try fm.copyItem(
            at: scriptURL, to: stageDir.appendingPathComponent("provision-macos-guest.sh"))
        let passwordURL = stageDir.appendingPathComponent("password")
        try password.write(to: passwordURL, atomically: true, encoding: .utf8)
        try fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: passwordURL.path)

        guard let app = resolveVMAgentApp() else {
            throw MacVMError.provisionFailed(
                "the mandatory NucleicVMAgent.app could not be located for full provisioning")
        }
        try fm.copyItem(at: app, to: stageDir.appendingPathComponent("NucleicVMAgent.app"))
        if let plist = resolveVMAgentPlist(near: app) {
            try fm.copyItem(
                at: plist, to: stageDir.appendingPathComponent(plist.lastPathComponent))
        }
        let agentStaged = true

        // Stage nash next to the provisioner (docs/NASH.md §7.5): Phase 5⅓ installs the `nash`
        // found beside itself to /usr/local/bin — the ONLY shell the in-guest agent runs commands
        // under (no zsh fallback on the exec surface). A base without nash has a dead exec surface,
        // so fail the build up front (Phase 5⅓ also hard-fails in-guest) rather than provisioning
        // a guest that can't run anything.
        guard let nash = resolveNashBinary() else {
            throw MacVMError.provisionFailed(
                "no darwin nash binary is available to stage — nash is the required agent shell in "
                    + "every virtualized environment (docs/NASH.md §7.5). Build it with "
                    + "scripts/build-nash-macos.sh (staged from shell/dist/macos/nash) or use a "
                    + "packaged app that embeds it at Resources/macvm/nash.")
        }
        try fm.copyItem(at: nash, to: stageDir.appendingPathComponent("nash"))

        // Stage any user-picked `.app` bundles (Settings → "Included apps") into a `user-apps/`
        // subdir of the share; the provisioner copies each into the guest's `/Applications`. Best
        // effort per bundle — a copy that fails (bad/huge bundle) just doesn't make it into the base.
        //
        // The set is the current Settings selection UNIONED with `carryAppPaths` — the apps recorded on
        // the base being replaced/reprovisioned — so an app the user had installed here but has since
        // dropped from the "Included apps" list survives a rebuild (docs/MACOS_VM.md §9.1). Filtered to
        // bundles that still exist on the host (`existingAppBundles`); a vanished source is dropped, and
        // deduped by leaf name so a carried path and a settings path for the same app don't double-stage.
        let userApps = Self.dedupedByLeaf(
            Self.existingAppBundles(Self.orderedUnion(MacVMSettings.bundledAppPaths, carryAppPaths)))
        // Bake the host's FULL Xcode in too, unasked — it is the ONLY way a guest can have a `metal`
        // compiler. The Command Line Tools ship no `xcodebuild` (so `-downloadComponent MetalToolchain`,
        // the only supported Metal installer, is unreachable) and `xcrun` can't resolve `metal` unless a
        // full Xcode is the selected developer dir, so a CLT-only clone simply cannot build a shader.
        // Not recorded in `installedAppPaths`: this is re-derived from the host on every build rather
        // than an operator choice to carry forward. A missing host Xcode is fatal: publishing a base
        // without the Apple SDKs merely defers the failure to every session clone and defeats the
        // macOS build surface. Fail while building the base, where the remedy is actionable.
        let hostXcode = Self.preferredHostXcode()
        let operatorXcode = userApps.first { path in
            let leaf = URL(fileURLWithPath: path).lastPathComponent
            return leaf.hasPrefix("Xcode") && leaf.hasSuffix(".app")
                && FileManager.default.isExecutableFile(
                    atPath: URL(fileURLWithPath: path)
                        .appendingPathComponent("Contents/Developer/usr/bin/xcodebuild").path)
        }
        guard let requiredXcode = operatorXcode ?? hostXcode else {
            throw MacVMError.provisionFailed(
                "a full Xcode is required for macOS VM builds, but no usable "
                    + "/Applications/Xcode.app or Xcode-beta.app was found on the host. "
                    + "Install Xcode on the host (or select a full Xcode.app under Included apps), "
                    + "then rebuild the macOS base image.")
        }
        // Always stage exactly one known-good Xcode. Drop named-but-incomplete operator bundles
        // instead of letting their leaf name suppress the usable host copy.
        let optionalApps = userApps.filter { path in
            let leaf = URL(fileURLWithPath: path).lastPathComponent
            return !(leaf.hasPrefix("Xcode") && leaf.hasSuffix(".app"))
        }
        let stagedApps = optionalApps + [requiredXcode]
        if !stagedApps.isEmpty {
            let userAppsDir = stageDir.appendingPathComponent("user-apps", isDirectory: true)
            try fm.createDirectory(at: userAppsDir, withIntermediateDirectories: true)
            for path in stagedApps {
                let src = URL(fileURLWithPath: path)
                let destination = userAppsDir.appendingPathComponent(src.lastPathComponent)
                do {
                    try fm.copyItem(at: src, to: destination)
                } catch {
                    try? fm.removeItem(at: destination)
                    if path == requiredXcode {
                        throw MacVMError.provisionFailed(
                            "could not stage the required \(src.lastPathComponent) into the macOS "
                                + "base provisioning share: \(error)")
                    }
                    let message =
                        "skipping optional included app \(src.path): \(String(describing: error))"
                    provisionLog.warning("\(message, privacy: .public)")
                }
            }
            let stagedXcodebuild = userAppsDir
                .appendingPathComponent(URL(fileURLWithPath: requiredXcode).lastPathComponent)
                .appendingPathComponent("Contents/Developer/usr/bin/xcodebuild")
            guard fm.isExecutableFile(atPath: stagedXcodebuild.path) else {
                throw MacVMError.provisionFailed(
                    "the staged \(URL(fileURLWithPath: requiredXcode).lastPathComponent) is "
                        + "incomplete (Contents/Developer/usr/bin/xcodebuild is missing); "
                        + "the macOS base was not published.")
            }
        }

        // Stage the guest-side installer for any operator-selected "Common packages" (Settings) as
        // `install-packages.sh`; the provisioner runs it near the end and each package fetches +
        // installs itself in the guest (e.g. the latest Chrome, over the guest's NAT network). Nothing
        // selected → no file, and the provisioner skips the phase. Like the apps above, the id set is
        // the Settings selection unioned with `carryPackageIDs` carried from the base being replaced, so
        // a package installed here survives a rebuild even if since deselected. `installShell` filters
        // the union to installable catalog ids.
        let installablePkgIDs = Set(MacVMPackage.catalog.filter { $0.isInstallable }.map { $0.id })
        // The installable subset we're staging — recorded into `bundle.json` for carry-forward.
        let stagedPackageIDs = Self.orderedUnion(MacVMSettings.selectedPackageIDs, carryPackageIDs)
            .filter { installablePkgIDs.contains($0) }
        if let pkgShell = MacVMPackage.installShell(forIDs: stagedPackageIDs) {
            try? pkgShell.write(
                to: stageDir.appendingPathComponent("install-packages.sh"),
                atomically: true, encoding: .utf8)
        }

        // ── 2. Boot with the RW share attached, on a dedicated background queue (never main). The
        //       provisioning surface binds its `VZVirtualMachineView` on the main thread, but the VM
        //       itself runs off-main like every other VM.
        let mac = Self.randomMAC()
        // Keep staging on Apple's automount even though MDM policy is now active. The final readiness
        // boot exercises the custom-tagged production mount explicitly; making the long toolchain pass
        // depend on that mount too would add no coverage and would complicate failure attribution.
        let entryMount = MacVMSpec.Mount(
            host: stageDir.path, name: Self.provisionShareName, readOnly: false,
            recreateHostPath: false)
        let config = try Self.makeConfiguration(
            bundle: bundle, cpus: MacVMSettings.vmCPUs, memoryGiB: MacVMSettings.vmMemoryGiB,
            mac: mac, mounts: [entryMount])

        let bootstrapURL = stageDir.appendingPathComponent(Self.bootstrapScriptName)
        try Self.provisionBootstrapScript(user: user, mountTag: nil).write(
            to: bootstrapURL, atomically: true, encoding: .utf8)
        try fm.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bootstrapURL.path)

        let instance = MacVMInstance(
            configuration: config, label: Self.baseProvisionSurfaceName)
        baseMaintenance = MacVMMaintenanceInfo(
            name: Self.baseProvisionSurfaceName, os: .macOS,
            activity: "Provisioning…", booting: true)
        do {
            try await instance.start()
        } catch {
            throw MacVMError.provisionFailed(
                "could not boot the base for full post-MDM provisioning: \(error)")
        }

        let surfaceName = Self.baseProvisionSurfaceName
        await surface.attach(
            name: surfaceName,
            virtualMachine: UncheckedSendableBox(value: instance.vm as AnyObject))
        // If the operator opted to watch this build, bring the monitor up now that the view is bound.
        if baseObserverRequested { await surface.setObserverVisible(name: surfaceName, visible: true) }

        // ── 3–4. Drive HID → launch the bootstrap → poll STATUS on the share.
        let activePhase: MacVMBaseProgress.Phase = .provisioning
        baseProgress = MacVMBaseProgress(phase: activePhase, fraction: nil)
        let statusURL = stageDir.appendingPathComponent("STATUS")
        let startedURL = stageDir.appendingPathComponent("STARTED")
        let logURL = stageDir.appendingPathComponent("provision.log")
        let flags = await driveHIDBootstrap(
            surface: surface, name: surfaceName, phase: activePhase,
            startedURL: startedURL, statusURL: statusURL, logURL: logURL)

        // Stay on the provisioning row while the toolchain boot powers off; the real finalize stages
        // (readiness verification + sealing) come after this pass returns to provisionAndFinalize.
        baseProgress = MacVMBaseProgress(phase: activePhase, fraction: nil)
        await surface.detach(name: surfaceName)
        await instance.awaitStopped(timeout: 120)  // the bootstrap powers off when done

        guard let flags else {
            let diagnostic = preserveProvisioningDiagnostics(
                bundle: bundle, phase: "full", statusURL: statusURL, logURL: logURL)
            var message = "the base never reached a usable desktop during provisioning "
                + "(no STATUS readback)"
            if let diagnostic { message += "; diagnostic: \(diagnostic.path)" }
            throw MacVMError.agentUnavailable(message)
        }
        let agentInstalled = agentStaged && flags.agentApp && flags.launchAgent
        guard flags.exitCode == 0, agentInstalled else {
            let diagnostic = preserveProvisioningDiagnostics(
                bundle: bundle, phase: "full", statusURL: statusURL, logURL: logURL)
            let detail = Self.provisionLogTail(at: logURL)
            var message = "guest provisioner failed (exit \(flags.exitCode), "
                + "app=\(flags.agentApp), launchAgent=\(flags.launchAgent))"
            if let detail { message += "; guest log:\n\(detail)" }
            if let diagnostic { message += "; diagnostic: \(diagnostic.path)" }
            throw MacVMError.provisionFailed(message)
        }
        let axAgentReady = flags.sipDisabled && flags.tccCount >= 3
        return ProvisionResult(
            provisioned: true, agentInstalled: true,
            sipDisabled: flags.sipDisabled, axAgentReady: axAgentReady,
            installedAppPaths: userApps, installedPackageIDs: stagedPackageIDs)
    }

    /// The staged bootstrap's filename on the share.
    static let bootstrapScriptName = "nucleic-bootstrap.sh"

    /// The provisioning share's logical name. Apple's automount surfaces it at
    /// `/Volumes/My Shared Files/nucleic-provision` — the one guest path reachable before anything
    /// in the guest can run, so it's what the HID launch types.
    static let provisionShareName = "nucleic-provision"

    /// The **custom mountpoint** the bootstrap re-mounts that same share at, and runs the whole
    /// provisioner from. Deliberately space-free: the automount root's spaces have to survive every
    /// shell step and every tool the provisioner shells out to, and a single dropped quote costs a
    /// half-hour build. Under `/Volumes` to stay idiomatic for a mountpoint (and adjacent to the
    /// automount it shadows); the empty directory left behind after the unmount is harmless in the
    /// sealed base.
    static let provisionMountPoint = "/Volumes/nucleic-provision"

    /// Surface (and VM) name for the base-build provisioning VM — the key the diagnostic monitor and
    /// the HID bootstrap both address.
    public static let baseProvisionSurfaceName = "base-provision"

    /// Show or hide the diagnostic monitor window for the in-flight base build. Remembers the request
    /// so it's (re)applied when the provisioning surface next attaches; a no-op when no build is live.
    public func setBaseProvisionObserver(visible: Bool) async {
        baseObserverRequested = visible
        await surfaceHost?.setObserverVisible(name: Self.baseProvisionSurfaceName, visible: visible)
    }

    /// Drive the host-side surface to launch the staged bootstrap, then poll the share for its
    /// `STATUS` readback. Re-attempts the launch (open Spotlight → Terminal → run) until a `STARTED`
    /// sentinel proves the bootstrap is running (so we stop typing into a live install), then just
    /// waits for `STATUS`. Returns `nil` if neither appears before the deadline.
    ///
    /// Each poll it republishes ``baseProgress``: once `STARTED` appears, its `detail` carries the tail
    /// of the guest's `provision.log`, so the long, fraction-less toolchain install shows the step it's
    /// actually on instead of a frozen spinner (no sub-step before then). The Control panel's "Base
    /// image" row, by contrast, holds a single steady "Provisioning…" for the whole build.
    private func driveHIDBootstrap(
        surface: any MacVMSurfaceHost, name: String, phase: MacVMBaseProgress.Phase,
        startedURL: URL, statusURL: URL, logURL: URL,
        timeout: TimeInterval = 1800, maintenanceActivity: String = "Provisioning…",
        initialLaunchDelay: TimeInterval = 8
    ) async -> ProvisionStatusFlags? {
        let fm = FileManager.default
        let deadline = Date().addingTimeInterval(timeout)
        var running = false
        // Hold the FIRST Terminal-launch attempt for a beat: on a fresh boot the desktop/Dock/Spotlight
        // aren't ready the instant the surface attaches, so an immediate `cmd+space` + "Terminal" is
        // typed into nothing and wasted (then the retry is a long wait away). Let the login session
        // settle first — larger on the declarative first boot, which is the slowest.
        var nextLaunch = Date().addingTimeInterval(initialLaunchDelay)
        while Date() < deadline {
            if let text = try? String(contentsOf: statusURL, encoding: .utf8), text.contains("CODE=") {
                return Self.parseProvisionStatus(text)
            }
            if !running, fm.fileExists(atPath: startedURL.path) {
                running = true  // the bootstrap is executing — stop typing, just wait for STATUS
            }
            if !running, Date() >= nextLaunch {
                // Input is delivered straight to the guest's virtual keyboard (background; no focus
                // stealing), so we can just type whenever we retry the launch.
                await Self.typeBootstrapLaunch(surface: surface, name: name)
                nextLaunch = Date().addingTimeInterval(25)  // retry login-timing until STARTED appears
            }
            let detail = running
                ? (Self.lastProvisionLogLine(at: logURL) ?? "Running the provisioner in the guest…")
                : nil
            baseProgress = MacVMBaseProgress(phase: phase, fraction: nil, detail: detail)
            // The Control panel's "Base image" row shows one steady status for the whole build; it's
            // no longer "booting" once the bootstrap has signalled STARTED.
            baseMaintenance = MacVMMaintenanceInfo(
                name: name, os: .macOS, activity: maintenanceActivity, booting: !running)
            try? await Task.sleep(nanoseconds: 1_000_000_000)
        }
        return nil
    }

    /// The last non-empty line of the guest's `provision.log`, trimmed and length-bounded — the live
    /// step to surface as base-build progress while the (indeterminate) toolchain install runs. `nil`
    /// when the log isn't readable yet.
    static func lastProvisionLogLine(at url: URL) -> String? {
        guard let text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
        guard let line = text.split(whereSeparator: \.isNewline)
            .last(where: { !$0.trimmingCharacters(in: .whitespaces).isEmpty })
        else { return nil }
        let trimmed = line.trimmingCharacters(in: .whitespaces)
        return trimmed.count > 140 ? String(trimmed.prefix(140)) + "…" : trimmed
    }

    /// A bounded multi-line failure excerpt for the surfaced error and persisted diagnostics.
    static func provisionLogTail(
        at url: URL, maxLines: Int = 20, maxCharacters: Int = 4_000
    ) -> String? {
        guard let text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
        let lines = text.split(whereSeparator: \.isNewline)
            .suffix(max(1, maxLines)).map(String.init)
        guard !lines.isEmpty else { return nil }
        let joined = lines.joined(separator: "\n")
        return joined.count > maxCharacters ? String(joined.suffix(maxCharacters)) : joined
    }

    /// Copy transient guest evidence beside the base before the staging directory is removed.
    /// Password files and staged binaries are deliberately excluded.
    @discardableResult
    private func preserveProvisioningDiagnostics(
        bundle: MacVMBundle, phase: String, statusURL: URL, logURL: URL
    ) -> URL? {
        let fm = FileManager.default
        let directory = bundle.provisioningDiagnosticsURL.appendingPathComponent(
            "\(phase)-\(UUID().uuidString.lowercased())", isDirectory: true)
        do {
            try fm.createDirectory(at: directory, withIntermediateDirectories: true)
            try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: directory.path)
            var copied = false
            for (source, name) in [(statusURL, "STATUS"), (logURL, "provision.log")] {
                guard fm.fileExists(atPath: source.path) else { continue }
                let destination = directory.appendingPathComponent(name)
                try fm.copyItem(at: source, to: destination)
                try fm.setAttributes(
                    [.posixPermissions: 0o600], ofItemAtPath: destination.path)
                copied = true
            }
            if copied { return directory }
            try? fm.removeItem(at: directory)
            return nil
        } catch {
            return nil
        }
    }

    /// Synthesize the keystrokes that open Terminal via Spotlight and run the staged bootstrap. Timed
    /// generously — this is a one-time base build, not a latency-sensitive path.
    private static func typeBootstrapLaunch(surface: any MacVMSurfaceHost, name: String) async {
        func pause(_ seconds: Double) async {
            try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
        }
        // Dismiss anything focus-stealing, open Spotlight, search + launch Terminal.
        await surface.send(name: name, .key(chord: "esc"))
        await pause(0.8)
        await surface.send(name: name, .key(chord: "cmd+space"))
        await pause(1.5)  // Spotlight can be slow to accept input on a freshly-booted desktop
        await surface.send(name: name, .text("Terminal"))
        await pause(1.2)
        await surface.send(name: name, .key(chord: "return"))
        await pause(4.0)  // Terminal cold-launch
        // Terminal has just taken keyboard focus, and the FIRST synthesized keystroke after a focus
        // change is intermittently dropped by the guest — which turns "/bin/bash …" into "bin/bash …"
        // ("command not found", re-typed every retry until a keystroke finally lands). Guard the leading
        // slash two ways: (1) a throwaway warm-up keystroke absorbs a dropped first key before the real
        // command, and (2) the command itself leads with a space, so if a key is still dropped it costs
        // that harmless space rather than the slash (bash ignores leading whitespace before a command).
        await surface.send(name: name, .text(" "))
        await pause(0.5)
        // Run the staged bootstrap from the automount — the only share path allowed before the MDM
        // Network Volumes policy has been installed and verified.
        let entry = guestSharePath(os: .macOS, name: provisionShareName)
        let command = " /bin/bash '\(entry)/\(bootstrapScriptName)'"
        await surface.send(name: name, .text(command))
        await surface.send(name: name, .key(chord: "return"))
    }

    /// The host-composed bootstrap the guest runs (via HID) — network-free: it primes passwordless
    /// sudo, runs the provisioner, writes a `CODE=… SIP=… APP=… LA=… TCC=…` readback to `STATUS` on
    /// the share, leaves the sudo drop-in installed for agent turns, and powers off. Reads the account
    /// password from the staged `password` file (no password typing). The `STARTED` sentinel tells the
    /// host to stop re-typing.
    ///
    /// It enters through Apple's automount (the only share path reachable cold) and, as soon as it has
    /// passwordless sudo, re-mounts the SAME share at ``provisionMountPoint`` from `mountTag`'s device
    /// and does everything else from there — a path with no spaces to quote. `mountTag` is `nil` when
    /// that device isn't attached, which keeps the whole run on the automount path.
    static func provisionBootstrapScript(
        user: String, mountTag: String?, mountPoint: String = provisionMountPoint
    ) -> String {
        let entry = guestSharePath(os: .macOS, name: provisionShareName)
        // Best effort, and verified before it's adopted: an unmountable device, or one that somehow
        // isn't this share, leaves SHARE on the automount and the build proceeds exactly as before.
        let remount = mountTag.map { tag in
            """

            # Everything below runs from a SPACE-FREE mountpoint. The provisioner hands its own path to
            # dozens of shell steps (`$0`-derived asset lookups, log redirection, installer/plist
            # tooling); on `/Volumes/My Shared Files/…` each one is a quoting bug waiting to happen.
            # Same share, same files — just a mountpoint that can't be word-split. Best effort: if the
            # mount doesn't take we stay on the automount path.
            if sudo /bin/mkdir -p '\(mountPoint)' \\
              && sudo /sbin/mount_virtiofs '\(tag)' '\(mountPoint)' \\
              && [ -f '\(mountPoint)/provision-macos-guest.sh' ]; then
              SHARE='\(mountPoint)'
            fi
            """
        } ?? ""
        // Leave the sealed base clean: the readback is already written and synced, so drop the
        // ephemeral mount and its now-empty directory before powering off.
        let unmount = mountTag == nil
            ? ""
            : "sudo /sbin/umount '\(mountPoint)' 2>/dev/null || true\n"
                + "sudo /bin/rmdir '\(mountPoint)' 2>/dev/null || true"
        let plist = "/Library/LaunchAgents/xyz.blakeslee.nucleic.vmagent.plist"
        let tccDB = "/Library/Application Support/com.apple.TCC/TCC.db"
        let tccQuery =
            "SELECT count(*) FROM access WHERE service IN "
            + "('kTCCServiceScreenCapture','kTCCServiceAccessibility','kTCCServicePostEvent') "
            + "AND auth_value=2;"
        return """
        #!/bin/bash
        # The HID-typed launch can only reach Apple's automount, so that's where we enter.
        SHARE="\(entry)"
        touch "$SHARE/STARTED" 2>/dev/null || true
        PW="$(cat "$SHARE/password")"
        # Install durable passwordless sudo for the agent account. Provisioning and later agent turns
        # are both non-interactive, so neither can satisfy a password prompt.
        printf '%s\\n' "$PW" | sudo -S sh -c 'grep -q "includedir /private/etc/sudoers.d" /etc/sudoers || printf "%s\\n" "@includedir /private/etc/sudoers.d" >> /etc/sudoers; printf "%s\\n" "\(user) ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/nucleic-agent; chmod 0440 /etc/sudoers.d/nucleic-agent' 2>/dev/null
        \(remount)
        NUCLEIC_AGENT_PW="$PW" NUCLEIC_PROVISION_NO_SHUTDOWN=1 NUCLEIC_PROVISION_SHARE="$SHARE" /bin/bash "$SHARE/provision-macos-guest.sh" "" "$PW" > "$SHARE/provision.log" 2>&1
        CODE=$?
        SIP=$(csrutil status 2>/dev/null | grep -qi disabled && echo 1 || echo 0)
        APP=$(test -d /Applications/NucleicVMAgent.app && echo 1 || echo 0)
        LA=$(test -f "\(plist)" && echo 1 || echo 0)
        TCC=$(sudo sqlite3 "\(tccDB)" "\(tccQuery)" 2>/dev/null || echo 0)
        printf 'CODE=%s SIP=%s APP=%s LA=%s TCC=%s\\n' "$CODE" "$SIP" "$APP" "$LA" "$TCC" > "$SHARE/STATUS"
        sync
        if [ "$CODE" -eq 0 ]; then
          echo "✓ Full provisioning completed; shutting down cleanly for base publication."
        else
          echo "✗ Full provisioning failed (exit $CODE); status and log were synced before shutdown." >&2
        fi
        \(unmount)
        sudo shutdown -h now
        """
    }
}
#endif
