import CoreGraphics
import CoreText
import Foundation
import ImageIO
import NucleicProtocol
import Testing
import UniformTypeIdentifiers

@testable import NucleicCore

/// Unit coverage for the pure/logic surface of the macOS-VM subsystem (docs/MACOS_VM.md). The VZ
/// runtime itself (install / boot / SSH) needs Apple silicon + a provisioned base and is exercised by
/// `macvm-spike`, not here — these tests pin the naming, MAC/lease parsing, SSH command assembly,
/// spec clamping, and settings that must stay correct without a VM.
@Suite struct MacVMTests {

    // MARK: - Naming

    @Test func vmNameIsLowercasedMacSiblingWithChannelSuffix() {
        let sid = SessionID(rawValue: "AB12CD34EF")
        let name = MacVMManager.vmName(for: sid)
        #expect(name.hasPrefix("nucleic-mac-"))
        #expect(name == name.lowercased())
        #expect(name.hasSuffix(ContainerManager.channelSuffix))
        // The short id (lowercased) sits between the prefix and the channel suffix.
        #expect(name.contains(sid.short.lowercased()))
    }

    // MARK: - Failed suspend-to-disk restore (the guest cold-boots; state is GONE)

    /// A restore VZ refuses cold-boots the guest, so the caller that was promised its state back has to
    /// be told it isn't coming. The reason string is what carries that news — keep it specific enough
    /// to act on (which layer refused, and its code) and never empty.
    @Test func restoreFailureReasonNamesTheFrameworkAndCode() {
        // The observed shape: VZ rejects a saved state whose config it won't accept (code 12).
        let vz = NSError(domain: "VZErrorDomain", code: 12, userInfo: [
            NSLocalizedDescriptionKey: "The virtual machine failed to restore with error “invalid argument”."
        ])
        let reason = MacVMEngine.restoreFailureReason(vz)
        #expect(reason.contains("12"))
        #expect(reason.lowercased().contains("rejected"))

        // A non-VZ failure (a corrupt/unreadable save file) falls back to the system message rather
        // than inventing a framework attribution.
        let io = NSError(domain: NSCocoaErrorDomain, code: 260, userInfo: [
            NSLocalizedDescriptionKey: "The file couldn’t be opened because it doesn’t exist."
        ])
        let ioReason = MacVMEngine.restoreFailureReason(io)
        #expect(ioReason.contains("couldn’t be opened"))
        #expect(!ioReason.contains("VZErrorDomain"))
        #expect(!ioReason.isEmpty)
    }

    // MARK: - VM lifecycle tool (mac_vm_control / linux_vm_control) reply framing

    @Test func vmControlReplyWireJSONCarriesStateOrDenial() throws {
        let ok = try JSONValue(parsing: Data(
            MCPApprovalServer.VMControlReply.ok(state: "suspended", message: "frozen").wireJSON().utf8))
        #expect(ok["ok"]?.boolValue == true)
        #expect(ok["state"]?.stringValue == "suspended")
        #expect(ok["message"]?.stringValue == "frozen")
        let denied = try JSONValue(parsing: Data(
            MCPApprovalServer.VMControlReply.denied(message: "not running").wireJSON().utf8))
        #expect(denied["denied"]?.boolValue == true)
        #expect(denied["message"]?.stringValue == "not running")
        #expect(denied["state"] == nil)  // a denial carries no lifecycle state
    }

    // MARK: - MAC normalization + lease parsing

    @Test func normalizeMACIsLeadingZeroInsensitive() {
        // The lease file drops leading zeros; VZMACAddress keeps them. Both must normalize equal.
        #expect(MacVMEngine.normalizeMAC("2:34:5:6:7:8") == "02:34:05:06:07:08")
        #expect(MacVMEngine.normalizeMAC("D6:A7:58:8E:78:D4") == "d6:a7:58:8e:78:d4")
        #expect(
            MacVMEngine.normalizeMAC("02:34:05:06:07:08")
                == MacVMEngine.normalizeMAC("2:34:5:6:7:8"))
    }

    @Test func parseLeasesFindsIPForMACIgnoringLeadingZeros() {
        let leases = """
        {
        \tname=vm-a
        \tip_address=192.168.64.7
        \thw_address=1,d6:a7:58:8e:78:d4
        \tidentifier=1,d6:a7:58:8e:78:d4
        \tlease=0x600000
        }
        {
        \tname=vm-b
        \tip_address=192.168.64.9
        \thw_address=1,2:34:5:6:7:8
        }
        """
        // Query with the zero-padded form; the lease stores the stripped form.
        #expect(MacVMEngine.parseLeases(leases, forMAC: "02:34:05:06:07:08") == "192.168.64.9")
        #expect(MacVMEngine.parseLeases(leases, forMAC: "d6:a7:58:8e:78:d4") == "192.168.64.7")
        #expect(MacVMEngine.parseLeases(leases, forMAC: "aa:bb:cc:dd:ee:ff") == nil)
    }

    @Test func parseLeasesTakesNewestMatchingLease() {
        let leases = """
        {
        \tip_address=192.168.64.2
        \thw_address=1,de:ad:be:ef:00:01
        }
        {
        \tip_address=192.168.64.20
        \thw_address=1,de:ad:be:ef:00:01
        }
        """
        #expect(MacVMEngine.parseLeases(leases, forMAC: "de:ad:be:ef:00:01") == "192.168.64.20")
    }

    // MARK: - SSH command assembly

    @Test func shQuoteWrapsAndEscapesSingleQuotes() {
        #expect(MacVMEngine.shQuote("simple") == "'simple'")
        #expect(MacVMEngine.shQuote("a'b") == "'a'\\''b'")
    }

    @Test func remoteScriptExportsEnvThenCdsThenRunsBody() {
        let script = MacVMEngine.remoteScript(
            workdir: "/Volumes/My Shared Files/workspace",
            env: ["FOO": "bar", "BAZ": "x'y"],  // sorted by key: BAZ before FOO
            body: "xcodebuild test")
        #expect(script.contains("export BAZ='x'\\''y';"))  // single quotes escaped
        #expect(script.contains("export FOO='bar';"))
        // Env exports precede the cd, which precedes the body.
        let bazIdx = script.range(of: "export BAZ=")!.lowerBound
        let cdIdx = script.range(of: "cd '/Volumes/My Shared Files/workspace' || exit 1;")!.lowerBound
        #expect(bazIdx < cdIdx)
        #expect(script.hasSuffix("xcodebuild test"))
    }

    @Test func remoteScriptWithoutWorkdirSkipsCd() {
        let script = MacVMEngine.remoteScript(workdir: nil, env: [:], body: "echo hi")
        #expect(!script.contains("cd "))
        #expect(script == "echo hi")
    }

    // MARK: - Host-path re-creation

    @Test func hostPathScriptMacMountsOriginalPathDirectly() {
        let script = MacVMEngine.hostPathRecreationScript(
            os: .macOS,
            mounts: [MacVMSpec.Mount(host: "/Users/me/proj", name: "workspace", readOnly: false)])
        let s = try! #require(script)
        // A restored VM may already have the mount; the setup is idempotent.
        #expect(s.contains("/sbin/mount | /usr/bin/grep -Fq ' on /Users/me/proj ('"))
        // Migrate only the exact symlink produced by the old automount implementation.
        #expect(s.contains("$(/usr/bin/readlink '/Users/me/proj')"))
        #expect(s.contains("= '/Volumes/My Shared Files/workspace'"))
        #expect(s.contains("sudo /bin/rm '/Users/me/proj'"))
        #expect(s.contains("refusing to replace unrelated symlink"))
        #expect(s.contains("refusing to hide existing path"))
        // The custom single-directory device is attached at the real original path.
        #expect(s.contains("sudo /bin/mkdir -p '/Users/me/proj'"))
        #expect(s.contains(
            "sudo /sbin/mount_virtiofs 'nucleic-mount-0' '/Users/me/proj'"))
        #expect(!s.contains("ln -sfn"))
    }

    @Test func macShareTagsAreStableShortAndDirectMountPolicyHonorsOptOut() {
        #expect(MacVMEngine.macOSShareTag(index: 0) == "nucleic-mount-0")
        #expect(MacVMEngine.macOSShareTag(index: 123).utf8.count < 36)
        #expect(MacVMEngine.directMacOSMount(
            MacVMSpec.Mount(host: "/Users/me/proj", name: "workspace", readOnly: false)))
        #expect(!MacVMEngine.directMacOSMount(
            MacVMSpec.Mount(
                host: "/Users/me/proj", name: "workspace", readOnly: false,
                recreateHostPath: false)))
    }

    @Test func hostPathScriptLinuxBindMountsWithSymlinkFallback() {
        let script = MacVMEngine.hostPathRecreationScript(
            os: .linux,
            mounts: [MacVMSpec.Mount(host: "/Users/me/proj", name: "workspace", readOnly: false)])
        let s = try! #require(script)
        // Mounts the session virtiofs at the share root first…
        #expect(s.contains("mount -t virtiofs 'nucleicshare' '/mnt/nucleic'"))
        // …then bind-mounts the share at the identical host path, symlinking if the bind can't be made.
        #expect(s.contains("mkdir -p '/Users/me/proj'"))
        #expect(s.contains("mount --bind '/mnt/nucleic/workspace' '/Users/me/proj'"))
        #expect(s.contains("ln -sfn '/mnt/nucleic/workspace' '/Users/me/proj'"))
        // Linux runs as root — no sudo needed.
        #expect(!s.contains("sudo "))
    }

    @Test func hostPathScriptSkipsWhenHostEqualsGuestPath() {
        // A mount whose host path already IS the guest share path would self-reference — nothing to do.
        #expect(MacVMEngine.hostPathRecreationScript(
            os: .macOS,
            mounts: [MacVMSpec.Mount(
                host: "/Volumes/My Shared Files/workspace", name: "workspace", readOnly: false)]) == nil)
        #expect(MacVMEngine.hostPathRecreationScript(
            os: .linux,
            mounts: [MacVMSpec.Mount(
                host: "/mnt/nucleic/workspace", name: "workspace", readOnly: false)]) == nil)
    }

    @Test func hostPathScriptRespectsOptOutAndEmptyMounts() {
        #expect(MacVMEngine.hostPathRecreationScript(os: .macOS, mounts: []) == nil)
        #expect(MacVMEngine.hostPathRecreationScript(
            os: .macOS,
            mounts: [MacVMSpec.Mount(
                host: "/Users/me/proj", name: "workspace", readOnly: false,
                recreateHostPath: false)]) == nil)
    }

    @Test func hostPathScriptHandlesMultipleMounts() {
        let script = MacVMEngine.hostPathRecreationScript(
            os: .macOS,
            mounts: [
                MacVMSpec.Mount(host: "/Users/me/proj", name: "workspace", readOnly: false),
                MacVMSpec.Mount(host: "/opt/data", name: "data", readOnly: true),
            ])
        let s = try! #require(script)
        #expect(s.contains(
            "mount_virtiofs 'nucleic-mount-0' '/Users/me/proj'"))
        #expect(s.contains(
            "mount_virtiofs 'nucleic-mount-1' '/opt/data'"))
    }

    @Test func workdirPrefixPrefersIdenticalPathThenFallsBack() {
        let prefix = MacVMSpec.workdirPrefix(["/Users/me/proj", "/Volumes/My Shared Files/workspace"])
        // Tries the identical host path first, then the (space-containing, so quoted) share path, and
        // never fails the command if neither exists.
        #expect(prefix
            == "cd '/Users/me/proj' 2>/dev/null || cd '/Volumes/My Shared Files/workspace' 2>/dev/null || true; ")
    }

    @Test func workdirPrefixDropsEmptyCandidatesAndReturnsEmptyForNone() {
        #expect(MacVMSpec.workdirPrefix([]) == "")
        #expect(MacVMSpec.workdirPrefix(["", ""]) == "")
        // A single usable candidate still terminates with the `|| true` guard.
        #expect(MacVMSpec.workdirPrefix(["", "/mnt/nucleic/workspace"])
            == "cd '/mnt/nucleic/workspace' 2>/dev/null || true; ")
    }

    // MARK: - vsock exec framing (the SSH exec path was retired for the in-guest agent)

    @Test func execRequestLineCarriesOpAndCommand() throws {
        let line = MacVMAgentWire.requestLine(
            op: MacVMAgentWire.Exec.op,
            fields: [MacVMAgentWire.Exec.commandKey: .string("echo ok")])
        #expect(line.last == 0x0A)  // NDJSON: one object per line
        let obj = try JSONValue(parsing: line.dropLast()).objectValue
        #expect(obj?["op"]?.stringValue == "exec")
        #expect(obj?[MacVMAgentWire.Exec.commandKey]?.stringValue == "echo ok")
    }

    @Test func execFrameLineHasTagButNoOp() throws {
        // Streaming frames carry a `t` tag, not an `op` — `requestLineRaw` must not inject one.
        let frame = MacVMAgentWire.requestLineRaw([
            MacVMAgentWire.Exec.tagKey: .string(MacVMAgentWire.Exec.signal),
            MacVMAgentWire.Exec.signalKey: .number(9),
        ])
        let obj = try JSONValue(parsing: frame.dropLast()).objectValue
        #expect(obj?["op"] == nil)
        #expect(obj?[MacVMAgentWire.Exec.tagKey]?.stringValue == "sig")
        #expect(obj?[MacVMAgentWire.Exec.signalKey]?.intValue == 9)  // whole number renders as int
    }

    // MARK: - Spec

    @Test func specClampsResourcesToAtLeastOne() {
        let spec = MacVMSpec(name: "nucleic-mac-x", cpus: 0, memoryGiB: -4)
        #expect(spec.cpus == 1)
        #expect(spec.memoryGiB == 1)
    }

    @Test func specRenamedKeepsEverythingButName() {
        let spec = MacVMSpec(
            name: "a", cpus: 6, memoryGiB: 12,
            mounts: [MacVMSpec.Mount(host: "/repo", name: "workspace", readOnly: false)],
            workdir: "/w", env: ["K": "V"], sshUser: "agent")
        let renamed = spec.renamed("b")
        #expect(renamed.name == "b")
        #expect(renamed.cpus == 6)
        #expect(renamed.memoryGiB == 12)
        #expect(renamed.mounts == spec.mounts)
        #expect(renamed.workdir == "/w")
        #expect(renamed.env == ["K": "V"])
    }

    // MARK: - Restore image versioning

    @Test func restoreCacheNameTracksImageIdentity() {
        // The IPSW filename encodes the macOS version/build, so it IS the cache key — different
        // versions land in different files (the fix that lets the fetch path move up to macOS 27).
        let v26 = URL(string: "https://updates.cdn-apple.com/x/UniversalMac_26.0_25A123_Restore.ipsw")!
        let v27 = URL(string: "https://updates.cdn-apple.com/y/UniversalMac_27.0_26A456_Restore.ipsw")!
        #expect(MacVMEngine.restoreCacheName(for: v26) == "UniversalMac_26.0_25A123_Restore.ipsw")
        #expect(MacVMEngine.restoreCacheName(for: v27) == "UniversalMac_27.0_26A456_Restore.ipsw")
        #expect(MacVMEngine.restoreCacheName(for: v26) != MacVMEngine.restoreCacheName(for: v27))
    }

    @Test func restoreCacheNameAppendsIpswWhenMissing() {
        let noExt = URL(string: "https://example.com/downloads/some-restore")!
        #expect(MacVMEngine.restoreCacheName(for: noExt).hasSuffix(".ipsw"))
    }

    @Test func restoreImageURLSettingReads() async throws {
        let suite = UserDefaults(suiteName: "macvm-url-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            #expect(MacVMSettings.restoreImageURL == nil)
            suite.set("https://example.com/UniversalMac_27.0.ipsw", forKey: MacVMSettings.restoreImageURLKey)
            #expect(MacVMSettings.restoreImageURL == "https://example.com/UniversalMac_27.0.ipsw")
        }
    }

    // MARK: - Capability

    @Test func supportedIffNoUnsupportedReason() {
        #expect(MacVMEngine.isSupported == (MacVMEngine.unsupportedReason == nil))
        #expect(MacVMManager.isSupported == MacVMEngine.isSupported)
    }

    // MARK: - Base progress labels

    @Test func baseProgressLabelsAreDistinctAndNonEmpty() {
        // Every phase — including the Lane B finalize sub-stages that split the old opaque
        // "Finalizing the base image" — must have a distinct, non-empty checklist label.
        let phases: [MacVMBaseProgress.Phase] = [
            .downloadingRestoreImage, .installing, .firstBootSetup, .provisioning,
            .installingAgent, .disablingSIP, .writingGrants, .reenablingSIP, .verifyingPolicy,
            .applyingPolicy, .verifyingReadiness, .sealing, .finalizing, .ready,
        ]
        let labels = phases.map { MacVMBaseProgress(phase: $0).label }
        #expect(Set(labels).count == labels.count)
        #expect(labels.allSatisfy { !$0.isEmpty })
    }

    @Test func linuxBaseProgressLabelsAreLinuxWordedNotMacOS() {
        // The settings checklist renders these for a Linux build too; they must not say "macOS".
        let phases: [MacVMBaseProgress.Phase] = [.downloadingRestoreImage, .installing, .provisioning, .ready]
        for phase in phases {
            let label = MacVMBaseProgress(phase: phase).label(for: .linux)
            #expect(!label.isEmpty)
            #expect(!label.contains("macOS"))
            #expect(!label.contains("restore image"))
        }
        #expect(MacVMBaseProgress(phase: .ready).label(for: .linux) == "Base narOS image ready")
        // The macOS phrasing stays macOS-worded.
        #expect(MacVMBaseProgress(phase: .ready).label(for: .macOS) == "Base macOS image ready")
    }

    @Test func provisionErrorDescriptionIsOSNeutral() {
        // A Linux base-build failure flows through the shared MacVMError, so its prefix must not
        // hardcode "macOS" (the wrapped detail names the OS).
        let desc = String(describing: MacVMError.provisionFailed("the Linux guest agent is missing"))
        #expect(!desc.contains("macOS"))
        #expect(desc.hasPrefix("Failed to provision the base VM:"))
    }

    @Test func baseBundleKeepsMDMCredentialsHostSideBesideMetadata() {
        let bundle = MacVMBundle(root: URL(fileURLWithPath: "/tmp/example.bundle"))
        #expect(bundle.mdmStateURL.lastPathComponent == "mdm-state.json")
        // Compare paths, not URLs: `deletingLastPathComponent()` returns a directory URL (trailing
        // slash) while `root` here does not, and URL equality is literal about that distinction.
        #expect(bundle.mdmStateURL.deletingLastPathComponent().path == bundle.root.path)
        #expect(bundle.mdmStateURL != bundle.metadataURL)
        // Diagnostics live OUTSIDE the bundle, keyed by its name. Inside it, they were destroyed by
        // the next clean rebuild or "Delete & reinstall" — so the evidence for a failed enrollment was
        // routinely deleted by the first step taken to investigate it.
        #expect(bundle.mdmDiagnosticsURL.path == "/tmp/Diagnostics/example.bundle/MDM")
        #expect(
            bundle.provisioningDiagnosticsURL.path == "/tmp/Diagnostics/example.bundle/Provisioning")
        #expect(!bundle.mdmDiagnosticsURL.path.hasPrefix(bundle.root.path + "/"))
    }

    // MARK: - Base status (bundle.json ⇄ MacVMBaseStatus, provisioning readback)

    @Test func baseStatusJSONRoundTripsAndDefaultsMissingKeys() {
        let full = MacVMBaseStatus(
            installed: true, accountProvisioned: true, provisioned: true, agentInstalled: true,
            sipDisabled: true, axAgentReady: true, osVersion: "27.0", buildVersion: "26A1",
            installedAppPaths: ["/Apps/Foo.app", "/Apps/Bar.app"], installedPackageIDs: ["chrome"],
            mdmEnrolled: true, profilesInstalled: true)
        // Round-trip through the dictionary the bundle.json is (de)serialized as.
        let back = MacVMBaseStatus(json: full.dictionary)
        #expect(back == full)
        #expect(back.mdmEnrolled)
        #expect(back.profilesInstalled)
        // The MDM flags default false for a base built before they existed, and are omitted from the
        // dictionary when false (keeps old bundle.json clean).
        let noMDM = MacVMBaseStatus(json: ["installed": true])
        #expect(!noMDM.mdmEnrolled)
        #expect(!noMDM.profilesInstalled)
        #expect(MacVMBaseStatus(installed: true).dictionary["mdmEnrolled"] == nil)
        #expect(back.installedAppPaths == ["/Apps/Foo.app", "/Apps/Bar.app"])
        #expect(back.installedPackageIDs == ["chrome"])
        // Computer use is host-side, so "ready" == installed (no provisioning / SIP).
        #expect(MacVMBaseStatus(installed: true).computerUseReady)
        #expect(!MacVMBaseStatus().computerUseReady)
        // A legacy base's `computerUseReady` key maps onto the AX-agent readiness (its old meaning).
        let legacy = MacVMBaseStatus(json: ["installed": true, "computerUseReady": true, "osVersion": "26.0"])
        #expect(legacy.installed)
        #expect(legacy.axAgentReady)
        #expect(legacy.osVersion == "26.0")
    }

    @Test func baseStatusDefaultsInstalledAppsPackagesEmptyForOlderBundle() {
        // A bundle.json predating the carry-forward keys reads back as empty (not nil / crash), and a
        // status with no recorded apps omits the keys from the dictionary (keeps old JSON clean).
        let old = MacVMBaseStatus(json: ["installed": true, "provisioned": true])
        #expect(old.installedAppPaths.isEmpty)
        #expect(old.installedPackageIDs.isEmpty)
        #expect(MacVMBaseStatus(installed: true).dictionary["installedAppPaths"] == nil)
        #expect(MacVMBaseStatus(installed: true).dictionary["installedPackageIDs"] == nil)
    }

    @Test func orderedUnionDedupesPreservingFirstSeenOrder() {
        // Settings selection wins order; a value in both appears once; new carried values append.
        #expect(
            MacVMEngine.orderedUnion(["a", "b"], ["b", "c"]) == ["a", "b", "c"])
        #expect(MacVMEngine.orderedUnion([], ["x"]) == ["x"])
        #expect(MacVMEngine.orderedUnion(["x"], []) == ["x"])
        #expect(MacVMEngine.orderedUnion(["a", "a"], ["a"]) == ["a"])
    }

    @Test func dedupedByLeafKeepsFirstPathPerAppName() {
        // Two source paths for the same `Foo.app` collapse to the first; distinct leaves both survive.
        #expect(
            MacVMEngine.dedupedByLeaf(["/one/Foo.app", "/two/Foo.app", "/three/Bar.app"])
                == ["/one/Foo.app", "/three/Bar.app"])
    }

    @Test func preferredHostXcodePicksStableOverBetaAndNeedsXcodebuild() {
        // A full Xcode is identified by the `xcodebuild` the Command Line Tools don't ship — that
        // binary is the only supported Metal-toolchain installer, so a candidate without it is useless.
        let has: (String) -> Bool = { path in
            path.hasPrefix("/Applications/Xcode.app") || path.hasPrefix("/Applications/Xcode-beta.app")
        }
        #expect(MacVMEngine.preferredHostXcode(exists: has) == "/Applications/Xcode.app")
        // Only the beta installed → the beta; stable is preferred only when it's really there.
        #expect(
            MacVMEngine.preferredHostXcode(exists: { $0.hasPrefix("/Applications/Xcode-beta.app") })
                == "/Applications/Xcode-beta.app")
        // A bare bundle with no xcodebuild (a CLT-only host, or a stub) is not a full Xcode.
        #expect(MacVMEngine.preferredHostXcode(exists: { _ in false }) == nil)
    }

    @Test func addingHostXcodeAppendsUnlessTheOperatorStagedTheirOwn() {
        // The host Xcode rides along with the operator's picks so every clone can compile Metal.
        #expect(
            MacVMEngine.addingHostXcode(["/Applications/Foo.app"], hostXcode: "/Applications/Xcode.app")
                == ["/Applications/Foo.app", "/Applications/Xcode.app"])
        // An operator-staged Xcode wins — never two Xcodes in one /Applications.
        #expect(
            MacVMEngine.addingHostXcode(
                ["/Volumes/x/Xcode-beta.app"], hostXcode: "/Applications/Xcode.app")
                == ["/Volumes/x/Xcode-beta.app"])
        // No host Xcode ⇒ the staged set is untouched (the base builds, just without `metal`).
        #expect(MacVMEngine.addingHostXcode(["/Applications/Foo.app"], hostXcode: nil)
            == ["/Applications/Foo.app"])
    }

    @Test func pendingBaseCarryPersistsSetAndClears() async throws {
        let suite = UserDefaults(suiteName: "macvm-carry-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            #expect(MacVMSettings.pendingBaseCarryApps.isEmpty)
            #expect(MacVMSettings.pendingBaseCarryPackages.isEmpty)
            // A base being deleted stashes its recorded set for the next build to restore.
            MacVMSettings.setPendingBaseCarry(apps: ["/Apps/Foo.app"], packages: ["chrome"])
            #expect(MacVMSettings.pendingBaseCarryApps == ["/Apps/Foo.app"])
            #expect(MacVMSettings.pendingBaseCarryPackages == ["chrome"])
            // A successful replacement build clears it (the new base's bundle.json now holds the set).
            MacVMSettings.clearPendingBaseCarry()
            #expect(MacVMSettings.pendingBaseCarryApps.isEmpty)
            #expect(MacVMSettings.pendingBaseCarryPackages.isEmpty)
            // An empty stash write removes the keys rather than persisting empty arrays.
            MacVMSettings.setPendingBaseCarry(apps: [], packages: [])
            #expect(suite.object(forKey: MacVMSettings.pendingBaseCarryAppsKey) == nil)
        }
    }

    @Test func baseStatusSummaryReflectsReadiness() {
        #expect(MacVMBaseStatus().summary.contains("No base"))
        #expect(MacVMBaseStatus(installed: true).summary.contains("account"))  // installed, no account yet
        // A provisioned base: computer use works host-side (no SIP mentioned).
        let provisioned = MacVMBaseStatus(installed: true, accountProvisioned: true, provisioned: true)
        #expect(provisioned.summary.contains("computer use"))
        #expect(!provisioned.summary.contains("SIP"))
        #expect(MacVMBaseStatus(
            installed: true, accountProvisioned: true, provisioned: true, agentInstalled: true,
            sipDisabled: true, axAgentReady: true).summary.contains("AX"))
    }

    // MARK: - Host-side input keymap + scroll

    @Test func keyMapParsesChordsWithModifiers() {
        let s = MacVMKeyMap.stroke(forChord: "cmd+shift+s")
        #expect(s?.keyCode == 0x01)  // 's'
        #expect(s?.command == true)
        #expect(s?.shift == true)
        #expect(MacVMKeyMap.stroke(forChord: "return")?.keyCode == 0x24)
        #expect(MacVMKeyMap.stroke(forChord: "enter")?.keyCode == 0x24)  // alias
        #expect(MacVMKeyMap.stroke(forChord: "boguskey") == nil)
    }

    @Test func keyMapTypesCharactersWithShiftForUppercaseAndSymbols() {
        let a = MacVMKeyMap.stroke(forCharacter: "a")
        #expect(a?.keyCode == 0x00)
        #expect(a?.shift == false)
        #expect(MacVMKeyMap.stroke(forCharacter: "A")?.shift == true)
        #expect(MacVMKeyMap.stroke(forCharacter: "A")?.keyCode == 0x00)
        // Shifted symbol: '!' is shift+'1'.
        #expect(MacVMKeyMap.stroke(forCharacter: "!")?.shift == true)
        #expect(MacVMKeyMap.stroke(forCharacter: "!")?.keyCode == 0x12)
    }

    @Test func typeChunksAreBoundedAndLossless() {
        // Long literal text is synthesized in bounded main-actor slices (plan §5); the split must
        // reassemble to the exact payload with every chunk within the bound.
        let text = String(repeating: "let x = 42; // chunk\n", count: 40)  // 840 chars
        let chunks = MacVMEngine.typeChunks(text, size: MacVMEngine.typeChunkCharacters)
        #expect(chunks.allSatisfy { $0.count <= MacVMEngine.typeChunkCharacters })
        #expect(chunks.joined() == text)
        // Short text and edge cases: one chunk, or none for an empty payload.
        #expect(MacVMEngine.typeChunks("short", size: 32) == ["short"])
        #expect(MacVMEngine.typeChunks("", size: 32).isEmpty)
        // Character (grapheme) boundaries: a multi-scalar emoji never splits mid-sequence.
        let flags = String(repeating: "🇺🇸", count: 5)
        #expect(MacVMEngine.typeChunks(flags, size: 2).joined() == flags)
    }

    @Test func directTypeThresholdKeepsShortTextOnTheDirectPath() {
        // A chord-sized string stays below the chunking threshold (the low-latency path); the
        // constants must keep the direct bound at least one full chunk wide.
        #expect(MacVMEngine.directTypeMaxCharacters >= MacVMEngine.typeChunkCharacters)
        #expect("cmd+shift+s".count <= MacVMEngine.directTypeMaxCharacters)
    }

    @Test func scrollDeltasMapDirectionToSignedLines() {
        #expect(MacVMEngine.scrollDeltas(direction: "down", amount: 3) == (0, -3))
        #expect(MacVMEngine.scrollDeltas(direction: "up", amount: 5) == (0, 5))
        #expect(MacVMEngine.scrollDeltas(direction: "left", amount: 2) == (2, 0))
        #expect(MacVMEngine.scrollDeltas(direction: "right", amount: 2) == (-2, 0))
    }

    @Test func scrollTicksSplitTheGestureIntoSmallNotches() {
        // A gesture is delivered as a STREAM of small notches: apps with smooth scrolling animate per
        // event and coalesce anything arriving mid-animation, so one outsized event scrolls ~one notch.
        let down = MacVMEngine.scrollTicks(dx: 0, dy: -10)
        #expect(down.count == 5)
        #expect(down.allSatisfy { abs($0.dy) <= MacVMEngine.scrollLinesPerTick })
        #expect(down.allSatisfy { $0.dy < 0 })  // sign preserved: still scrolling down

        // Pacing must never change the requested distance — the notches sum back to the total.
        for (dx, dy) in [(0, -30), (0, 30), (7, 0), (-7, 0), (0, -1), (3, -3)] {
            let ticks = MacVMEngine.scrollTicks(dx: dx, dy: dy)
            #expect(ticks.reduce(0) { $0 + $1.dx } == dx, "dx \(dx) must be preserved")
            #expect(ticks.reduce(0) { $0 + $1.dy } == dy, "dy \(dy) must be preserved")
            #expect(ticks.allSatisfy {
                abs($0.dx) <= MacVMEngine.scrollLinesPerTick
                    && abs($0.dy) <= MacVMEngine.scrollLinesPerTick
            })
        }

        // An odd amount keeps a short final notch rather than rounding the distance away.
        #expect(MacVMEngine.scrollTicks(dx: 0, dy: -3).map(\.dy) == [-2, -1])
        // A single line is one notch, and nothing to scroll is no events at all.
        #expect(MacVMEngine.scrollTicks(dx: 0, dy: 1).count == 1)
        #expect(MacVMEngine.scrollTicks(dx: 0, dy: 0).isEmpty)
    }

    @Test func scrollPacingStaysInsideTheActionTimeout() {
        // The paced stream plus the pointer settle and the post-scroll animation waits must fit the
        // per-action deadline, or the biggest allowed scroll reports a spurious timeout. Worst case is
        // the maximum amount, and the verify path can send the gesture TWICE.
        let notches = MacVMEngine.scrollTicks(dx: 0, dy: -30).count
        let gestureSeconds = Double(notches * MacVMEngine.scrollTickIntervalMillis) / 1000
        let settleSeconds = Double(MacVMEngine.scrollAnimationSettleNanos) / 1_000_000_000
        #expect(gestureSeconds * 2 + settleSeconds * 2
            < MacVMEngine.surfaceComputerActionTimeoutSeconds)
        // Below ~30 ms notches coalesce again in an animating app, which is the bug being fixed.
        #expect(MacVMEngine.scrollTickIntervalMillis >= 30)
    }

    @Test func actionNeedsSettleGatesOnlyInputActions() {
        // Input actions repaint asynchronously, so they wait for the guest to settle before capture.
        for action in ["left_click", "right_click", "double_click", "mouse_move", "left_click_drag",
            "type", "key", "scroll", "launch_app"] {
            #expect(MacVMEngine.actionNeedsSettle(action), "\(action) should settle before capture")
        }
        // These don't inject input (or manage their own timing), so they capture without a settle.
        for action in ["screenshot", "cursor_position", "wait"] {
            #expect(!MacVMEngine.actionNeedsSettle(action), "\(action) should not settle")
        }
    }

    // MARK: - Resource probe parsing (Control panel VM meters)

    @Test func parseResourceProbeComputesUsedMemoryAndCPUFromIdle() {
        // vm_stat (16 KiB pages) + a `top` "CPU usage" line, as the guest emits them.
        let probe = """
        Mach Virtual Memory Statistics: (page size of 16384 bytes)
        Pages free:                                1000.
        Pages active:                              2000.
        Pages inactive:                             500.
        Pages wired down:                          1000.
        Pages occupied by compressor:               500.
        __CPU__
        CPU usage: 4.76% user, 9.52% sys, 85.71% idle
        """
        let total: UInt64 = 8 * 1_073_741_824  // 8 GiB ceiling
        let sample = MacVMEngine.parseResourceProbe(probe, memoryTotal: total)
        // used = (active + wired + compressed) × page size = 3500 × 16384.
        #expect(sample.memoryUsedBytes == 3500 * 16384)
        #expect(sample.memoryTotalBytes == total)
        // CPU = 100 − idle, within float tolerance.
        #expect(abs(sample.cpuPercent - (100 - 85.71)) < 0.01)
    }

    @Test func parseResourceProbeDegradesToCeilingOnBlankOutput() {
        // A missing/garbled probe must not throw — it yields a ceiling-only sample (zeros).
        let total: UInt64 = 4 * 1_073_741_824
        let sample = MacVMEngine.parseResourceProbe("", memoryTotal: total)
        #expect(sample.memoryUsedBytes == 0)
        #expect(sample.cpuPercent == 0)
        #expect(sample.memoryTotalBytes == total)
        #expect(sample.memoryPercent == 0)
    }

    @Test func parseProvisionStatusReadsGuestReadbackLine() {
        // The guest bootstrap writes `CODE=… SIP=… APP=… LA=… TCC=…` to STATUS on the share.
        let flags = MacVMEngine.parseProvisionStatus("CODE=0 SIP=1 APP=1 LA=1 TCC=3")
        #expect(flags.exitCode == 0)
        #expect(flags.sipDisabled)
        #expect(flags.agentApp)
        #expect(flags.launchAgent)
        #expect(flags.tccCount == 3)
        // Order-independent and tolerant of surrounding noise / SIP-on / partial grants / bad code.
        let partial = MacVMEngine.parseProvisionStatus("noise\nCODE=1 TCC=0 APP=1 SIP=0 LA=0\nmore")
        #expect(partial.exitCode == 1)
        #expect(!partial.sipDisabled)
        #expect(partial.agentApp)
        #expect(!partial.launchAgent)
        #expect(partial.tccCount == 0)
        // A missing CODE defaults to -1 (never mistaken for success).
        #expect(MacVMEngine.parseProvisionStatus("SIP=0").exitCode == -1)
    }

    @Test func provisioningFailureLogTailIsBoundedAndKeepsTheNewestLines() throws {
        let url = FileManager.default.temporaryDirectory
            .appendingPathComponent("provision-tail-\(UUID().uuidString).log")
        defer { try? FileManager.default.removeItem(at: url) }
        try (1...30).map { "line-\($0)" }.joined(separator: "\n")
            .write(to: url, atomically: true, encoding: .utf8)

        let tail = try #require(MacVMEngine.provisionLogTail(
            at: url, maxLines: 3, maxCharacters: 100))
        #expect(tail == "line-28\nline-29\nline-30")
        let characterBound = try #require(MacVMEngine.provisionLogTail(
            at: url, maxLines: 30, maxCharacters: 10))
        #expect(characterBound == "29\nline-30")
    }

    // MARK: - Settings (isolated task-local defaults suite)

    @Test func settingsDefaultsAndOverrides() async throws {
        let suite = UserDefaults(suiteName: "macvm-test-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            // Defaults with an empty suite.
            #expect(MacVMSettings.serviceEnabled == false)
            #expect(MacVMSettings.exposeByDefault == false)  // false while service is off
            #expect(MacVMSettings.vmCPUs == MacVMSettings.defaultVMCPUs)
            #expect(MacVMSettings.vmMemoryGiB == MacVMSettings.defaultVMMemoryGiB)
            #expect(MacVMSettings.maxConcurrentVMs == MacVMSettings.defaultMaxConcurrentVMs)
            #expect(MacVMSettings.vmQueueTimeoutSeconds == MacVMSettings.defaultVMQueueTimeoutSeconds)
            #expect(MacVMSettings.sshUser == MacVMSettings.defaultSSHUser)
            #expect(MacVMSettings.basePrebuiltPath == nil)
            #expect(MacVMSettings.restoreImagePath == nil)

            // Overrides take effect.
            suite.set(true, forKey: MacVMSettings.serviceEnabledKey)
            suite.set(true, forKey: MacVMSettings.exposeByDefaultKey)
            suite.set(16, forKey: MacVMSettings.vmCPUsKey)
            suite.set(45, forKey: MacVMSettings.vmQueueTimeoutSecondsKey)
            suite.set("   ", forKey: MacVMSettings.sshUserKey)  // blank falls back to default
            suite.set("/base/bundle", forKey: MacVMSettings.basePrebuiltPathKey)
            #expect(MacVMSettings.serviceEnabled == true)
            #expect(MacVMSettings.exposeByDefault == true)  // now that the service is on
            #expect(MacVMSettings.vmCPUs == 16)
            #expect(MacVMSettings.vmQueueTimeoutSeconds == 45)
            #expect(MacVMSettings.sshUser == MacVMSettings.defaultSSHUser)
            #expect(MacVMSettings.basePrebuiltPath == "/base/bundle")
        }
    }

    // MARK: - Admission / eviction ranking

    /// Build a local `SessionSummary` with just the fields the admission policy reads. Fully qualified
    /// because `NucleicProtocol` also exports a `SessionSummary` (the wire type).
    private func summary(
        id: String, status: SessionStatus, lastUser: Date?, updated: Date,
        archived: Bool = false, hostID: String? = nil, disposition: TurnDisposition? = nil
    ) -> NucleicCore.SessionSummary {
        let session = Session(
            id: SessionID(rawValue: id), projectID: ProjectID(rawValue: "p"), backend: .claudeCode,
            title: "t", status: status, transcriptPath: "/tmp/t", archived: archived,
            lastTurnDisposition: disposition,
            lastUserMessageAt: lastUser, createdAt: updated, updatedAt: updated)
        var s = NucleicCore.SessionSummary(session, pendingApprovalCount: 0)
        s.hostID = hostID
        return s
    }

    @Test func evictionRankingKeepsDoneChatsStalestFirstAndExcludesBusy() {
        let old = Date(timeIntervalSince1970: 1_000)
        let mid = Date(timeIntervalSince1970: 2_000)
        let new = Date(timeIntervalSince1970: 3_000)
        let doneOld = summary(id: "AAAAAAAA", status: .awaitingInput, lastUser: old, updated: old)
        let doneNew = summary(id: "BBBBBBBB", status: .finished, lastUser: new, updated: new)
        let busy = summary(id: "CCCCCCCC", status: .running, lastUser: mid, updated: mid)
        let names = [doneNew, busy, doneOld].map { MacVMManager.vmName(for: $0.id) }

        let ranked = AppStore.rankEvictableVMs(among: names, summaries: [doneNew, busy, doneOld])

        // The actively-working chat's VM is never offered; done chats come back stalest-first, so the
        // engine reclaims the least-recently-used one and keeps the more recent.
        #expect(ranked == [MacVMManager.vmName(for: doneOld.id), MacVMManager.vmName(for: doneNew.id)])
    }

    @Test func evictionRankingMapsLinuxNamesAndFallsBackToUpdatedAt() {
        let old = Date(timeIntervalSince1970: 1_000)
        let new = Date(timeIntervalSince1970: 3_000)
        // No user message ever — ranks on `updatedAt`. Owns a Linux VM (distinct name prefix).
        let doneOld = summary(id: "AAAAAAAA", status: .idle, lastUser: nil, updated: old)
        let doneNew = summary(id: "BBBBBBBB", status: .finished, lastUser: nil, updated: new)
        let names = [MacVMManager.linuxVMName(for: doneOld.id), MacVMManager.vmName(for: doneNew.id)]

        let ranked = AppStore.rankEvictableVMs(among: names, summaries: [doneNew, doneOld])

        #expect(ranked == [MacVMManager.linuxVMName(for: doneOld.id), MacVMManager.vmName(for: doneNew.id)])
    }

    @Test func evictionRankingIgnoresArchivedRemoteAndUnownedVMs() {
        let at = Date(timeIntervalSince1970: 5_000)
        let done = summary(id: "AAAAAAAA", status: .finished, lastUser: at, updated: at)
        let archived = summary(id: "BBBBBBBB", status: .finished, lastUser: at, updated: at, archived: true)
        let remote = summary(id: "CCCCCCCC", status: .finished, lastUser: at, updated: at, hostID: "peer")
        let names = [
            MacVMManager.vmName(for: done.id),
            MacVMManager.vmName(for: archived.id),
            MacVMManager.vmName(for: remote.id),
            "nucleic-mac-orphan",  // a running VM with no live chat (e.g. base maintenance)
        ]

        let ranked = AppStore.rankEvictableVMs(among: names, summaries: [done, archived, remote])

        // Only the live, local, non-archived done chat's VM is reclaimable.
        #expect(ranked == [MacVMManager.vmName(for: done.id)])
    }
    @Test func pictureInPictureSelectsBackgroundVMOwner() {
        let old = Date(timeIntervalSince1970: 1_000)
        let new = Date(timeIntervalSince1970: 2_000)
        let foreground = summary(id: "AAAAAAAA", status: .running, lastUser: new, updated: new)
        let background = summary(id: "BBBBBBBB", status: .awaitingInput, lastUser: old, updated: old)
        let running = [foreground, background].map { MacVMManager.vmName(for: $0.id) }

        let selected = AppStore.pictureInPictureVMSessionID(
            runningVMNames: running, openSessionID: foreground.id,
            currentSessionID: nil, summaries: [foreground, background])

        #expect(selected == background.id)
    }

    @Test func pictureInPictureKeepsOnlyOpenOwnerDormantUntilSessionSwitch() {
        let at = Date(timeIntervalSince1970: 1_000)
        let owner = summary(id: "AAAAAAAA", status: .running, lastUser: at, updated: at)
        let running = [MacVMManager.linuxVMName(for: owner.id)]

        let whileOpen = AppStore.pictureInPictureVMSessionID(
            runningVMNames: running, openSessionID: owner.id,
            currentSessionID: nil, summaries: [owner])
        let afterSwitch = AppStore.pictureInPictureVMSessionID(
            runningVMNames: running, openSessionID: SessionID(rawValue: "BBBBBBBB"),
            currentSessionID: whileOpen, summaries: [owner])

        #expect(whileOpen == owner.id)
        #expect(afterSwitch == owner.id)
    }

    @Test func pictureInPictureKeepsCurrentBackgroundOwnerStable() {
        let old = Date(timeIntervalSince1970: 1_000)
        let new = Date(timeIntervalSince1970: 2_000)
        let current = summary(id: "AAAAAAAA", status: .awaitingInput, lastUser: old, updated: old)
        let newer = summary(id: "BBBBBBBB", status: .running, lastUser: new, updated: new)
        let running = [
            MacVMManager.vmName(for: current.id),
            MacVMManager.linuxVMName(for: newer.id),
        ]

        let selected = AppStore.pictureInPictureVMSessionID(
            runningVMNames: running, openSessionID: SessionID(rawValue: "CCCCCCCC"),
            currentSessionID: current.id, summaries: [current, newer])

        #expect(selected == current.id)
    }

    @Test func pictureInPictureListOrdersBackgroundVMsExcludingOpen() {
        let old = Date(timeIntervalSince1970: 1_000)
        let new = Date(timeIntervalSince1970: 2_000)
        let open = summary(id: "AAAAAAAA", status: .running, lastUser: new, updated: new)
        let working = summary(id: "BBBBBBBB", status: .running, lastUser: old, updated: old)
        let idleNewer = summary(id: "CCCCCCCC", status: .awaitingInput, lastUser: new, updated: new)
        let idleOlder = summary(id: "DDDDDDDD", status: .awaitingInput, lastUser: old, updated: old)
        let running = [open, working, idleNewer, idleOlder].map { MacVMManager.vmName(for: $0.id) }

        let ids = AppStore.pictureInPictureVMSessionIDs(
            runningVMNames: running, openSessionID: open.id,
            preferredSessionID: nil, summaries: [open, working, idleNewer, idleOlder])

        // Open session excluded; a turn in flight leads, then most-recently-updated among the idle.
        #expect(ids == [working.id, idleNewer.id, idleOlder.id])
    }

    @Test func pictureInPictureListFloatsPreferredCardFirst() {
        let old = Date(timeIntervalSince1970: 1_000)
        let new = Date(timeIntervalSince1970: 2_000)
        let working = summary(id: "BBBBBBBB", status: .running, lastUser: new, updated: new)
        let picked = summary(id: "CCCCCCCC", status: .awaitingInput, lastUser: old, updated: old)
        let running = [working, picked].map { MacVMManager.vmName(for: $0.id) }

        let ids = AppStore.pictureInPictureVMSessionIDs(
            runningVMNames: running, openSessionID: SessionID(rawValue: "AAAAAAAA"),
            preferredSessionID: picked.id, summaries: [working, picked])

        // The user's hand-picked card leads even over a working session; it's a bias, not a filter.
        #expect(ids == [picked.id, working.id])
    }

    @Test func pictureInPictureListEmptyWhenOnlyOpenOwnsVM() {
        let at = Date(timeIntervalSince1970: 1_000)
        let owner = summary(id: "AAAAAAAA", status: .running, lastUser: at, updated: at)
        let running = [MacVMManager.linuxVMName(for: owner.id)]

        let ids = AppStore.pictureInPictureVMSessionIDs(
            runningVMNames: running, openSessionID: owner.id,
            preferredSessionID: nil, summaries: [owner])

        #expect(ids.isEmpty)
    }

    // MARK: - Done reap (launch-time half: a chat that was Done when the app quit)

    @Test func longDoneRequiresBothTheDoneStateAndTheFullGrace() {
        let doneAt = Date(timeIntervalSince1970: 10_000)
        let grace = TimeInterval(MacVMSettings.defaultDoneReapGraceSeconds)
        let done = summary(
            id: "AAAAAAAA", status: .awaitingInput, lastUser: doneAt, updated: doneAt,
            disposition: .completed)

        // Inside the grace window the clone is kept — this is the follow-up the grace exists for.
        #expect(!AppStore.isLongDone(done.id, summaries: [done], now: doneAt + grace - 1))
        // At the boundary and past it, it's reapable. (`>=`, so an exact-grace age counts.)
        #expect(AppStore.isLongDone(done.id, summaries: [done], now: doneAt + grace))
        #expect(AppStore.isLongDone(done.id, summaries: [done], now: doneAt + grace * 10))
    }

    @Test func longDoneSparesEveryChatThatIsNotActuallyDone() {
        let at = Date(timeIntervalSince1970: 10_000)
        let later = at + TimeInterval(MacVMSettings.defaultDoneReapGraceSeconds) * 10
        // Long-idle but NOT done: awaiting input because the agent asked a question, mid-turn, or
        // never classified. Age alone must never reap a guest — only age *in Done*.
        let asked = summary(
            id: "AAAAAAAA", status: .awaitingInput, lastUser: at, updated: at,
            disposition: .awaitingInput)
        let running = summary(id: "BBBBBBBB", status: .running, lastUser: at, updated: at)
        let unclassified = summary(id: "CCCCCCCC", status: .awaitingInput, lastUser: at, updated: at)
        let waiting = summary(
            id: "DDDDDDDD", status: .awaitingInput, lastUser: at, updated: at,
            disposition: .waitingBackground)  // armed a monitor — waiting, not done
        let all = [asked, running, unclassified, waiting]
        for s in all {
            #expect(!AppStore.isLongDone(s.id, summaries: all, now: later))
        }
        // A chat with no summary at all (not yet hydrated) is never reaped on a guess.
        #expect(!AppStore.isLongDone(SessionID(rawValue: "EEEEEEEE"), summaries: all, now: later))
    }

    @Test func longDoneCountsAFinishedRunAsDone() {
        // `.finished` is Done without any disposition — a non-interactive run that simply ended. It
        // holds a clone exactly like a classified interactive chat, so it must reap on the same clock.
        let at = Date(timeIntervalSince1970: 10_000)
        let grace = TimeInterval(MacVMSettings.defaultDoneReapGraceSeconds)
        let finished = summary(id: "AAAAAAAA", status: .finished, lastUser: at, updated: at)
        #expect(!AppStore.isLongDone(finished.id, summaries: [finished], now: at + grace - 1))
        #expect(AppStore.isLongDone(finished.id, summaries: [finished], now: at + grace))
    }

    @Test func doneReapGraceIsFiveMinutesAndOverridable() async throws {
        #expect(MacVMSettings.defaultDoneReapGraceSeconds == 300)  // the 5 minutes the policy promises
        let suite = UserDefaults(suiteName: "macvm-test-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            #expect(MacVMSettings.doneReapGraceSeconds == 300)
            suite.set(30, forKey: MacVMSettings.doneReapGraceSecondsKey)
            #expect(MacVMSettings.doneReapGraceSeconds == 30)
        }
    }

    // MARK: - Guidance

    @Test func macVMGuidanceOnlyWhenEnabled() {
        let off = SessionController.sandboxBuildGuidance(allowHostExec: true, allowMacVMExec: false)
        let on = SessionController.sandboxBuildGuidance(allowHostExec: true, allowMacVMExec: true)
        #expect(!off.contains("mac_vm_exec"))
        #expect(on.contains("mac_vm_exec"))
        #expect(on.contains("virtiofs is mounted directly there"))
    }

    @Test func computerUseGuidanceOnlyWhenEnabled() {
        let off = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, allowMacVMComputer: false)
        let on = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, allowMacVMComputer: true)
        #expect(!off.contains("mac_vm_computer"))
        #expect(on.contains("mac_vm_computer"))
    }

    @Test func clearNotificationsGuidanceRidesOnComputerUse() {
        // The clear-notifications tool only matters while looking at the VM's screen, so its guidance
        // is scoped to computer-use — absent for exec-only exposure, present once computer-use is on.
        let execOnly = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, allowMacVMComputer: false)
        let computer = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, allowMacVMComputer: true)
        #expect(!execOnly.contains("mac_vm_clear_notifications"))
        #expect(computer.contains("mac_vm_clear_notifications"))
    }

    @Test func vmLifecycleGuidanceTracksVMExposure() {
        // Distinctive per-block phrases — the Linux block name-drops `mac_vm_control` as "the
        // sibling of…", so a bare `contains("mac_vm_control")` would cross-match.
        let macBlock = "manage that macOS VM's lifecycle"
        let linuxBlock = "manage that Linux VM's lifecycle"
        // No VM exposed → neither control block appears.
        let none = SessionController.sandboxBuildGuidance(allowHostExec: true)
        #expect(!none.contains(macBlock))
        #expect(!none.contains(linuxBlock))
        // The control block rides on the VM being usable at all — even computer-use-only exposure.
        let macExec = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true)
        #expect(macExec.contains(macBlock))
        #expect(!macExec.contains(linuxBlock))
        let macComputerOnly = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: false, allowMacVMComputer: true)
        #expect(macComputerOnly.contains(macBlock))
        // Linux control is gated on the Linux VM independently.
        let linux = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowLinuxVMExec: true)
        #expect(linux.contains(linuxBlock))
        #expect(!linux.contains(macBlock))
    }

    @Test func vmLifecycleGuidanceInstructsProactiveFreeingUnderTheCap() {
        // The macOS control block must push the agent to free its own VM the moment it stops using
        // it — macOS guests are hard-capped across agents, so an idle one starves the pool. "Idle"
        // includes mid-turn gaps (reading files, container work), not just the end of a stretch of
        // VM work, so the block says so explicitly. The cap number is threaded in, not hardcoded, so
        // the prose stays truthful when the user overrides `maxConcurrentVMs`.
        let mac = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, maxConcurrentVMs: 2)
        #expect(mac.contains("at most 2 can run concurrently"))
        #expect(mac.contains("You MUST free your VM the moment you are no longer ACTIVELY using it"))
        #expect(mac.contains("even if that is in the middle of the very turn you booted it in"))
        #expect(mac.contains("free the slot before them and resume after"))
        // A non-default cap flows through verbatim.
        let macFour = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, maxConcurrentVMs: 4)
        #expect(macFour.contains("at most 4 can run concurrently"))
    }

    @Test func macVMUseGuidanceCarriesTheFreeWhenIdleDuty() {
        // The duty rides on the exec and computer-use blocks too, not just the lifecycle block — the
        // agent decides to *use* the VM there, and that's where it needs to know it owns freeing it.
        let exec = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, allowMacVMComputer: false)
        #expect(exec.contains(
            "the moment you are no longer ACTIVELY using the VM you MUST free it with "
                + "`mac_vm_control`"))
        let computer = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: false, allowMacVMComputer: true)
        #expect(computer.contains("the moment you stop ACTIVELY driving the screen, free the VM"))
    }

    @Test func linuxVMLifecycleGuidanceClaimsNoConcurrencyCap() {
        // `maxConcurrentVMs` is a macOS-guest ceiling; Linux guests don't share it. The Linux block
        // must not borrow the macOS scarcity prose — that would be false and would buy nothing but
        // suspend/resume churn — while still asking for ordinary RAM courtesy.
        let linux = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowLinuxVMExec: true, maxConcurrentVMs: 2)
        #expect(linux.contains("Unlike macOS VMs, Linux VMs are NOT capped across agents"))
        #expect(!linux.contains("at most 2 VMs run concurrently"))
        #expect(!linux.contains("NEVER leave one running"))
        #expect(linux.contains("give the host its RAM back"))
    }

    // MARK: - Computer-use command builders

    @Test func hostSurfaceComputerActionsHaveAFiniteTimeout() {
        #expect(MacVMEngine.surfaceComputerActionTimeoutSeconds > 0)
        #expect(MacVMEngine.surfaceComputerActionTimeoutSeconds <= 30)
    }

    @Test func asuserWrapsForAquaSession() {
        #expect(MacVMEngine.asuser("/usr/sbin/screencapture -x")
            == "launchctl asuser $(id -u) /usr/sbin/screencapture -x")
    }

    @Test func screenshotCommandCapturesAndBase64s() {
        let cmd = MacVMEngine.screenshotCommand()
        #expect(cmd.contains("launchctl asuser $(id -u) /usr/sbin/screencapture -x -t jpg"))
        #expect(cmd.contains("base64 -i"))
        #expect(cmd.contains("rm -f"))
    }

    @Test func pointerCommandsMapToCliclickVerbs() {
        #expect(MacVMEngine.pointerCommand(action: "left_click", x: 10, y: 20)
            == "launchctl asuser $(id -u) /usr/local/bin/cliclick c:10,20")
        #expect(MacVMEngine.pointerCommand(action: "right_click", x: 1, y: 2).hasSuffix("rc:1,2"))
        #expect(MacVMEngine.pointerCommand(action: "double_click", x: 1, y: 2).hasSuffix("dc:1,2"))
        #expect(MacVMEngine.pointerCommand(action: "mouse_move", x: 1, y: 2).hasSuffix("m:1,2"))
    }

    @Test func dragCommandUsesExplicitStartAndTarget() {
        // dd:/du: need real coordinates — no `.` placeholder.
        #expect(MacVMEngine.dragCommand(fromX: 3, fromY: 4, toX: 5, toY: 6).hasSuffix("dd:3,4 du:5,6"))
    }

    @Test func parseCursorReadsCliclickPointOutput() {
        #expect(MacVMEngine.parseCursor("640,400\n").map { "\($0.0),\($0.1)" } == "640,400")
        #expect(MacVMEngine.parseCursor("garbage") == nil)
    }

    @Test func typeCommandShellQuotesText() {
        let cmd = MacVMEngine.typeCommand("hello 'world'")
        #expect(cmd.contains("/usr/local/bin/cliclick -w 20 t:'hello '\\''world'\\'''"))
    }

    @Test func keyCommandBuildsChordsAndSpecials() {
        // Letter with a modifier → hold cmd, type the letter.
        #expect(MacVMEngine.keyCommand(chord: "cmd+s").hasSuffix("kd:cmd t:'s' ku:cmd"))
        // Multiple modifiers + digit (screenshot shortcut).
        #expect(MacVMEngine.keyCommand(chord: "cmd+shift+4").hasSuffix("kd:cmd,shift t:'4' ku:cmd,shift"))
        // A special key with a modifier.
        #expect(MacVMEngine.keyCommand(chord: "cmd+tab").hasSuffix("kd:cmd kp:tab ku:cmd"))
        // Bare special key, no modifiers.
        #expect(MacVMEngine.keyCommand(chord: "return").hasSuffix("cliclick kp:return"))
        #expect(MacVMEngine.keyCommand(chord: "escape").hasSuffix("cliclick kp:esc"))
    }

    @Test func scrollCommandApproximatesWithArrowKeys() {
        let cmd = MacVMEngine.scrollCommand(direction: "down", amount: 3)
        #expect(cmd.hasSuffix("kp:arrow-down kp:arrow-down kp:arrow-down"))
        #expect(MacVMEngine.scrollCommand(direction: "up", amount: 1).hasSuffix("kp:arrow-up"))
    }

    @Test func launchAppCommandQuotesName() {
        #expect(MacVMEngine.launchAppCommand("Xcode").hasSuffix("/usr/bin/open -a 'Xcode'"))
    }

    @Test func launchAppCommandAppendsQuotedURL() {
        // The URL rides along as the document to open — quoted, so a query string can't split the
        // command or inject one.
        #expect(
            MacVMEngine.launchAppCommand("Safari", url: "https://example.com/a?b=1&c=2")
                .hasSuffix("/usr/bin/open -a 'Safari' 'https://example.com/a?b=1&c=2'"))
        #expect(
            MacVMEngine.launchAppCommand("Safari", url: "https://x/'; rm -rf /; echo '")
                .contains(#"'https://x/'\''; rm -rf /; echo '\'''"#))
        // No URL (or an empty one) leaves the plain launch untouched.
        #expect(MacVMEngine.launchAppCommand("Safari", url: nil).hasSuffix("-a 'Safari'"))
        #expect(MacVMEngine.launchAppCommand("Safari", url: "").hasSuffix("-a 'Safari'"))
    }

    // MARK: - `open_browser` shortcut

    @Test func knownBrowsersCoverChromeAndFirefox() {
        let keys = Set(MacVMEngine.knownBrowsers.map(\.key))
        #expect(keys.isSuperset(of: ["chrome", "firefox", "safari", "edge"]))
        let chrome = MacVMEngine.knownBrowsers.first { $0.key == "chrome" }
        // "chrome" resolves to Chrome for Testing first on macOS (what the base installs), falling back
        // to a stock Chrome; on the arm64 Linux base it resolves to Debian's chromium, which needs
        // accessibility forced on for ax_* to see inside it.
        #expect(chrome?.macApps.first == "Google Chrome for Testing")
        #expect(chrome?.macApps.contains("Google Chrome") == true)
        #expect(chrome?.linuxBins.first == "chromium")
        #expect(chrome?.linuxBins.contains("google-chrome") == true)
        #expect(chrome?.linuxArgs.contains("--force-renderer-accessibility") == true)
        // Safari is macOS-only, so it isn't offered on Linux (empty binary list).
        #expect(MacVMEngine.knownBrowsers.first { $0.key == "safari" }?.linuxBins.isEmpty == true)
    }

    @Test func macBrowserFallbackChainKeepsEveryBranchInTheGUISession() {
        let cmd = MacVMEngine.launchAppCommand(
            ["Google Chrome for Testing", "Google Chrome"], url: "https://example.com")
        // Both branches must carry their OWN `launchctl asuser`: a `||` inside a single wrap would be
        // parsed by the outer shell, dropping the fallback into launchd's Background domain where a GUI
        // app can't open a window.
        let branches = cmd.components(separatedBy: " || ")
        #expect(branches.count == 2)
        #expect(branches.allSatisfy { $0.hasPrefix("launchctl asuser $(id -u) ") })
        #expect(branches[0].contains("'Google Chrome for Testing'"))
        #expect(branches[1].contains("'Google Chrome'"))
        #expect(branches.allSatisfy { $0.contains("'https://example.com'") })
        // A single-app list stays the plain one-shot form (no chain).
        #expect(!MacVMEngine.launchAppCommand(["Safari"]).contains("||"))
    }

    @Test func linuxBrowserLaunchPassesFlagsBeforeTheURL() throws {
        let cmd = MacVMEngine.linuxLaunchBinaryCommand(
            candidates: ["chromium"], url: "https://example.com",
            args: ["--force-renderer-accessibility"])
        // The URL is positional, so the flag has to precede it — otherwise Chromium takes the flag as a
        // second document to open.
        let flag = try #require(cmd.range(of: "--force-renderer-accessibility"))
        let page = try #require(cmd.range(of: "https://example.com"))
        #expect(flag.upperBound < page.lowerBound)
        // No args is unchanged from the old single-argument form.
        #expect(!MacVMEngine.linuxLaunchBinaryCommand(candidates: ["firefox"])
            .contains("--force-renderer-accessibility"))
    }

    @Test func normalizedBrowserURLFillsInTheScheme() {
        // Nothing to open: the browser lands on its own start page.
        #expect(MacVMEngine.normalizedBrowserURL(nil) == nil)
        #expect(MacVMEngine.normalizedBrowserURL("   ") == nil)
        // An explicit scheme is the agent's call, whatever it is.
        #expect(MacVMEngine.normalizedBrowserURL(" https://example.com ") == "https://example.com")
        #expect(MacVMEngine.normalizedBrowserURL("file:///tmp/a.html") == "file:///tmp/a.html")
        #expect(MacVMEngine.normalizedBrowserURL("about:blank") == "about:blank")
        // Scheme-less: loopback is a dev server (http), everything else gets https.
        #expect(MacVMEngine.normalizedBrowserURL("localhost:3000") == "http://localhost:3000")
        #expect(MacVMEngine.normalizedBrowserURL("127.0.0.1:8080/app") == "http://127.0.0.1:8080/app")
        #expect(MacVMEngine.normalizedBrowserURL("example.com/x") == "https://example.com/x")
        // A path on a non-loopback host doesn't get read as a port/host mix-up.
        #expect(MacVMEngine.normalizedBrowserURL("example.com/localhost") == "https://example.com/localhost")
    }

    @Test func linuxLaunchBinaryCommandAppendsQuotedURL() {
        let cmd = MacVMEngine.linuxLaunchBinaryCommand(
            candidates: ["firefox"], url: "http://localhost:3000")
        #expect(cmd.contains("\"$b\" 'http://localhost:3000' >/dev/null"))
        // No URL keeps the bare launch (no stray argument before the redirect).
        #expect(
            MacVMEngine.linuxLaunchBinaryCommand(candidates: ["firefox"])
                .contains("\"$b\" >/dev/null"))
    }

    @Test func linuxLaunchBinaryCommandDropsToDesktopUserAndDetaches() {
        let cmd = MacVMEngine.linuxLaunchBinaryCommand(candidates: ["firefox", "firefox-esr"])
        // Tries each candidate on PATH, in order.
        #expect(cmd.contains("for b in 'firefox' 'firefox-esr'; do"))
        #expect(cmd.contains("command -v \"$b\""))
        // Runs as the autologin desktop user (not the root the exec agent runs as), detached.
        #expect(cmd.contains("runuser -u 'nucleic'"))
        #expect(cmd.contains("setsid"))
        // Carries the desktop session's Wayland/X/D-Bus environment.
        #expect(cmd.contains("WAYLAND_DISPLAY=wayland-0"))
        #expect(cmd.contains("DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus"))
    }

    // MARK: - Native in-guest agent (docs/MACOS_VM_NATIVE_AGENT.md)

    @Test func agentRequestLineIsOneJSONObjectPerLine() throws {
        let line = MacVMAgentWire.requestLine(
            op: "click", fields: ["x": .number(10), "y": .number(20)])
        #expect(line.last == 0x0A)  // newline-terminated (NDJSON)
        #expect(!line.dropLast().contains(0x0A))  // and exactly ONE line
        let parsed = try JSONValue(parsing: line.dropLast())
        #expect(parsed["op"]?.stringValue == "click")
        #expect(parsed["x"]?.intValue == 10)
        #expect(parsed["y"]?.intValue == 20)
    }

    @Test func agentRequestLineOpWinsOverFieldCollision() throws {
        // `op` is the dispatcher's field; a caller-supplied collision must not hijack it.
        let line = MacVMAgentWire.requestLine(op: "ping", fields: ["op": .string("evil")])
        let parsed = try JSONValue(parsing: line.dropLast())
        #expect(parsed["op"]?.stringValue == "ping")
    }

    @Test func agentReplyParsingAcceptsObjectsRejectsGarbage() throws {
        let reply = try MacVMAgentWire.parseReply(Data(#"{"ok":true,"version":1}"#.utf8))
        #expect(reply["ok"]?.boolValue == true)
        #expect(reply["version"]?.intValue == 1)
        #expect(throws: (any Error).self) {
            try MacVMAgentWire.parseReply(Data("not json".utf8))
        }
        #expect(throws: (any Error).self) {
            try MacVMAgentWire.parseReply(Data(#"[1,2,3]"#.utf8))  // an array is not a reply
        }
    }

    @Test func agentErrorSeparatesTransportFromOpFailures() {
        // Op-level failures keep the channel; transport failures discard it (re-probe next action).
        #expect(!MacVMAgentError.agentError("no such ref").isTransportFailure)
        #expect(MacVMAgentError.ioFailed("EOF").isTransportFailure)
        #expect(MacVMAgentError.timeout.isTransportFailure)
        #expect(MacVMAgentError.protocolError("bad line").isTransportFailure)
        #expect(MacVMAgentError.noSocketDevice.isTransportFailure)
    }

    @Test func scrollDeltaMapsDirectionToWheelLines() {
        // CGEvent wheel conventions: wheel1 > 0 scrolls content up, wheel2 > 0 scrolls left.
        #expect(MacVMEngine.scrollDelta(direction: "up", amount: 3) == (0, 3))
        #expect(MacVMEngine.scrollDelta(direction: "down", amount: 3) == (0, -3))
        #expect(MacVMEngine.scrollDelta(direction: "left", amount: 2) == (2, 0))
        #expect(MacVMEngine.scrollDelta(direction: "right", amount: 2) == (-2, 0))
        #expect(MacVMEngine.scrollDelta(direction: "diagonal??", amount: 1) == (0, -1))  // → down
    }

    @Test func axActionsAreAgentOnlyVocabulary() {
        #expect(MacVMEngine.axActions == [
            "ax_dump", "ax_element_at", "ax_press", "ax_set_value", "ax_focus",
        ])
        // The pixel vocabulary must stay disjoint — routing switches on membership.
        for pixel in ["screenshot", "left_click", "type", "key", "scroll", "launch_app", "wait"] {
            #expect(!MacVMEngine.axActions.contains(pixel))
        }
    }

    @Test func computerUseGuidanceTeachesAXFirst() {
        let on = SessionController.sandboxBuildGuidance(
            allowHostExec: true, allowMacVMExec: true, allowMacVMComputer: true)
        #expect(on.contains("ax_dump"))
        #expect(on.contains("ax_press"))
    }

    // MARK: - macOS 27 declarative first-boot provisioning (docs/MACOS_VM.md §4.4)

    @Test func provisionBootstrapScriptIsNetworkFreeAndReportsStatus() {
        // The host-composed bootstrap the guest runs via HID: reads the password from the share,
        // runs the provisioner, and writes a CODE/SIP/APP/LA/TCC readback + powers off. No network.
        let script = MacVMEngine.provisionBootstrapScript(user: "agent", mountTag: nil)
        #expect(script.contains("touch \"$SHARE/STARTED\""))              // "running" sentinel
        #expect(script.contains("cat \"$SHARE/password\""))               // no typed password
        #expect(script.contains("provision-macos-guest.sh"))              // runs the provisioner
        #expect(script.contains("agent ALL=(ALL) NOPASSWD: ALL"))         // grants durable sudo
        #expect(script.contains("/etc/sudoers.d/nucleic-agent"))
        #expect(!script.contains("rm -f /etc/sudoers.d/nucleic-agent"))   // survives base sealing
        #expect(script.contains("> \"$SHARE/STATUS\""))                   // writes the readback
        #expect(script.contains("Full provisioning failed (exit $CODE)")) // labels failed shutdown
        #expect(script.contains("shutdown -h now"))                       // powers off when done
        #expect(!script.contains("ssh"))                                  // never touches SSH
        // With no custom-mountpoint device attached the whole run stays on Apple's automount.
        #expect(script.contains("SHARE=\"/Volumes/My Shared Files/nucleic-provision\""))
        #expect(!script.contains("mount_virtiofs"))
    }

    @Test func provisionBootstrapMovesOffTheAutomountToASpaceFreeMountpoint() {
        // The HID launch can only reach Apple's automount, so the bootstrap must still ENTER there…
        let script = MacVMEngine.provisionBootstrapScript(user: "agent", mountTag: "nucleic-mount-1")
        #expect(script.contains("SHARE=\"/Volumes/My Shared Files/nucleic-provision\""))
        // …and then re-mount the same share at a mountpoint with no spaces to quote, adopting it only
        // after the mount is proven to carry the staged provisioner.
        #expect(script.contains(
            "sudo /sbin/mount_virtiofs 'nucleic-mount-1' '/Volumes/nucleic-provision'"))
        #expect(script.contains("[ -f '/Volumes/nucleic-provision/provision-macos-guest.sh' ]"))
        #expect(script.contains("SHARE='/Volumes/nucleic-provision'"))
        #expect(!MacVMEngine.provisionMountPoint.contains(" "))
        // The provisioner runs FROM that path (so its own $0-derived lookups are space-free too) and
        // is told which share to signal the host through.
        #expect(script.contains("NUCLEIC_PROVISION_SHARE=\"$SHARE\""))
        #expect(script.contains("\"$SHARE/provision-macos-guest.sh\""))
        #expect(script.contains("> \"$SHARE/provision.log\""))
        // Ordering: passwordless sudo is primed BEFORE the mount (mount_virtiofs needs root), and the
        // readback is written and synced BEFORE the mount is torn down.
        let sudoAt = try! #require(script.range(of: "NOPASSWD: ALL")).lowerBound
        let mountAt = try! #require(script.range(of: "mount_virtiofs")).lowerBound
        let statusAt = try! #require(script.range(of: "$SHARE/STATUS")).lowerBound
        let umountAt = try! #require(script.range(of: "/sbin/umount")).lowerBound
        #expect(sudoAt < mountAt)
        #expect(statusAt < umountAt)
        // The ephemeral mountpoint doesn't survive into the sealed base.
        #expect(script.contains("sudo /bin/rmdir '/Volumes/nucleic-provision'"))
    }

    @Test func customGuestMountPointOverridesBothHostPathAndAutomount() {
        let mount = MacVMSpec.Mount(
            host: "/var/folders/tmp/nucleic-provision-abc", name: "nucleic-provision",
            readOnly: false, recreateHostPath: false, guestPath: "/Volumes/nucleic-provision")
        // An explicit mountpoint implies a direct (custom-tagged) device even though the share opted
        // out of host-path re-creation…
        #expect(MacVMEngine.directMacOSMount(mount))
        #expect(MacVMEngine.macOSMountPoint(mount) == "/Volumes/nucleic-provision")
        // …and the guest mounts it THERE, not at the host path and not under the automount root.
        let script = try! #require(MacVMEngine.hostPathRecreationScript(os: .macOS, mounts: [mount]))
        #expect(script.contains(
            "sudo /sbin/mount_virtiofs 'nucleic-mount-0' '/Volumes/nucleic-provision'"))
        #expect(!script.contains("/var/folders/tmp/nucleic-provision-abc"))
        // Without one, nothing changes: the host path stays the mountpoint.
        let plain = MacVMSpec.Mount(host: "/Users/me/proj", name: "workspace", readOnly: false)
        #expect(MacVMEngine.macOSMountPoint(plain) == "/Users/me/proj")
    }

    @Test func macOSGuestProvisionerKeepsPasswordlessSudo() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let provisioner = repoRoot.appendingPathComponent("scripts/provision-macos-guest.sh")
        let script = try String(contentsOf: provisioner, encoding: .utf8)
        #expect(script.contains("@includedir /private/etc/sudoers.d"))
        #expect(script.contains("ALL=(ALL) NOPASSWD: ALL"))
        #expect(script.contains("/private/etc/sudoers.d/nucleic-agent"))
        #expect(script.contains("chmod 0440 /private/etc/sudoers.d/nucleic-agent"))
    }

    @Test func macOSGuestProvisionerRequiresNashAndWritesNoTCC() throws {
        // NASH.md §7.5 (M5, locked): nash is the ONLY shell the in-guest exec surface runs, so the
        // provisioner must install the staged nash to /usr/local/bin and HARD-FAIL when none is
        // staged — a nash-less base has a dead exec surface (the agent refuses to run commands
        // under anything else). The staging side is MacVMEngine.resolveNashBinary() → the
        // provisioning share (which likewise throws when no binary is available).
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let provisioner = repoRoot.appendingPathComponent("scripts/provision-macos-guest.sh")
        let script = try String(contentsOf: provisioner, encoding: .utf8)
        #expect(script.contains(#"sudo cp "$NASH_SRC" /usr/local/bin/nash"#))
        #expect(script.contains("UserShell /usr/local/bin/nash"))  // agent account login shell
        #expect(script.contains("no nash binary staged — ABORTING"))  // required, not optional
        #expect(!script.contains("SKIPPING. The in-guest agent will run commands under /bin/zsh"))
        #expect(script.contains("/etc/profile.d/nucleic-nash-path.sh"))  // PATH for `nash -l`

        // This TOOLCHAIN provisioner writes NO TCC rows and touches SIP not at all. Under Lane B
        // (docs/MACOS_VM_POLICY_ALTERNATIVE.md) the datastore grants ARE written under transient
        // SIP-off — but by a SEPARATE, dedicated pass (scripts/macvm-policy-grants.sh, run over vsock
        // in its own Recovery-toggled boot), which finishes and re-enables SIP BEFORE this script
        // runs. Keeping the write out of this script keeps the two concerns cleanly split: this one is
        // the SIP-on toolchain pass, and it must never itself sqlite3-INSERT into TCC.db or run
        // `csrutil`. (The Lane B write lives in macvm-policy-grants.sh, tested separately below.)
        //
        // Checked against EXECUTABLE lines only — the script keeps a comment explaining where the
        // grants come from, and that record is worth more than a whole-file substring match.
        for line in script.split(separator: "\n") {
            let code = line.drop(while: { $0 == " " })
            guard !code.hasPrefix("#") else { continue }
            for banned in ["kTCCServiceSystemPolicy", "TCC.db", "csrutil", "SIP_OFF"] {
                #expect(!code.contains(banned), "the toolchain provisioner must stay TCC/SIP-free: \(code)")
            }
        }
    }

    // MARK: - Lane B — datastore policy grants (MacVMEngine+PolicyGrants)

    /// The Lane B guest script grants exactly the five services keyed to the agent bundle id, writes
    /// them into the SYSTEM TCC.db, disables the notification SOURCES (not the alerts), and reads
    /// everything back — docs/MACOS_VM_POLICY_ALTERNATIVE.md.
    @Test func policyGrantsScriptWritesTheFiveServicesKeyedByBundleID() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let script = try String(
            contentsOf: repoRoot.appendingPathComponent("scripts/macvm-policy-grants.sh"),
            encoding: .utf8)
        for service in MacVMEngine.policyGrantServices {
            #expect(script.contains(service), "policy-grants script must grant \(service)")
        }
        // Keyed by BUNDLE ID (client_type 0 = allowed by bundle id), ALLOWED (auth_value 2), into the
        // SYSTEM TCC.db, always with NAMED columns (the schema gains columns across OS releases).
        #expect(script.contains("xyz.blakeslee.nucleic.vmagent"))
        #expect(script.contains("/Library/Application Support/com.apple.TCC/TCC.db"))
        #expect(script.contains("INSERT OR REPLACE INTO access"))
        #expect(script.contains(",0,2,3,1,"))  // client_type,auth_value,auth_reason,auth_version
        // Read-back asserts auth_value AND csreq presence per service, then a single verdict marker.
        #expect(script.contains("SELECT auth_value FROM access"))
        #expect(script.contains("csreq IS NOT NULL"))
        #expect(script.contains("POLICY_GRANTS_OK"))
        // Notification SOURCES disabled surgically (docs' preferred path), never a blanket DND.
        #expect(script.contains("com.apple.tipsd"))
        #expect(script.contains("com.apple.BTMNotificationAgent"))
        #expect(script.contains("launchctl disable"))
        #expect(!script.lowercased().contains("do not disturb"))
    }

    /// The vsock invocation pipes the base64'd script over stdin into `sudo bash` and passes its
    /// parameters as sudo-set env — so the script body and nothing sensitive ride the command line.
    @Test func policyGrantsRemoteBodyPipesScriptViaStdinWithEnv() {
        let body = MacVMEngine.policyGrantsRemoteBody(
            scriptBase64: "QUJD", csreqHex: "deadbeef", requireCsreq: true, user: "agent",
            verifyOnly: false)
        #expect(body.contains("printf %s 'QUJD'"))
        #expect(body.contains("/usr/bin/base64 --decode"))
        #expect(body.contains("/usr/bin/sudo"))
        #expect(body.contains("/bin/bash"))
        #expect(body.contains("NUCLEIC_VMAGENT_CSREQ_HEX='deadbeef'"))
        #expect(body.contains("NUCLEIC_REQUIRE_CSREQ=1"))
        #expect(body.contains("NUCLEIC_POLICY_GRANTS_VERIFY_ONLY=0"))
        #expect(body.contains("NUCLEIC_AGENT_USER='agent'"))
        // The script body itself never appears on the argv the guest agent runs.
        #expect(!body.contains("INSERT OR REPLACE"))

        let verify = MacVMEngine.policyGrantsRemoteBody(
            scriptBase64: "QUJD", csreqHex: nil, requireCsreq: false, user: "agent", verifyOnly: true)
        #expect(verify.contains("NUCLEIC_VMAGENT_CSREQ_HEX=''"))   // no blob → NULL rows
        #expect(verify.contains("NUCLEIC_REQUIRE_CSREQ=0"))
        #expect(verify.contains("NUCLEIC_POLICY_GRANTS_VERIFY_ONLY=1"))
    }

    /// The marker parser reads the guest's SIP state, per-service grants, and verdict from stdout —
    /// never the exit code, so a partial failure names the row that broke.
    @Test func parsePolicyGrantsMarkersReadsGrantsAndVerdict() {
        let ok = """
        SIP=1
        GRANT kTCCServiceSystemPolicyAllFiles auth=2 csreq=1
        GRANT kTCCServiceSystemPolicyNetworkVolumes auth=2 csreq=1
        GRANT kTCCServiceScreenCapture auth=2 csreq=1
        GRANT kTCCServiceAccessibility auth=2 csreq=1
        GRANT kTCCServicePostEvent auth=2 csreq=0
        NOTIF com.apple.tipsd=disabled
        POLICY_GRANTS_OK
        """
        let readback = MacVMEngine.parsePolicyGrantsMarkers(ok)
        #expect(readback.sipDisabled == true)
        #expect(readback.ok)
        #expect(readback.grants.count == 5)
        #expect(readback.grants["kTCCServiceScreenCapture"]?.auth == "2")
        #expect(readback.grants["kTCCServiceScreenCapture"]?.hasCsreq == true)
        #expect(readback.grants["kTCCServicePostEvent"]?.hasCsreq == false)
        #expect(readback.notif["com.apple.tipsd"] == "disabled")

        let failed = """
        SIP=0
        GRANT kTCCServiceScreenCapture auth=none csreq=0
        POLICY_GRANTS_FAIL: kTCCServiceScreenCapture(auth=none)
        """
        let bad = MacVMEngine.parsePolicyGrantsMarkers(failed)
        #expect(bad.sipDisabled == false)
        #expect(!bad.ok)
        #expect(bad.failReason?.contains("kTCCServiceScreenCapture") == true)
    }

    @Test func policyLaneDefaultsToDatastore() async {
        let suite = UserDefaults(suiteName: "macvm-lane-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            #expect(MacVMSettings.policyLane == .datastore)          // Lane B is the default
            suite.set("mdm", forKey: MacVMSettings.policyLaneKey)
            #expect(MacVMSettings.policyLane == .mdm)
            suite.set("bogus", forKey: MacVMSettings.policyLaneKey)
            #expect(MacVMSettings.policyLane == .datastore)          // unknown → default, never wedges
        }
    }

    // MARK: - Network-volumes consent grant (MacVMEngine+ConsentGrant)

    /// Vision's normalized bottom-left-origin box maps to the surface's 1920×1200 top-left-origin
    /// click space (the same space `capture` screenshots and `.click` share).
    @Test func normalizedOCRBoxMapsToSurfaceClickSpace() {
        let box = CGRect(x: 0.45, y: 0.20, width: 0.10, height: 0.10)  // center (0.5, 0.25)
        let point = MacVMEngine.clickPoint(forNormalizedBox: box)
        #expect(point.x == 960)   // 0.5 × 1920
        #expect(point.y == 900)   // (1 − 0.25) × 1200
    }

    /// The readiness gate's probe must exercise the PRODUCTION path: the real host-path mount script
    /// (`mount_virtiofs` at the mount's own guest mountpoint) plus a read of it, the nash the exec
    /// surface requires, and an exec round-trip. Probing anything easier — an automount, a path the
    /// engine doesn't actually use — is what let a broken base be stamped as good.
    @Test func baseReadinessScriptExercisesTheProductionPath() throws {
        // The probe share is built by ONE helper, shared with the VM configuration, so the script and
        // the attached device can't drift (the virtiofs tag is the mount's index in that array).
        let mount = MacVMEngine.consentProbeMount(hostDirectory: "/var/folders/zz/T/nucleic-consent-1")
        let mountPoint = MacVMEngine.macOSMountPoint(mount)
        let mountScript = try #require(
            MacVMEngine.hostPathRecreationScript(os: .macOS, mounts: [mount]))
        let script = MacVMEngine.baseReadinessScript(
            mountPoint: mountPoint, mountScript: mountScript)

        // The production MECHANISM, verbatim: mount_virtiofs of the custom-tagged device…
        #expect(script.contains("sudo /sbin/mount_virtiofs 'nucleic-mount-0' '\(mountPoint)'"))
        // …at an explicit guest mountpoint, NOT the host's per-run temp path (which would mount a
        // device inside the guest's own /var/folders TMPDIR tree — the reason `guestPath` exists).
        #expect(mountPoint == MacVMEngine.consentProbeGuestPath)
        #expect(!script.contains("/var/folders"))
        // …and the readiness READ must target that same mountpoint. Reading the automount instead
        // (which doesn't trip the network-volume consent gate) is precisely the vacuous probe that
        // certified a base whose clones still hung. The mount script's own legacy-symlink migration
        // legitimately *mentions* the automount root, so assert on the read, not on absence.
        #expect(script.contains("/bin/ls '\(mountPoint)' >/dev/null 2>&1"))
        #expect(!script.contains("/bin/ls '\(MacVMEngine.macOSShareRoot)"))
        // Each leg reports its own marker, so a partial failure names what broke.
        #expect(script.contains(MacVMEngine.ReadinessMarker.mounted))
        #expect(script.contains(MacVMEngine.ReadinessMarker.nash))
        #expect(script.contains(MacVMEngine.ReadinessMarker.exec))
        #expect(script.contains(MacVMEngine.guestNashPath))
    }

    /// A report is ready only when every leg passed; failures carry actionable text.
    @Test func baseReadinessReportIsReadyOnlyWithNoFailures() {
        var report = MacVMEngine.BaseReadinessReport()
        report.workspaceMounted = true
        report.nashInstalled = true
        report.execWorks = true
        #expect(report.isReady)
        report.failures.append("nash is missing")
        #expect(!report.isReady)
        #expect(report.summary.contains("nash=true"))
    }

    @Test func macOSGuestProvisionerDownloadsMetalAfterImportedApplications() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let provisioner = repoRoot.appendingPathComponent("scripts/provision-macos-guest.sh")
        let script = try String(contentsOf: provisioner, encoding: .utf8)

        let includedAppsInstalled = try #require(
            script.range(of: "sudo /usr/bin/ditto \"$app\" \"$dest\""))
        let commonPackagesInstalled = try #require(
            script.range(of: "/bin/bash \"$PKG_INSTALLER\""))
        let metalDownloaded = try #require(
            script.range(of: "-downloadComponent MetalToolchain", options: .backwards))

        #expect(includedAppsInstalled.upperBound < metalDownloaded.lowerBound)
        #expect(commonPackagesInstalled.upperBound < metalDownloaded.lowerBound)
    }

    @Test func macOSGuestProvisionerVerifiesMetalByCompilingAProbe() throws {
        // "Downloaded" isn't "installed": `-downloadComponent` can exit 0 with an unusable toolchain,
        // so the provisioner must resolve `metal` through xcrun and actually compile something — after
        // the download, or it would be proving the wrong thing.
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let script = try String(
            contentsOf: repoRoot.appendingPathComponent("scripts/provision-macos-guest.sh"),
            encoding: .utf8)

        let metalDownloaded = try #require(
            script.range(of: "-downloadComponent MetalToolchain", options: .backwards))
        let probeCompiled = try #require(script.range(of: "probe.metal", options: .backwards))
        #expect(metalDownloaded.upperBound < probeCompiled.lowerBound)
        #expect(script.contains("--find metal"))
    }

    @Test func macOSGuestProvisionerRequiresAUsableXcodeAndSwiftUIFrontend() throws {
        // A base build must fail at provisioning time instead of publishing a clone source that
        // cannot compile Apple-platform code. The copy is bundle-aware, and both missing Xcode and
        // an SDK/SwiftUI failure are fatal.
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let script = try String(
            contentsOf: repoRoot.appendingPathComponent("scripts/provision-macos-guest.sh"),
            encoding: .utf8)

        #expect(script.contains(#"sudo /usr/bin/ditto "$app" "$dest""#))
        #expect(script.contains("no full Xcode in /Applications — refusing to publish"))
        #expect(script.contains("xcodebuild is missing"))
        #expect(script.contains("import SwiftUI"))
        #expect(script.contains("-typecheck \"$SWIFTUI_PROBE/Probe.swift\""))
        #expect(script.contains("could not typecheck a SwiftUI frontend probe"))
        // The promised non-Apple toolchains are also resolved before the base is sealed.
        #expect(script.contains("required development tools are missing"))
        for tool in ["node", "npm", "python3", "rustc", "cargo", "go", "git", "cmake"] {
            #expect(script.contains(" \(tool)"))
        }
    }

    /// A copied-in Xcode is unusable until its license is accepted by root, and an agent exec has no
    /// TTY to answer the prompt in — so the provisioner must accept it during the base build, verify
    /// the acceptance the way a build does, and fall back to driving the interactive prompt with its
    /// confirmations pre-fed rather than trusting `-license accept`'s exit code.
    @Test func macOSGuestProvisionerAcceptsTheXcodeLicenseBeforeBuildingAnything() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let script = try String(
            contentsOf: repoRoot.appendingPathComponent("scripts/provision-macos-guest.sh"),
            encoding: .utf8)

        // Non-interactive verb first, then the interactive `xcodebuild -license` with "agree" fed in.
        let accept = try #require(
            script.range(of: "\"$XCODE_DEVDIR/usr/bin/xcodebuild\" -license accept"))
        let interactive = try #require(
            script.range(of: "printf 'q\\nagree\\nagree\\ny\\n'", options: .backwards))
        #expect(accept.upperBound < interactive.lowerBound)
        #expect(script.contains("sudo \"$XCODE_DEVDIR/usr/bin/xcodebuild\" -license >/dev/null"))
        // Verified functionally (what a build hits), not by exit code…
        #expect(script.contains("xcode_license_ok()"))
        // …and everything happens before the Metal download, which needs a licensed xcodebuild.
        let metal = try #require(
            script.range(of: "-downloadComponent MetalToolchain", options: .backwards))
        #expect(interactive.upperBound < metal.lowerBound)
        // Further confirmations: no taskgated auth panel on the first debug/test run.
        #expect(script.contains("DevToolsSecurity -enable"))
        #expect(script.contains("-t user _developer"))
    }

    @Test func randomPasswordIsHexAndLongEnough() {
        let a = MacVMEngine.randomPassword()
        let b = MacVMEngine.randomPassword()
        #expect(a.count == 20)
        #expect(a.allSatisfy { $0.isHexDigit })
        #expect(a != b)  // 80 bits of entropy — a collision means the generator is broken
    }

    @Test func agentPasswordSettingReads() async throws {
        let suite = UserDefaults(suiteName: "macvm-pw-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            #expect(MacVMSettings.agentPassword == nil)
            suite.set("  hunter2  ", forKey: MacVMSettings.agentPasswordKey)
            #expect(MacVMSettings.agentPassword == "hunter2")
        }
    }

    @Test func firstBootSetupPhaseHasDistinctLabel() {
        let phases: [MacVMBaseProgress.Phase] = [
            .downloadingRestoreImage, .installing, .firstBootSetup, .provisioning, .ready,
        ]
        let labels = phases.map { MacVMBaseProgress(phase: $0).label }
        #expect(Set(labels).count == labels.count)
        #expect(MacVMBaseProgress(phase: .firstBootSetup).label.contains("unattended"))
    }

    @Test func computerUseSettingGatedOnService() async throws {
        let suite = UserDefaults(suiteName: "macvm-cu-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            suite.set(true, forKey: MacVMSettings.computerUseByDefaultKey)
            #expect(MacVMSettings.computerUseByDefault == false)  // service off ⇒ false
            suite.set(true, forKey: MacVMSettings.serviceEnabledKey)
            #expect(MacVMSettings.computerUseByDefault == true)
        }
    }


    // MARK: - Linux guests

    @Test func specDefaultsToMacOSAndRenamePreservesOS() {
        #expect(MacVMSpec(name: "a").os == .macOS)
        let linux = MacVMSpec(name: "a", os: .linux)
        #expect(linux.os == .linux)
        #expect(linux.renamed("b").os == .linux)  // renamed() must not lose the guest OS
        #expect(linux.renamed("b").name == "b")
    }

    @Test func linuxVMNameIsDistinctLowercasedSibling() {
        let sid = SessionID(rawValue: "AB12CD34EF")
        let mac = MacVMManager.vmName(for: sid)
        let lin = MacVMManager.linuxVMName(for: sid)
        #expect(lin.hasPrefix("nucleic-lin-"))
        #expect(lin == lin.lowercased())
        #expect(lin.hasSuffix(ContainerManager.channelSuffix))
        #expect(lin != mac)  // a session's Linux + macOS clones never collide
    }

    /// The narOS-era first-boot provisioner: flavor-driven (desktop bakes everything at image build;
    /// headless pulls `naros-tier-vm`, which owns the sudoers/agent setup the old script did by
    /// hand), and it must seal the base with the readiness flag the host polls for.
    @Test func linuxFirstBootProvisionerIsFlavorDrivenAndSealsTheBase() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let provisioner = repoRoot.appendingPathComponent(
            "guest/linux-base/provision/provision-linux-guest.sh")
        let script = try String(contentsOf: provisioner, encoding: .utf8)
        #expect(script.contains("/etc/naros/manifest.json"))              // flavor comes from the manifest
        #expect(script.contains("apt-get install -y naros-tier-vm"))      // headless pulls the tier
        #expect(script.contains("systemctl disable nucleic-firstboot"))   // runs once
        #expect(script.contains("touch /var/lib/nucleic/provisioned"))    // the host's readiness gate
    }

    @Test func bundleCompletenessIsOSAware() throws {
        let fm = FileManager.default
        let root = fm.temporaryDirectory.appendingPathComponent("linbundle-\(UUID().uuidString)")
        try fm.createDirectory(at: root, withIntermediateDirectories: true)
        defer { try? fm.removeItem(at: root) }
        let bundle = MacVMBundle(root: root)
        // Lay down only the Linux artifacts (kernel + initrd + rootfs disk).
        for url in [bundle.kernelURL, bundle.initrdURL, bundle.diskImageURL] {
            fm.createFile(atPath: url.path, contents: Data("x".utf8))
        }
        #expect(bundle.isComplete(for: .linux) == true)
        #expect(bundle.isComplete(for: .macOS) == false)  // no Mac platform identity/NVRAM
        #expect(bundle.isComplete == false)  // the macOS-flavored convenience accessor
    }

    @Test func baseStatusRoundTripsGuestOS() {
        // A Linux status serializes `os` and reads back as Linux.
        let linux = MacVMBaseStatus(installed: true, provisioned: true, osVersion: "24.04", os: .linux)
        let back = MacVMBaseStatus(json: linux.dictionary)
        #expect(back.os == .linux)
        #expect(back.provisioned == true)
        #expect(back.summary.contains("Linux"))
        // A legacy bundle.json without the `os` key defaults to macOS.
        #expect(MacVMBaseStatus(json: ["installed": true]).os == .macOS)
    }

    @Test func linuxSettingsDefaultsAndOverrides() async throws {
        let suite = UserDefaults(suiteName: "linuxvm-test-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            #expect(MacVMSettings.linuxServiceEnabled == false)
            #expect(MacVMSettings.linuxExposeByDefault == false)  // false while service off
            #expect(MacVMSettings.linuxBasePrebuiltPath == nil)
            // Pinned defaults when unset: Ubuntu kernel/initrd, narOS OCI rootfs (the plain-URL
            // rootfs override is an escape hatch and stays empty).
            #expect(MacVMSettings.linuxKernelURL == MacVMSettings.defaultLinuxKernelURL)
            #expect(MacVMSettings.linuxRootfsURL.isEmpty)
            #expect(MacVMSettings.linuxRootfsImage.contains("naros-vm"))
            #expect(MacVMSettings.linuxBaseBuildDebug == false)

            suite.set(true, forKey: MacVMSettings.linuxServiceEnabledKey)
            suite.set("https://example.test/vmlinux", forKey: MacVMSettings.linuxKernelURLKey)
            #expect(MacVMSettings.linuxServiceEnabled == true)
            #expect(MacVMSettings.linuxExposeByDefault == true)  // defaults true once service on
            #expect(MacVMSettings.linuxKernelURL == "https://example.test/vmlinux")
        }
    }

    #if arch(arm64)
    @Test func defaultLinuxCommandLineBootsConsoleAndRoot() {
        let cmd = MacVMEngine.defaultLinuxCommandLine
        #expect(cmd.contains("console=hvc0"))
        #expect(cmd.contains("root=/dev/vda"))
    }

    /// The bootstrap-initramfs cache is keyed on the `/init` script's content: a name-keyed cache
    /// once kept serving a stale init after the repo's changed, so payload files staged by the new
    /// code were never installed into the rootfs (an unreachable-agent build that looked guest-side).
    @Test func bootstrapCacheNameTracksInitScriptContent() {
        let a = MacVMEngine.bootstrapCacheName(initScript: Data("init v1".utf8))
        let b = MacVMEngine.bootstrapCacheName(initScript: Data("init v2".utf8))
        #expect(a != b)
        #expect(a == MacVMEngine.bootstrapCacheName(initScript: Data("init v1".utf8)))
        #expect(a.hasPrefix("nucleic-bootstrap-") && a.hasSuffix(".cpio.gz"))
        #expect(MacVMEngine.bootstrapCacheName(initScript: nil) == "nucleic-bootstrap-unhashed.cpio.gz")
    }

    @Test func provisionCommandLineIsQuietByDefaultAndVerboseInDebug() {
        // Default: exactly the persisted clone cmdline, so a debug-less build changes nothing.
        #expect(MacVMEngine.linuxProvisionCommandLine(debug: false) == MacVMEngine.defaultLinuxCommandLine)
        // Debug: still boots the same console/root, but verbose — no `quiet`, journal on the console.
        let dbg = MacVMEngine.linuxProvisionCommandLine(debug: true)
        #expect(dbg.contains("console=hvc0"))
        #expect(dbg.contains("root=/dev/vda"))
        #expect(!dbg.contains("quiet"))
        #expect(dbg.contains("systemd.journald.forward_to_console=1"))
    }

    /// The console-log sanitizer behind `debug-report.txt`: systemd probes its "terminal" with
    /// CSI/OSC/DCS sequences, so a raw serial log buries the few real lines (this sample is lifted
    /// from an actual failed provision.log).
    @Test func consoleLogSanitizerStripsEscapesAndKeepsText() {
        let raw = "\u{1B}P+q6E616D65\u{1B}\\\u{1B}[6n\u{1B}[32766;32766H\u{1B}[!p\u{1B}]104\u{1B}\\"
            + "\u{1B}[0m\u{1B}[?7h[nucleic-modsetup] vsock transport loaded\n"
            + "\u{1B}]3008;start=abc;user=root;type=boot\u{1B}\\\n"
            + "\u{1B}7\u{1B}8Debian GNU/Linux forky/sid host hvc0\n\n"
        let clean = MacVMEngine.sanitizeConsoleLog(raw)
        #expect(clean == "[nucleic-modsetup] vsock transport loaded\nDebian GNU/Linux forky/sid host hvc0")
    }

    /// A provision failure must leave a self-contained debug report in the bundle: the recipe, the
    /// error, and the sanitized log tails — not just an opaque "agent never answered".
    @Test func provisionFailureWritesDebugReportIntoBundle() async throws {
        let fm = FileManager.default
        let root = fm.temporaryDirectory.appendingPathComponent("lindebug-\(UUID().uuidString)")
        try fm.createDirectory(at: root, withIntermediateDirectories: true)
        defer { try? fm.removeItem(at: root) }
        let bundle = MacVMBundle(root: root)
        let console = "\u{1B}[6n[nucleic-bootdebug] /dev/vsock: MISSING\n"
        try Data(console.utf8).write(to: root.appendingPathComponent("provision.log"))

        let engine = MacVMEngine(storageRoot: root.appendingPathComponent("store"))
        let error = await engine.linuxProvisionFailure(
            bundle: bundle, phase: "the agent handshake",
            underlying: MacVMError.agentUnavailable("the Linux guest agent never answered"))

        let report = try String(
            contentsOf: root.appendingPathComponent("debug-report.txt"), encoding: .utf8)
        #expect(report.contains("failed phase: the agent handshake"))
        #expect(report.contains("[provision.log tail]"))
        #expect(report.contains("[nucleic-bootdebug] /dev/vsock: MISSING"))  // sanitized, kept
        #expect(!report.contains("\u{1B}"))  // escapes stripped
        #expect(report.contains("kernel:"))  // the recipe is recorded
        // The thrown error itself quotes the guest console and points at the report.
        let message = String(describing: error)
        #expect(message.contains("/dev/vsock: MISSING"))
        #expect(message.contains("debug-report.txt"))
    }

    @Test func linuxCacheNameTracksFilenameWithoutForcingIpsw() {
        let url = URL(string: "https://cloud-images.ubuntu.com/x/ubuntu-24.04-arm64-root.tar.xz")!
        #expect(MacVMEngine.linuxCacheName(for: url) == "ubuntu-24.04-arm64-root.tar.xz")
        // Unlike restoreCacheName, it must NOT append .ipsw.
        #expect(!MacVMEngine.linuxCacheName(for: url).hasSuffix(".ipsw"))
    }

    /// The kernel-release parser behind the modules/kernel coherence check. Ubuntu's rolling
    /// cloud-image URLs keep one filename across respins, so the *name* can't say which kernel a
    /// cached Image is — only the embedded banner can, and it's what pairs the right modules with it.
    @Test func kernelReleaseIsReadFromTheEmbeddedBanner() throws {
        let fm = FileManager.default
        let dir = fm.temporaryDirectory.appendingPathComponent("kver-\(UUID().uuidString)")
        try fm.createDirectory(at: dir, withIntermediateDirectories: true)
        defer { try? fm.removeItem(at: dir) }

        // Shaped like the real banner: binary padding, then the version string mid-file.
        let img = dir.appendingPathComponent("vmlinux")
        var bytes = Data(repeating: 0, count: 64)
        bytes.append(Data("Linux version 7.0.0-28-generic (buildd@bos03-arm64-093) #28-Ubuntu".utf8))
        try bytes.write(to: img)
        #expect(MacVMEngine.kernelRelease(of: img) == "7.0.0-28-generic")

        // A file with no banner yields nil rather than a bogus release (the check then no-ops).
        let blank = dir.appendingPathComponent("blank")
        try Data(repeating: 0x41, count: 256).write(to: blank)
        #expect(MacVMEngine.kernelRelease(of: blank) == nil)
    }

    /// Upstream-identity stamping: a cached artifact is reused only while its recorded identity still
    /// matches, and purging takes the stamp and anything derived from it along. This is what makes a
    /// republished mutable tag (`:latest`, `:26.07`) or an Ubuntu respin actually reach an install.
    @Test func upstreamStampGatesReuseAndPurgeTakesDerivedFiles() throws {
        let fm = FileManager.default
        let dir = fm.temporaryDirectory.appendingPathComponent("stamp-\(UUID().uuidString)")
        try fm.createDirectory(at: dir, withIntermediateDirectories: true)
        defer { try? fm.removeItem(at: dir) }

        let cache = dir.appendingPathComponent("vmlinuz-generic")
        let derived = dir.appendingPathComponent("vmlinux")
        try Data("kernel".utf8).write(to: cache)
        try Data("unwrapped".utf8).write(to: derived)

        // No stamp yet: an artifact predating this mechanism reads as unknown, i.e. stale.
        #expect(MacVMEngine.readUpstreamStamp(for: cache) == nil)
        MacVMEngine.writeUpstreamStamp("sha256:abc", for: cache)
        #expect(MacVMEngine.readUpstreamStamp(for: cache) == "sha256:abc")

        // Purging clears the artifact, its stamp, and the file derived from it — leaving the derived
        // copy behind is exactly how a stale kernel would survive a re-download.
        MacVMEngine.purgeCachedArtifact(cache, derived: [derived])
        #expect(fm.fileExists(atPath: cache.path) == false)
        #expect(fm.fileExists(atPath: MacVMEngine.upstreamStampURL(for: cache).path) == false)
        #expect(fm.fileExists(atPath: derived.path) == false)
    }
    #endif

    // MARK: - Common packages (MacVMPackage)

    @Test func catalogHoldsOnlyOptionalExtrasNotChrome() {
        // Chrome is NOT a catalog entry: every base installs Chrome for Testing unconditionally in
        // provision-macos-guest.sh, so there is nothing to opt into.
        #expect(MacVMPackage.named("chrome") == nil)
        #expect(!MacVMPackage.catalog.contains { $0.id == "chrome" })
        // Xcode is present but grayed-out scaffolding for now.
        #expect(MacVMPackage.xcode.available == false)
        #expect(MacVMPackage.xcode.isInstallable == false)
        #expect(MacVMPackage.xcode.unavailableNote != nil)  // the UI shows a "why" next to the row
        #expect(MacVMPackage.named("xcode") == MacVMPackage.xcode)
        #expect(MacVMPackage.named("nope") == nil)
    }

    @Test func installShellSkipsUnknownAndUnavailableIDs() throws {
        // Unknown and unavailable ids are dropped, and an all-unusable set yields nil so callers skip
        // the guest round-trip entirely. Every id lands there today — the catalog's only entry (xcode)
        // is an unavailable placeholder — so the composer currently returns nil for everything.
        #expect(MacVMPackage.installShell(forIDs: []) == nil)
        #expect(MacVMPackage.installShell(forIDs: ["xcode", "bogus"]) == nil)
        #expect(MacVMPackage.installShell(forIDs: ["chrome"]) == nil)
    }

    @Test func installedIDsParsesOnlyMarkedPackages() {
        // Parsing is catalog-scoped: a marker for a catalog id is reported, one for a non-entry (chrome
        // is no longer a package) is not, so a stale selection can't fake an install.
        #expect(MacVMPackage.installedIDs(
            fromOutput: "\(MacVMPackage.okMarker) xcode") == ["xcode"])
        #expect(MacVMPackage.installedIDs(
            fromOutput: "\(MacVMPackage.okMarker) chrome").isEmpty)
        #expect(MacVMPackage.installedIDs(fromOutput: "nothing here").isEmpty)
    }

    @Test func selectedPackageIDsPersistAndFilterOutUnavailable() async throws {
        let suite = UserDefaults(suiteName: "macvm-pkgs-\(UUID().uuidString)")!
        await ContainerServiceSettings.withDefaults(suite) {
            #expect(MacVMSettings.selectedPackageIDs.isEmpty)
            // A grayed-out (xcode), retired (chrome) or unknown id can never be selected — only
            // installable ids survive, so a selection persisted by an older build is dropped on read.
            MacVMSettings.setSelectedPackageIDs(["chrome", "xcode", "bogus"])
            #expect(MacVMSettings.selectedPackageIDs.isEmpty)
        }
    }

    @Test func baseMDMPolicyDecisionNeverEnrollsTwiceOrReplacesAnOrphanedCA() {
        #expect(MacVMEngine.baseMDMPolicyAction(
            guestEnrolled: false, persistedStateExists: false) == .enroll)
        #expect(MacVMEngine.baseMDMPolicyAction(
            guestEnrolled: false, persistedStateExists: true) == .enroll)
        #expect(MacVMEngine.baseMDMPolicyAction(
            guestEnrolled: true, persistedStateExists: true) == .update)
        #expect(MacVMEngine.baseMDMPolicyAction(
            guestEnrolled: true, persistedStateExists: false) == .orphanedEnrollment)
    }

    @Test func minimalAgentBootstrapDoesOnlyPreMDMControlPlaneWork() throws {
        let script = MacVMEngine.minimalAgentBootstrapScript(user: "agent")
        #expect(script.contains("/usr/local/bin/nash"))
        #expect(script.contains("/Applications/NucleicVMAgent.app"))
        #expect(script.contains("sysadminctl -autologin set"))
        #expect(!script.contains("run_required sudo /usr/sbin/sysadminctl"))
        #expect(script.contains("next-boot agent probe will verify it"))
        #expect(script.contains("launchctl bootstrap"))
        #expect(script.contains("tee \"$SHARE/provision.log\""))
        #expect(script.contains("bootstrap may race launchd"))
        #expect(script.contains("Minimal exec-agent pass failed"))
        #expect(script.contains("STATUS"))
        #expect(!script.contains("softwareupdate"))
        #expect(!script.contains("brew install"))
        #expect(!script.contains("mount_virtiofs"))
        #expect(!script.contains("INSERT OR REPLACE INTO access"))

        let plist = Data(MacVMEngine.minimalAgentLaunchAgentPlist.utf8)
        let parsed = try PropertyListSerialization.propertyList(
            from: plist, options: [], format: nil) as? [String: Any]
        #expect(parsed?["Label"] as? String == "xyz.blakeslee.nucleic.vmagent")
    }

    @Test func onlyACompleteMDMOutcomeCanMarkBasePolicyReady() {
        let base = MacVMBaseStatus(
            installed: true, accountProvisioned: true, agentInstalled: true)
        let complete = MacVMEngine.MDMOutcome(
            enrolled: true, profilesInstalled: 2, log: ["verified"])
        let updated = MacVMEngine.baseStatus(byApplying: complete, to: base)
        #expect(updated?.installed == true)
        #expect(updated?.agentInstalled == true)
        #expect(updated?.mdmEnrolled == true)
        #expect(updated?.profilesInstalled == true)

        #expect(MacVMEngine.baseStatus(byApplying: .init(
            enrolled: false, profilesInstalled: 2, log: []), to: base) == nil)
        #expect(MacVMEngine.baseStatus(byApplying: .init(
            enrolled: true, profilesInstalled: 1, log: []), to: base) == nil)

        // The MDM lane's recipe gate turns on enrollment + profiles.
        var ready = updated!
        ready.provisioned = true
        #expect(MacVMEngine.baseStatusReadyForRecipe(ready, lane: .mdm))
        ready.mdmEnrolled = false
        #expect(!MacVMEngine.baseStatusReadyForRecipe(ready, lane: .mdm))
        ready.mdmEnrolled = true
        ready.profilesInstalled = false
        #expect(!MacVMEngine.baseStatusReadyForRecipe(ready, lane: .mdm))
    }

    @Test func datastoreLaneRecipeGateTurnsOnVerifiedGrants() {
        // Lane B (the default lane) gates the recipe on `policyGrantsVerified`, independent of any MDM
        // enrollment state (docs/MACOS_VM_POLICY_ALTERNATIVE.md).
        var status = MacVMBaseStatus(
            installed: true, accountProvisioned: true, provisioned: true, agentInstalled: true)
        #expect(!MacVMEngine.baseStatusReadyForRecipe(status))                    // default = .datastore
        #expect(!MacVMEngine.baseStatusReadyForRecipe(status, lane: .datastore))
        status.policyGrantsVerified = true
        #expect(MacVMEngine.baseStatusReadyForRecipe(status))
        #expect(MacVMEngine.baseStatusReadyForRecipe(status, lane: .datastore))
        // Verified grants do NOT satisfy the MDM lane, and MDM enrollment does NOT satisfy Lane B.
        #expect(!MacVMEngine.baseStatusReadyForRecipe(status, lane: .mdm))
        var mdm = MacVMBaseStatus(
            installed: true, accountProvisioned: true, provisioned: true, agentInstalled: true,
            mdmEnrolled: true, profilesInstalled: true)
        #expect(!MacVMEngine.baseStatusReadyForRecipe(mdm, lane: .datastore))
        #expect(MacVMEngine.baseStatusReadyForRecipe(mdm, lane: .mdm))
    }

    @Test func mdmGatewayAcceptsOneOrdinaryIPv4AddressOnly() {
        #expect(MacVMEngine.validatedMDMGateway("192.168.64.1\n") == "192.168.64.1")
        #expect(MacVMEngine.validatedMDMGateway("10.0.0.001") == "10.0.0.1")
        #expect(MacVMEngine.validatedMDMGateway("192.168.64.1; touch /tmp/pwned") == nil)
        #expect(MacVMEngine.validatedMDMGateway("192.168.64.1\n10.0.0.1") == nil)
        #expect(MacVMEngine.validatedMDMGateway("127.0.0.1") == nil)
        #expect(MacVMEngine.validatedMDMGateway("0.0.0.0") == nil)
        #expect(MacVMEngine.validatedMDMGateway("224.0.0.1") == nil)
        #expect(MacVMEngine.validatedMDMGateway("192.168.64.999") == nil)
        #expect(MacVMEngine.validatedMDMGateway("fe80::1") == nil)
    }

    @Test func mdmPolicyPassUsesOnlyTheSafeAutomount() {
        let mount = MacVMEngine.mdmPolicyPassMount(hostDirectory: "/tmp/mdm-stage")
        #expect(mount.host == "/tmp/mdm-stage")
        #expect(mount.name == "nucleic-provision")
        #expect(!mount.readOnly)
        #expect(!mount.recreateHostPath)
        #expect(mount.guestPath == nil)
        #expect(!MacVMEngine.directMacOSMount(mount))
    }

    // MARK: - Safe UAMDM approval recognition

    @Test func uamdmClassifierNeverClicksAnUnattributedInstallButton() {
        let install = CGRect(x: 0.7, y: 0.2, width: 0.1, height: 0.04)
        let lines = [
            (text: "Install", box: install),
            (text: "Unrelated Printer Profile", box: CGRect(x: 0.2, y: 0.7, width: 0.3, height: 0.05)),
        ]
        #expect(MacVMEngine.uamdmApprovalAction(in: lines) == .unknown)
    }

    @Test func uamdmClassifierSelectsOnlyExactNucleicControls() {
        let profile = CGRect(x: 0.2, y: 0.7, width: 0.3, height: 0.05)
        let install = CGRect(x: 0.7, y: 0.2, width: 0.1, height: 0.04)
        let dontInstall = CGRect(x: 0.5, y: 0.2, width: 0.15, height: 0.04)
        let action = MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrollment", box: profile),
            (text: "Don't Install", box: dontInstall),
            (text: " Install ", box: install),
        ])
        #expect(action == .install(install))

        #expect(MacVMEngine.uamdmApprovalAction(
            in: [(text: "Nucleic MDM Enrollment", box: profile)])
            == .openEnrollmentProfile(profile))
    }

    @Test func uamdmReviewSheetEnrollButtonIsClicked() {
        // The macOS 27 profile-review sheet confirms with "Enroll", not "Install" — a live run stalled
        // because the classifier only knew "Install". The Enroll button (not Ignore/Cancel) is chosen.
        let enroll = CGRect(x: 0.28, y: 0.24, width: 0.06, height: 0.03)
        let action = MacVMEngine.uamdmApprovalAction(in: [
            (text: "Are you sure you want to install this device profile?", box: .zero),
            (text: "Nucleic MDM Enrollment", box: CGRect(x: 0.4, y: 0.5, width: 0.2, height: 0.03)),
            (text: "Enroll", box: enroll),
            (text: "Ignore", box: CGRect(x: 0.55, y: 0.24, width: 0.06, height: 0.03)),
            (text: "Cancel", box: CGRect(x: 0.62, y: 0.24, width: 0.06, height: 0.03)),
        ])
        #expect(action == .install(enroll))
    }

    @Test func uamdmAnyApplePasswordSheetIsAnswerableWithoutSheetSpecificLabels() {
        // Generic detection: the stable "Enter your password" phrase + a located Password field is
        // enough. No account short name, no sheet-specific intent phrase, no submit-button label are
        // required (they mis-OCR; the loop submits with Return). Works for both the profile-install and
        // the residual trust sheet.
        let field = CGRect(x: 0.44, y: 0.39, width: 0.03, height: 0.02)
        let install: [(text: String, box: CGRect)] = [
            (text: "System Settings is trying to modify your system settings.", box: .zero),
            (text: "Enter your password to allow this.", box: .zero),
            (text: "Nucleic Agent", box: .zero),
            (text: "Password", box: field),
            (text: "Modify Settings", box: CGRect(x: 0.7, y: 0.25, width: 0.15, height: 0.04)),
        ]
        #expect(MacVMEngine.uamdmApprovalAction(in: install)
            == .authenticate(sheet: "modify-settings", passwordField: field))
        // No "Enter your password" phrase → not an actionable sheet.
        #expect(MacVMEngine.uamdmApprovalAction(in: Array(install.dropFirst(1)).filter {
            !$0.text.contains("Enter your password")
        }) == .unknown)
    }

    @Test func uamdmTolueratesOCRNoiseInFieldAndWrappedContext() {
        // The EXACT lines Vision returned on the live guest that stalled: the sentence wraps across
        // three observations, and the field placeholder came back as "Peseword" and the button as
        // "Updale Settings". Reading-order join handles the wrap; fuzzy field matching handles the
        // placeholder typo; Return-submit means the mangled button label no longer matters.
        let field = CGRect(x: 0.44, y: 0.39, width: 0.03, height: 0.02)
        let mangled: [(text: String, box: CGRect)] = [
            (text: "You are making changes to the", box: .zero),
            (text: "System Certificate Trust", box: .zero),
            (text: "Settings.", box: .zero),
            (text: "Enter your password to continue", box: .zero),
            (text: "Nucleic Agent", box: .zero),
            (text: "Peseword", box: field),
            (text: "Updale Settings", box: CGRect(x: 0.6, y: 0.3, width: 0.15, height: 0.04)),
        ]
        #expect(MacVMEngine.uamdmApprovalAction(in: mangled)
            == .authenticate(sheet: "certificate-trust", passwordField: field))
    }

    @Test func uamdmDistinguishesEachAuthorizationSheetForItsOwnRetryBudget() {
        // The flow raises several sheets in sequence; each needs its own budget, or retries spent on
        // the first leave the last unanswered — how a live run stalled on the final MDM enrollment
        // sheet after exhausting a single shared counter upstream.
        let field = CGRect(x: 0.44, y: 0.39, width: 0.03, height: 0.02)
        func sheet(_ intent: String) -> String? {
            let action = MacVMEngine.uamdmApprovalAction(in: [
                (text: intent, box: .zero),
                (text: "Enter your password to continue", box: .zero),
                (text: "Password", box: field),
            ])
            if case .authenticate(let s, _) = action { return s }
            return nil
        }
        #expect(sheet("You are making changes to the System Certificate Trust Settings.")
            == "certificate-trust")
        // The exact wording of the final enrollment sheet observed on macOS 27.
        #expect(sheet("Device Management is trying to enroll you in a remote management (MDM) service.")
            == "mdm-enroll")
        #expect(sheet("System Settings is trying to modify your system settings.") == "modify-settings")
        // Distinct sheets must not collide onto one budget key.
        #expect(sheet("You are making changes to the System Certificate Trust Settings.")
            != sheet("Device Management is trying to enroll you in a remote management (MDM) service."))
    }

    @Test func clickPointScalesWithTheCapturedFrameNotAFixedResolution() {
        // Vision boxes are normalized, so the SAME box must land proportionally on any panel size.
        // Hardcoding 1920×1200 silently misplaced every click the moment the capture differed.
        let box = CGRect(x: 0.50, y: 0.60, width: 0.04, height: 0.02)  // midX 0.52, midY 0.61
        let hd = MacVMEngine.clickPoint(forNormalizedBox: box, in: CGSize(width: 1920, height: 1200))
        #expect(hd.x == 998)   // 0.52 × 1920
        #expect(hd.y == 468)   // (1 − 0.61) × 1200

        // A different panel: the point must move proportionally, not stay put. (Compared with a ±1
        // tolerance because rounding each product independently is not exactly linear.)
        let retina = MacVMEngine.clickPoint(
            forNormalizedBox: box, in: CGSize(width: 3840, height: 2400))
        #expect(abs(retina.x - hd.x * 2) <= 1)
        #expect(abs(retina.y - hd.y * 2) <= 1)

        // And a non-16:10 panel scales each axis independently.
        let wide = MacVMEngine.clickPoint(
            forNormalizedBox: box, in: CGSize(width: 2560, height: 1440))
        #expect(wide.x == Int((0.52 * 2560).rounded()))
        #expect(wide.y == Int((0.39 * 1440).rounded()))
    }

    @Test func passwordPlaceholderMatchingToleratesSpellingAndOCRDamage() {
        let field = CGRect(x: 0.44, y: 0.39, width: 0.03, height: 0.02)
        func box(_ text: String) -> CGRect? {
            MacVMEngine.passwordFieldBox(in: [(text: text, box: field)])
        }
        // Real placeholder variants.
        #expect(box("Password") == field)
        #expect(box("Passcode") == field)
        // Observed OCR damage.
        #expect(box("Peseword") == field)
        #expect(box("Passwrd") == field)
        // Must NOT swallow unrelated UI words that happen to be short.
        #expect(box("Wallpaper") == nil)
        #expect(box("Passkeys Access for Web Browsers") == nil)
        #expect(box("Cancel") == nil)
        #expect(box("") == nil)
    }

    /// The regression this whole workstream exists for: every match in the classifier except the
    /// password field compared OCR output EXACTLY, so one substituted glyph in a six-letter button
    /// label meant the review sheet classified as `.unknown` and the loop sat there re-navigating
    /// panes until its deadline. These are the readings Vision actually produced on live runs.
    @Test func uamdmClassifierActsOnMangledButtonAndRowText() {
        let row = CGRect(x: 0.2, y: 0.4, width: 0.3, height: 0.05)
        let enroll = CGRect(x: 0.28, y: 0.24, width: 0.06, height: 0.03)

        // "Enroll" read as "EnroII" (capital-i for l — the single most common UI-text confusion).
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Are you sure you want to instaII this device profile?", box: .zero),
            (text: "Nucleic MDM EnroIIment", box: row),
            (text: "EnroII", box: enroll),
            (text: "Cancel", box: CGRect(x: 0.62, y: 0.24, width: 0.06, height: 0.03)),
        ]) == .install(enroll))

        // The ellipsis variant needs no table entry of its own — folding drops trailing punctuation.
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrollment", box: row),
            (text: "Install…", box: enroll),
        ]) == .install(enroll))

        // A damaged row still opens: the pending row is the one state the loop MUST click.
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrolment", box: row),
            (text: "Profile not installed. Double-click to review.", box: .zero),
        ]) == .openEnrollmentProfile(row))

        // And a wrapped sentence with damage inside it still identifies its sheet.
        let field = CGRect(x: 0.44, y: 0.39, width: 0.03, height: 0.02)
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Device Management is trying to enroII you in a", box: .zero),
            (text: "remote management (MDM) service.", box: .zero),
            (text: "Enter your passwerd to allow this.", box: .zero),
            (text: "Password", box: field),
        ]) == .authenticate(sheet: "mdm-enroll", passwordField: field))
    }

    /// Fuzziness that swallows the wrong control is worse than none: these are the neighbours on the
    /// very screens the loop drives, and none of them may read as a button it is allowed to press.
    @Test func fuzzyLabelMatchingStillRejectsTheWrongControls() {
        #expect(MacVMEngine.fuzzyEquals("Install", "Install"))
        #expect(MacVMEngine.fuzzyEquals(" Install ", "Install"))
        #expect(MacVMEngine.fuzzyEquals("lnstall", "Install"))
        #expect(MacVMEngine.fuzzyEquals("Install…", "Install"))
        // Destructive or dismissive neighbours on the same sheet.
        #expect(!MacVMEngine.fuzzyEquals("Don't Install", "Install"))
        #expect(!MacVMEngine.fuzzyEquals("Uninstall", "Install"))
        #expect(!MacVMEngine.fuzzyEquals("Installed", "Install"))
        #expect(!MacVMEngine.fuzzyEquals("Ignore", "Enroll"))
        #expect(!MacVMEngine.fuzzyEquals("Cancel", "Enroll"))
        #expect(!MacVMEngine.fuzzyEquals("Enrolled", "Enroll"))

        // Phrase search survives damage inside a wrapped sentence…
        #expect(MacVMEngine.fuzzyContains(
            "You are making changes to the System Certiflcate Trust Settings.", "Certificate Trust"))
        // …without finding phrases that simply are not there.
        #expect(!MacVMEngine.fuzzyContains(
            "Nucleic Agent Password Modify Settings", "Enter your password"))
        #expect(!MacVMEngine.fuzzyContains(
            "Nucleic MDM Enrollment Profile not installed. Double-click to review.",
            "installation failed"))

        // Phrase matching must respect word boundaries. Without that, "Enrollme[nt Installed]" is a
        // single insertion away from "not installed" — so the negation guard that protects the
        // `.installed` classification fired on a profile that HAD installed, and the loop went back to
        // clicking a row with nothing left to do.
        #expect(!MacVMEngine.fuzzyContains("Nucleic MDM Enrollment Installed", "not installed"))
        #expect(MacVMEngine.fuzzyContains("Nucleic MDM Enrollment Not Installed", "not installed"))
    }

    /// Folding is the shared normalization every match runs through, so its merges are load-bearing
    /// in both directions: too few and OCR damage still hides a label, too many and distinct labels
    /// collide.
    @Test func ocrFoldMergesConfusableGlyphsAndPunctuation() {
        #expect(MacVMEngine.ocrFold("Install") == MacVMEngine.ocrFold("lnstall"))
        #expect(MacVMEngine.ocrFold("Enroll") == MacVMEngine.ocrFold("EnroII"))
        #expect(MacVMEngine.ocrFold("Double-click") == MacVMEngine.ocrFold("Double click"))
        #expect(MacVMEngine.ocrFold("Install…") == MacVMEngine.ocrFold("Install"))
        #expect(MacVMEngine.ocrFold("  Enroll  ") == MacVMEngine.ocrFold("Enroll"))
        // Distinct words must survive folding as distinct words.
        #expect(MacVMEngine.ocrFold("Enroll") != MacVMEngine.ocrFold("Ignore"))
        #expect(MacVMEngine.ocrFold("Install") != MacVMEngine.ocrFold("Installed"))
    }

    /// Vision ranks several readings per line and we ask for them; preferring the one carrying more of
    /// this flow's vocabulary recovers a line whose top reading was the damaged one. It must never
    /// invent text — only choose among readings Vision itself proposed — and must keep Vision's own
    /// order when the lexicon says nothing.
    @Test func recognitionPrefersTheReadingWithKnownVocabulary() {
        let lexicon = MacVMEngine.approvalLexicon
        #expect(MacVMEngine.bestCandidate(among: ["EnroII", "Enroll", "Enrol"], lexicon: lexicon)
            == "Enroll")
        #expect(MacVMEngine.bestCandidate(
            among: ["Nucleic MDM Enroliment", "Nucleic MDM Enrollment"], lexicon: lexicon)
            == "Nucleic MDM Enrollment")
        // No lexicon hit anywhere → Vision's own top choice, unchanged.
        #expect(MacVMEngine.bestCandidate(among: ["zzz", "qqq"], lexicon: lexicon) == "zzz")
        #expect(MacVMEngine.bestCandidate(among: [], lexicon: lexicon) == nil)
        // An empty lexicon is exactly the old behaviour.
        #expect(MacVMEngine.bestCandidate(among: ["EnroII", "Enroll"], lexicon: []) == "EnroII")
    }

    /// Clicks are computed in the surface's INPUT space, never in the capture's pixel space. Once
    /// recognition moved to a native-resolution capture the two stopped being the same size, and
    /// scaling by the frame would have doubled every coordinate straight off the screen.
    @Test func clickMappingUsesTheInputSpaceNotTheCaptureResolution() {
        #expect(MacVMEngine.surfaceInputSize == CGSize(width: 1920, height: 1200))
        let box = CGRect(x: 0.50, y: 0.60, width: 0.04, height: 0.02)
        let click = MacVMEngine.clickPoint(forNormalizedBox: box, in: MacVMEngine.surfaceInputSize)
        #expect(click.x == 998)
        #expect(click.y == 468)
        // A 2× recognition capture recognizes the SAME normalized box; the click must not move.
        #expect(click == MacVMEngine.clickPoint(forNormalizedBox: box))
    }

    /// Render `lines` as dark text on a light background at the surface's capture size and encode it
    /// the way a capture is encoded. Synthesized rather than checked in as a fixture so the test needs
    /// no binary asset and stays legible about what it is asserting.
    static func syntheticCapture(
        _ lines: [String], width: Int = 1920, height: Int = 1200
    ) -> Data? {
        guard let context = CGContext(
            data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
            space: CGColorSpaceCreateDeviceRGB(),
            bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
        else { return nil }
        context.setFillColor(CGColor(red: 0.96, green: 0.96, blue: 0.96, alpha: 1))
        context.fill(CGRect(x: 0, y: 0, width: width, height: height))
        let font = CTFontCreateWithName("Helvetica" as CFString, 40, nil)
        for (index, line) in lines.enumerated() {
            let attributed = NSAttributedString(
                string: line,
                attributes: [
                    .font: font,
                    .foregroundColor: CGColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1),
                ])
            context.textPosition = CGPoint(x: 120, y: height - 200 - (index * 90))
            CTLineDraw(CTLineCreateWithAttributedString(attributed), context)
        }
        guard let image = context.makeImage() else { return nil }
        let out = NSMutableData()
        guard let destination = CGImageDestinationCreateWithData(
            out, UTType.jpeg.identifier as CFString, 1, nil)
        else { return nil }
        CGImageDestinationAddImage(destination, image, nil)
        guard CGImageDestinationFinalize(destination) else { return nil }
        return out as Data
    }

    /// The recognizer must actually recognize. Everything else in this file tests what the classifier
    /// does with recognized lines — nothing asserted that any line ever comes back, and that is exactly
    /// where a live run failed: Vision returned nothing for 566 consecutive frames of a perfectly sharp
    /// screenshot, `try?` discarded the reason, and the loop dutifully classified every frame
    /// `.unknown` and cycled Settings panes until its deadline. An end-to-end assertion over the real
    /// entry point is the cheap check that would have caught it before a 40-minute base build did.
    @Test func recognizerActuallyReadsTextFromACapture() async throws {
        let capture = try #require(
            Self.syntheticCapture(["Nucleic MDM Enrollment", "Enroll", "Password"]),
            "could not synthesize a capture to recognize")
        let recognition = await MacVMEngine.recognizeTextLines(
            inCapture: capture, lexicon: MacVMEngine.approvalLexicon)
        #expect(recognition.failure == nil, "recognizer reported: \(recognition.failure ?? "")")
        #expect(!recognition.lines.isEmpty, "the recognizer returned no observations at all")
        let joined = recognition.lines.map(\.text).joined(separator: " ")
        #expect(MacVMEngine.fuzzyContains(joined, "Enrollment"))
        #expect(MacVMEngine.fuzzyContains(joined, "Enroll"))
        // And the whole pipeline, not just the recognizer: these lines must drive a real action.
        #expect(
            MacVMEngine.stateLabel(MacVMEngine.uamdmApprovalAction(in: recognition.lines))
                == "install")
    }

    /// The gate that turns "five silent minutes then blame the guest" into an instant, named failure.
    /// It must pass on a healthy host — if this ever fails, the approval loop could not have worked.
    @Test func textRecognitionSelfTestPassesOnAHealthyHost() async {
        #expect(await MacVMEngine.verifyTextRecognition() == nil)
    }

    /// A recognizer failure must be *reported*, never silently returned as "no text on screen" — the
    /// conflation that made a broken recognizer look like a blank framebuffer for a whole run.
    @Test func recognizerReportsFailureRatherThanReadingAsAnEmptyScreen() async {
        let notAnImage = Data("this is not an image".utf8)
        let recognition = await MacVMEngine.recognizeTextLines(inCapture: notAnImage)
        #expect(recognition.lines.isEmpty)
        #expect(recognition.failure != nil, "an undecodable capture must report why, not read as empty")
    }

    /// Recognition boxes must be usable as clicks: normalized, inside the frame, and landing inside
    /// the surface's input space after conversion — whatever resolution the capture was.
    @Test func recognizedBoxesConvertToClicksInsideTheInputSpace() async throws {
        let capture = try #require(Self.syntheticCapture(["Nucleic MDM Enrollment", "Enroll"]))
        let lines = await MacVMEngine.recognizeTextLines(inCapture: capture).lines
        try #require(!lines.isEmpty)
        for line in lines {
            #expect(line.box.minX >= 0 && line.box.maxX <= 1)
            #expect(line.box.minY >= 0 && line.box.maxY <= 1)
            let point = MacVMEngine.clickPoint(
                forNormalizedBox: line.box, in: MacVMEngine.surfaceInputSize)
            #expect(point.x >= 0 && point.x <= Int(MacVMEngine.surfaceInputSize.width))
            #expect(point.y >= 0 && point.y <= Int(MacVMEngine.surfaceInputSize.height))
        }
    }

    @Test func passwordFieldFuzzyMatchAndEditDistanceBounds() {
        #expect(MacVMEngine.editDistance("peseword", "password") == 2)
        #expect(MacVMEngine.editDistance("password", "password") == 0)
        let field = CGRect(x: 0.44, y: 0.39, width: 0.03, height: 0.02)
        // Lowest of several plausible matches is chosen (the field, below the account row).
        let high = CGRect(x: 0.44, y: 0.9, width: 0.03, height: 0.02)
        #expect(MacVMEngine.passwordFieldBox(in: [
            (text: "Passwrd", box: high),
            (text: "Peseword", box: field),
        ]) == field)
        // A word too far from "password" is not treated as the field.
        #expect(MacVMEngine.passwordFieldBox(in: [
            (text: "Wallpaper", box: field),
        ]) == nil)
    }

    /// `bash -n` over a generated script; `nil` when it parses. Returns the parser's own message so a
    /// failure names the line rather than just asserting "invalid".
    static func bashSyntaxError(in script: String) -> String? {
        let bash = URL(fileURLWithPath: "/bin/bash")
        guard FileManager.default.isExecutableFile(atPath: bash.path) else { return nil }
        let scriptURL = FileManager.default.temporaryDirectory
            .appendingPathComponent("nucleic-bootstrap-lint-\(UUID().uuidString).sh")
        defer { try? FileManager.default.removeItem(at: scriptURL) }
        do { try script.write(to: scriptURL, atomically: true, encoding: .utf8) } catch {
            return "could not stage the script: \(error)"
        }
        let process = Process()
        process.executableURL = bash
        process.arguments = ["-n", scriptURL.path]
        let errors = Pipe()
        process.standardError = errors
        do { try process.run() } catch { return "could not run bash -n: \(error)" }
        let output = errors.fileHandleForReading.readDataToEndOfFile()
        process.waitUntilExit()
        guard process.terminationStatus != 0 else { return nil }
        return String(decoding: output, as: UTF8.self)
    }

    /// `security add-trusted-cert` must never appear in the boot-1 bootstrap again. It raises a
    /// SecurityAgent authorization sheet owned by a root CLI with no GUI app: it never becomes key so
    /// it cannot be driven, and it is a GUI dialog rather than a terminal read so redirecting stdin
    /// does not dismiss it — the command just blocks until the whole 900 s boot times out. It has
    /// wedged this build three separate times. Relaxing the gating right first is not a way back in
    /// either: `authorizationdb write … allow` silently no-ops on macOS 27.
    ///
    /// The standing rule this pins: nothing in this script may be able to hang the build. Every
    /// `security` invocation runs under `run_bounded`, so an unanswerable prompt becomes a reported
    /// failure in seconds instead of a silent stall.
    @Test func minimalAgentBootstrapCannotStallOnAnUnanswerablePrompt() {
        let script = MacVMEngine.minimalAgentBootstrapScript(user: "agent")
        var sawBoundedSecurityCall = false
        for line in script.split(separator: "\n") {
            let code = line.drop(while: { $0 == " " })
            guard !code.hasPrefix("#") else { continue }
            #expect(
                !code.contains("add-trusted-cert"),
                "raises an undriveable SecurityAgent sheet and blocks the boot: \(code)")
            #expect(
                !code.contains("authorizationdb"),
                "silently no-ops on macOS 27; it only ever bought a false sense of progress: \(code)")
            if code.contains("/usr/bin/security ") {
                sawBoundedSecurityCall = true
                #expect(
                    code.contains("run_bounded"),
                    "every security call must carry a hard deadline: \(code)")
            }
        }
        #expect(sawBoundedSecurityCall, "the trust step still has to talk to `security` at all")
        // The script is assembled in a Swift multi-line string, where a mis-escaped `\` continuation
        // or quote produces a file that only fails once a guest is booted — a ~15-minute round trip to
        // learn something `bash -n` answers instantly.
        #expect(Self.bashSyntaxError(in: script) == nil)
        // Trust is established by writing the admin domain as a file — the one route that calls no
        // authorization-gated API and therefore cannot prompt.
        #expect(script.contains("/Library/Security/Trust Settings/Admin.plist"))
        #expect(script.contains("run_bounded()"))
    }

    @Test func uamdmClassifierDoesNotMistakeNotInstalledForSuccess() {
        let profile = CGRect(x: 0.2, y: 0.7, width: 0.3, height: 0.05)
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrollment", box: profile),
            (text: "Not Installed", box: .zero),
        ]) == .openEnrollmentProfile(profile))
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrollment", box: profile),
            (text: "Installed", box: .zero),
        ]) == .installed)
    }

    /// macOS 27's Device Management pane renders an installed profile as its display name over an
    /// "<n> settings" subtitle and never prints the word "Installed" — so keying `.installed` on that
    /// word alone classified a *completed* install as "there is still a row to open". A live run
    /// stalled exactly there: the CA root profile sat installed and selected on screen while the pass
    /// re-clicked its row, exhausted the click budget, and then idled to its deadline.
    @Test func uamdmClassifierReadsTheMacOS27InstalledRow() {
        let row = CGRect(x: 0.2, y: 0.4, width: 0.3, height: 0.05)
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrollment", box: row),
            (text: "1 setting", box: .zero),
        ]) == .installed)
        // Plural, and with the surrounding pane chrome the real screen carries.
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Device Management", box: .zero),
            (text: "Work or School Account", box: .zero),
            (text: "Nucleic MDM Enrollment", box: row),
            (text: "3 settings", box: .zero),
        ]) == .installed)
        // A row with no settings subtitle is still just a row to open — the hint must not fire on the
        // pending/downloaded state, which is the one the loop genuinely has to click.
        #expect(MacVMEngine.uamdmApprovalAction(
            in: [(text: "Nucleic MDM Enrollment", box: row)]) == .openEnrollmentProfile(row))
    }

    /// The failure alert must be recognized, and must win over every other rule — it sits on top of
    /// the Device Management pane, so the row underneath still matches. A live run showed this exact
    /// alert while the loop kept working against the dead screen and then reported a generic timeout,
    /// discarding the one frame that named the fault.
    @Test func uamdmClassifierRecognizesTheInstallFailureAlert() {
        let row = CGRect(x: 0.2, y: 0.4, width: 0.3, height: 0.05)
        let alert: [(text: String, box: CGRect)] = [
            (text: "System Settings", box: .zero),
            (text: "Device Management", box: .zero),
            (text: "Nucleic MDM Enrollment", box: row),  // still visible behind the alert
            (text: "Profile installation failed.", box: .zero),
            (text: "The certificate could not be verified", box: .zero),
            (text: "(authentication error).", box: .zero),
            (text: "OK", box: .zero),
        ]
        guard case .installFailed(let screen) = MacVMEngine.uamdmApprovalAction(in: alert) else {
            Issue.record("an install-failure alert must classify as .installFailed")
            return
        }
        // The recognized text is carried out so the error names what was on screen.
        #expect(screen.localizedCaseInsensitiveContains("could not be verified"))

        // Wording variants seen across macOS versions.
        for line in ["Profile Installation Failed", "failed to install the profile"] {
            let action = MacVMEngine.uamdmApprovalAction(in: [
                (text: "Nucleic MDM Enrollment", box: row), (text: line, box: .zero),
            ])
            #expect(MacVMEngine.stateLabel(action) == "install-failed", "missed: \(line)")
        }

        // And it must not fire on the healthy screens, or every run would abort immediately.
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrollment", box: row),
            (text: "Profile not installed. Double-click to review.", box: .zero),
        ]) == .openEnrollmentProfile(row))
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "Nucleic MDM Enrollment", box: row), (text: "3 settings", box: .zero),
        ]) == .installed)
    }

    /// Regression, from a live run that classified twenty consecutive frames as `.installed` while the
    /// row on them read "Profile not installed. Double-click to review" — so the loop never clicked it
    /// and the enrollment never started. The `.installed` hint had been matching the bare substring
    /// " setting", which occurs inside **"System Settings"** in the menu bar of every screen this loop
    /// ever inspects. The subtitle must be matched as a whole line, and an explicit "not installed"
    /// must veto the hint outright.
    @Test func uamdmClassifierIsNotFooledByTheSystemSettingsMenuBar() {
        let row = CGRect(x: 0.2, y: 0.4, width: 0.3, height: 0.05)
        // The exact shape of the failing frame: menu-bar chrome plus a not-installed row.
        let downloaded: [(text: String, box: CGRect)] = [
            (text: "System Settings", box: .zero),
            (text: "Device Management", box: .zero),
            (text: "Downloaded", box: .zero),
            (text: "Nucleic MDM Enrollment", box: row),
            (text: "Profile not installed. Double-click to review.", box: .zero),
        ]
        #expect(MacVMEngine.uamdmApprovalAction(in: downloaded) == .openEnrollmentProfile(row))

        // "System Settings" alone must never satisfy the settings-count subtitle.
        #expect(!MacVMEngine.isSettingsCountLine("System Settings"))
        #expect(!MacVMEngine.isSettingsCountLine("Settings"))
        #expect(!MacVMEngine.isSettingsCountLine("Privacy & Security settings"))
        #expect(MacVMEngine.isSettingsCountLine("1 setting"))
        #expect(MacVMEngine.isSettingsCountLine("3 settings"))
        #expect(MacVMEngine.isSettingsCountLine("  12 Settings  "))

        // And an installed row that ALSO carries the menu bar still classifies as installed.
        #expect(MacVMEngine.uamdmApprovalAction(in: [
            (text: "System Settings", box: .zero),
            (text: "Nucleic MDM Enrollment", box: row),
            (text: "3 settings", box: .zero),
        ]) == .installed)
    }

    @Test func uamdmPasswordFieldIsClickedAtItsBoxCenter() {
        // The macOS 27 SecurityAgent sheet renders "Password" as the placeholder INSIDE the field, so
        // the field is clicked at the recognized box's center (`clickPoint`). The earlier heuristic
        // offset the click to the right of the box — off the edge of the narrow dialog — so the field
        // never focused and the typed password went nowhere (164 frames stuck on the trust sheet).
        let field = CGRect(x: 0.44, y: 0.61, width: 0.03, height: 0.02)
        let point = MacVMEngine.clickPoint(forNormalizedBox: field)
        #expect(point.x == Int(((0.44 + 0.015) * 1920).rounded()))  // box mid-x, inside the dialog
        #expect(point.x < 1075)  // stays within the ~x845–1075 dialog, unlike the old maxX+0.18 offset
    }

    // MARK: - Built-in MDM policy assets

    @Test func designatedRequirementComesFromTheSignedCodeObject() throws {
        let requirement = try #require(MacVMEngine.designatedRequirement(
            forAgentAt: URL(fileURLWithPath: "/usr/bin/true")))
        #expect(!requirement.isEmpty)
        #expect(requirement.contains("identifier"))
    }

    @Test func builtInMDMPoliciesExposeExactTopLevelIdentifiers() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let urls = try #require(MacVMEngine.builtInMDMPolicyProfileURLs(
            bundleResourceURL: nil, devRepoRoot: repoRoot))
        let identifiers = try MacVMEngine.configurationProfileIdentifiers(
            in: urls.map { try Data(contentsOf: $0) })
        #expect(identifiers == [
            "xyz.blakeslee.nucleic.pppc.vmagent",
            "xyz.blakeslee.nucleic.notifications.suppress",
        ])
    }

    @Test func builtInPPPCPolicyBindsToTheActuallyStagedAgentRequirement() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let urls = try #require(MacVMEngine.builtInMDMPolicyProfileURLs(
            bundleResourceURL: nil, devRepoRoot: repoRoot))
        let original = try urls.map { try Data(contentsOf: $0) }
        let requirement = #"identifier "xyz.blakeslee.nucleic.vmagent" and cdhash H"1234""#
        let rewritten = try MacVMEngine.policyProfiles(
            original, agentCodeRequirement: requirement)
        #expect(rewritten[1] == original[1]) // notification policy has no PPPC requirement

        let root = try PropertyListSerialization.propertyList(
            from: rewritten[0], options: [], format: nil) as? [String: Any]
        let payloads = try #require(root?["PayloadContent"] as? [[String: Any]])
        let tcc = try #require(payloads.first {
            $0["PayloadType"] as? String == "com.apple.TCC.configuration-profile-policy"
        })
        let services = try #require(tcc["Services"] as? [String: Any])
        for name in ["SystemPolicyAllFiles", "SystemPolicyNetworkVolumes"] {
            let entries = try #require(services[name] as? [[String: Any]])
            #expect(entries.count == 1)
            #expect(entries[0]["CodeRequirement"] as? String == requirement)
        }
    }

    // MARK: - MDM failure diagnostics (docs/MACOS_VM_PROVISIONING_REPAIR_PLAN.md, Workstream 0)

    @Test func guestOutputSummaryKeepsBothStreams() {
        // The enroll script narrates on stdout and fails on stderr, so a message built from either
        // alone loses half the story — which is how the "exit 0 but no marker" case went unexplained.
        let summary = MacVMEngine.boundedGuestOutput(
            stdout: "[mdm-enroll] pinned mdm.nucleic.internal -> 192.168.64.1\n",
            stderr: "LSOpenURLsWithRole() failed\n")
        #expect(summary.contains("stdout: [mdm-enroll] pinned"))
        #expect(summary.contains("stderr: LSOpenURLsWithRole"))
    }

    @Test func guestOutputSummaryIsBoundedAndNamesAnEmptyResult() {
        let long = String(repeating: "x", count: 5_000)
        let summary = MacVMEngine.boundedGuestOutput(stdout: long, stderr: "", limit: 100)
        #expect(summary.count < 200)
        #expect(MacVMEngine.boundedGuestOutput(stdout: "  \n", stderr: "") == "no output")
    }

    @Test func indentedGuestOutputLabelsOnlyTheStreamsThatProducedText() {
        let both = MacVMEngine.indentedGuestOutput(stdout: "one\ntwo", stderr: "bad")
        #expect(both.contains("  stdout:\n    one\n    two"))
        #expect(both.contains("  stderr:\n    bad"))
        let outOnly = MacVMEngine.indentedGuestOutput(stdout: "one", stderr: "   ")
        #expect(!outOnly.contains("stderr"))
        #expect(MacVMEngine.indentedGuestOutput(stdout: "", stderr: "") == "  (no output)")
    }

    @Test func approvalStateLabelsAreDistinctAndStable() {
        // These strings are the transcript's state column; a collision would make two different
        // screens indistinguishable in the one artifact a failed live run leaves behind.
        let labels = [
            MacVMEngine.stateLabel(.openEnrollmentProfile(.zero)),
            MacVMEngine.stateLabel(.install(.zero)),
            MacVMEngine.stateLabel(.authenticate(sheet: "mdm-enroll", passwordField: .zero)),
            MacVMEngine.stateLabel(.installed),
            MacVMEngine.stateLabel(.unknown),
        ]
        #expect(Set(labels).count == labels.count)
        #expect(labels.allSatisfy { !$0.isEmpty && !$0.contains(" ") })
        #expect(MacVMEngine.stateLabel(.unknown) == "unknown")
    }

    @Test func configurationProfileIdentifierRejectsNestedOrMalformedPayloads() throws {
        let nestedOnly = try PropertyListSerialization.data(
            fromPropertyList: [
                "PayloadType": "Configuration",
                "PayloadContent": [["PayloadIdentifier": "nested.is.not.enough"]],
            ], format: .xml, options: 0)
        #expect(throws: MacVMEngine.MDMOrchestrationError.self) {
            _ = try MacVMEngine.configurationProfileIdentifiers(in: [nestedOnly])
        }
        #expect(throws: MacVMEngine.MDMOrchestrationError.self) {
            _ = try MacVMEngine.configurationProfileIdentifiers(in: [Data("not a plist".utf8)])
        }
    }

    @Test func builtInMDMPolicyResolutionRequiresACompleteSet() throws {
        let root = FileManager.default.temporaryDirectory
            .appendingPathComponent("mdm-policy-\(UUID().uuidString)", isDirectory: true)
        defer { try? FileManager.default.removeItem(at: root) }
        let bundled = root.appendingPathComponent("bundle", isDirectory: true)
        let bundledMacVM = bundled.appendingPathComponent("macvm", isDirectory: true)
        let repo = root.appendingPathComponent("repo", isDirectory: true)
        let sourcePolicies = repo.appendingPathComponent(
            "scripts/macos-notification-fix", isDirectory: true)
        try FileManager.default.createDirectory(
            at: bundledMacVM, withIntermediateDirectories: true)
        try FileManager.default.createDirectory(
            at: sourcePolicies, withIntermediateDirectories: true)

        let names = MacVMEngine.builtInMDMPolicyProfileNames
        #expect(names == [
            "nucleic-vmagent-fda.mobileconfig",
            "nucleic-suppress-notifications.mobileconfig",
        ])
        // A partial packaged set is skipped in favor of a complete source-tree set.
        try Data("partial".utf8).write(to: bundledMacVM.appendingPathComponent(names[0]))
        for name in names {
            try Data(name.utf8).write(to: sourcePolicies.appendingPathComponent(name))
        }
        let fallback = try #require(MacVMEngine.builtInMDMPolicyProfileURLs(
            bundleResourceURL: bundled, devRepoRoot: repo))
        #expect(fallback.map(\.lastPathComponent) == names)
        #expect(fallback.allSatisfy { $0.path.contains("macos-notification-fix") })

        // Once packaged assets are complete they take precedence.
        try Data("complete".utf8).write(to: bundledMacVM.appendingPathComponent(names[1]))
        let packaged = try #require(MacVMEngine.builtInMDMPolicyProfileURLs(
            bundleResourceURL: bundled, devRepoRoot: repo))
        #expect(packaged.map(\.lastPathComponent) == names)
        #expect(packaged.allSatisfy { $0.path.contains("/bundle/macvm/") })
    }

    // MARK: - Failed-provisioning wedge (base without the in-guest agent)

    /// Regression: an empty CLT catalog used to launch a graphical installer and ask the host to
    /// press Return repeatedly. The unattended path must retain the pipefail guard, then stop with an
    /// actionable error without creating a sentinel or launching any graphical installer.
    @Test func macOSGuestProvisionerFailsClosedForEmptyCLTCatalog() throws {
        let repoRoot = URL(fileURLWithPath: #filePath)
            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
        let provisioner = repoRoot.appendingPathComponent("scripts/provision-macos-guest.sh")
        let script = try String(contentsOf: provisioner, encoding: .utf8)
        #expect(script.contains("set -euo pipefail"))  // the hazard the guards exist for
        // CLT label lookup: no match must reach our explicit diagnostic, not die in the pipeline.
        #expect(script.contains("sort -V | tail -1 || true"))
        #expect(script.contains("Refusing to open the graphical xcode-select installer"))
        #expect(!script.contains("sudo xcode-select --install"))
        #expect(!script.contains("CLT_PROMPT"))
    }

    /// The launch staleness check must treat a base whose last pass failed as needing re-provisioning
    /// even when its recipe stamp matches — a stamp proves nothing about a pass that didn't land the
    /// control plane. macOS needs the toolchain AND the in-guest agent (exec/computer-use are
    /// vsock-only); Linux bakes its agent during the provision build, so `provisioned` is the signal.
    @Test func baseUsabilityRequiresTheControlPlaneAndMDMPolicy() {
        func status(
            provisioned: Bool, agent: Bool, mdm: Bool = false, profiles: Bool = false,
            grants: Bool = false
        ) -> MacVMBaseStatus {
            var s = MacVMBaseStatus()
            s.installed = true
            s.accountProvisioned = true
            s.provisioned = provisioned
            s.agentInstalled = agent
            s.mdmEnrolled = mdm
            s.profilesInstalled = profiles
            s.policyGrantsVerified = grants
            return s
        }
        // A Lane A (MDM) base is usable with enrollment + profiles…
        #expect(MacVMEngine.baseIsUsable(status(
            provisioned: true, agent: true, mdm: true, profiles: true), os: .macOS))
        #expect(!MacVMEngine.baseIsUsable(status(
            provisioned: true, agent: true, mdm: false, profiles: true), os: .macOS))
        #expect(!MacVMEngine.baseIsUsable(status(
            provisioned: true, agent: true, mdm: true, profiles: false), os: .macOS))
        // …and a Lane B base is usable with verified datastore grants and no MDM state at all.
        #expect(MacVMEngine.baseIsUsable(status(
            provisioned: true, agent: true, grants: true), os: .macOS))
        // Neither lane's policy landed → not usable.
        #expect(!MacVMEngine.baseIsUsable(status(provisioned: true, agent: true), os: .macOS))
        // The in-guest agent is still required regardless of lane.
        #expect(!MacVMEngine.baseIsUsable(status(
            provisioned: true, agent: false, mdm: true, profiles: true), os: .macOS))
        #expect(!MacVMEngine.baseIsUsable(status(
            provisioned: true, agent: false, grants: true), os: .macOS))
        #expect(MacVMEngine.baseIsUsable(status(provisioned: true, agent: false), os: .linux))
        #expect(!MacVMEngine.baseIsUsable(status(provisioned: false, agent: false), os: .linux))
        #expect(MacVMEngine.macOSProvisioningRecipe == 13)
    }

    /// Clone-time admission duplicates the current-recipe publication invariant: neither a stale
    /// base, an agentless base, nor one missing mandatory policy may produce a session clone.
    @Test func ensureBaseBundleRefusesAnIncompleteControlPlane() async throws {
        // A fresh defaults suite so a developer machine's `basePrebuiltPath` can't reroute the lookup.
        let suite = UserDefaults(suiteName: "macvm-base-\(UUID().uuidString)")!
        try await ContainerServiceSettings.withDefaults(suite) {
            let root = FileManager.default.temporaryDirectory
                .appendingPathComponent("macvm-base-\(UUID().uuidString)", isDirectory: true)
            defer { try? FileManager.default.removeItem(at: root) }
            let engine = MacVMEngine(storageRoot: root)
            let baseDir = root.appendingPathComponent("base", isDirectory: true)
            try FileManager.default.createDirectory(at: baseDir, withIntermediateDirectories: true)
            let bundle = MacVMBundle(root: baseDir)
            for artifact in [
                bundle.hardwareModelURL, bundle.machineIdentifierURL,
                bundle.auxiliaryStorageURL, bundle.diskImageURL,
            ] {
                try Data().write(to: artifact)
            }

            func writeStatus(
                agentInstalled: Bool, mdmReady: Bool,
                recipe: Int = MacVMEngine.macOSProvisioningRecipe
            ) throws {
                let json: [String: Any] = [
                    "installed": true, "accountProvisioned": true, "provisioned": true,
                    "agentInstalled": agentInstalled, "mdmEnrolled": mdmReady,
                    "profilesInstalled": mdmReady, "provisioningRecipe": recipe,
                ]
                try JSONSerialization.data(withJSONObject: json).write(to: bundle.metadataURL)
            }

            try writeStatus(agentInstalled: false, mdmReady: false)
            await #expect(throws: MacVMError.self) {
                _ = try await engine.ensureBaseBundle(for: .macOS)
            }
            try writeStatus(agentInstalled: true, mdmReady: false)
            await #expect(throws: MacVMError.self) {
                _ = try await engine.ensureBaseBundle(for: .macOS)
            }

            // Even a complete old control plane cannot race ahead of recipe-13 Xcode verification.
            try writeStatus(
                agentInstalled: true, mdmReady: true,
                recipe: MacVMEngine.macOSProvisioningRecipe - 1)
            try Data("persisted MDM identity fixture".utf8).write(to: bundle.mdmStateURL)
            await #expect(throws: MacVMError.self) {
                _ = try await engine.ensureBaseBundle(for: .macOS)
            }

            try writeStatus(agentInstalled: true, mdmReady: true)
            // This pass now fails only because its host MDM identity fixture was removed.
            try FileManager.default.removeItem(at: bundle.mdmStateURL)
            await #expect(throws: MacVMError.self) {
                _ = try await engine.ensureBaseBundle(for: .macOS)
            }
            try Data("persisted MDM identity fixture".utf8).write(to: bundle.mdmStateURL)
            let resolved = try await engine.ensureBaseBundle(for: .macOS)
            #expect(resolved.root == baseDir)
        }
    }

    // MARK: - Registry change stream (plan item 7, docs/MAIN_THREAD_PERFORMANCE_PLAN.md)

    /// Every `changes()` subscriber is primed with the current registry snapshot on subscription —
    /// the contract that lets consumers replace their initial `runningVMs()` fetch with a bare
    /// `for await`. Booting a guest needs Apple silicon + a base, so this pins the reachable half:
    /// a fresh engine primes each subscriber, independently, with the (empty) current state.
    @Test func registryChangeStreamPrimesEachSubscriberWithCurrentSnapshot() async {
        let root = FileManager.default.temporaryDirectory
            .appendingPathComponent("macvm-changes-\(UUID().uuidString)", isDirectory: true)
        defer { try? FileManager.default.removeItem(at: root) }
        let engine = MacVMEngine(storageRoot: root)
        var first = await engine.changes().makeAsyncIterator()
        var second = await engine.changes().makeAsyncIterator()
        #expect(await first.next() == [])
        #expect(await second.next() == [])
        #expect(await engine.runningVMs() == [])
    }

    // MARK: - Force cancel / force delete

    /// A force-cancelled pass must not be able to write `bundle.json` back as it unwinds — otherwise the
    /// bundle the operator just deleted reappears half-built and the panel reports it as installed.
    /// The same flag must be cleared by the next deliberate pass, or every later build would silently
    /// fail to record its own progress.
    @Test func forceCancelStopsBundleWritesUntilTheNextDeliberatePass() async throws {
        let root = FileManager.default.temporaryDirectory
            .appendingPathComponent("macvm-forcecancel-\(UUID().uuidString)", isDirectory: true)
        defer { try? FileManager.default.removeItem(at: root) }
        let engine = MacVMEngine(storageRoot: root)
        let baseDir = root.appendingPathComponent("base", isDirectory: true)
        try FileManager.default.createDirectory(at: baseDir, withIntermediateDirectories: true)
        let bundle = MacVMBundle(root: baseDir)

        var status = MacVMBaseStatus()
        status.installed = true
        await engine.writeBaseStatus(bundle, status)
        #expect(await engine.readBaseStatus(bundle).installed, "a normal pass records its status")

        // Force-cancel, then simulate the unwinding pass trying to write again after a delete.
        let summary = await engine.forceCancelBaseWork()
        #expect(summary.contains("Nothing was holding"), "fresh engine holds nothing: \(summary)")
        try FileManager.default.removeItem(at: bundle.metadataURL)
        await engine.writeBaseStatus(bundle, status)
        #expect(
            !FileManager.default.fileExists(atPath: bundle.metadataURL.path),
            "a cancelled pass must not resurrect bundle.json")

        // A new deliberate pass clears the latch. `buildBaseImage` is the real clearer, but it needs a
        // VM; assert the invariant at the flag level so a future pass that forgets to reset it is caught.
        await engine.clearBaseWorkCancelledForTesting()
        await engine.writeBaseStatus(bundle, status)
        #expect(
            await engine.readBaseStatus(bundle).installed,
            "the next deliberate pass must be able to record status again")
    }

    /// Force delete must not consult `baseIsBusy` — that guard is exactly what left a wedged
    /// provisioning run with no way out but quitting the app.
    @Test func forceDeleteRemovesTheBundleAndClearsProgress() async throws {
        let suite = UserDefaults(suiteName: "macvm-forcedelete-\(UUID().uuidString)")!
        try await ContainerServiceSettings.withDefaults(suite) {
            let root = FileManager.default.temporaryDirectory
                .appendingPathComponent("macvm-forcedelete-\(UUID().uuidString)", isDirectory: true)
            defer { try? FileManager.default.removeItem(at: root) }
            let engine = MacVMEngine(storageRoot: root)
            let baseDir = root.appendingPathComponent("base", isDirectory: true)
            try FileManager.default.createDirectory(at: baseDir, withIntermediateDirectories: true)
            try Data("x".utf8).write(to: baseDir.appendingPathComponent("Disk.img"))

            try await engine.deleteBaseImage(includingRestoreImages: false, force: true)
            #expect(!FileManager.default.fileExists(atPath: baseDir.path), "the bundle is gone")
            #expect(await engine.currentBaseProgress() == nil, "progress is cleared")
        }
    }
}
