import AppKit import Foundation struct RealityRecoveryHooks: Sendable { enum Kind: Equatable, Sendable { case missedDestroy, simulatedSleep, tourRollback } let kind: Kind let token: String init(kind: Kind, token: String) throws { guard !token.isEmpty, token.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 }) else { throw RealityError("Recovery hooks require a nonempty isolated alphanumeric token") } self.kind = kind self.token = token } var environment: [String: String] { var result = ["PARCEL_E2E": "1", "PARCEL_E2E_REAL_APPS": "1", "PARCEL_E2E_TOKEN": token] if kind == .missedDestroy { result["PARCEL_E2E_DROP_ONE_DESTROYED"] = "1" } return result } @MainActor func requireWakeReceipt(in directory: URL) async throws { let url = directory.appendingPathComponent("wake-receipt.json") let deadline = ContinuousClock.now.advanced(by: .seconds(2)) while !FileManager.default.fileExists(atPath: url.path), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(30)) } guard FileManager.default.fileExists(atPath: url.path) else { throw RealityError("Token-scoped wake hook produced no product delivery receipt") } let receipt = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: url)) guard receipt == ["token": token, "event": "wake"] else { throw RealityError("Wake receipt does not match this isolated scenario token") } } var wakeNotification: Notification.Name { Notification.Name("dev.vinnymac.parcel.e2e.\(token).wake") } var notification: Notification.Name { let event = kind == .missedDestroy ? "wake" : "sleep" return Notification.Name("dev.vinnymac.parcel.e2e.\(token).\(event)") } } @MainActor func coverageLaunchEnvironment(_ inherited: [String: String], hooks: RealityRecoveryHooks?) -> [String: String] { var result = inherited.filter { !$0.key.hasPrefix("PARCEL_") } result["PARCEL_E2E"] = "0" if let hooks { result.merge(hooks.environment) { _, isolated in isolated } } return result } @MainActor func checkPhantomGap(_ session: RealitySession) async throws { let hooks = try RealityRecoveryHooks(kind: .missedDestroy, token: UUID().uuidString) try session.configure() let owned = try await session.startingWindows([.textEdit, .textEdit, .textEdit]) try await session.start(recoveryHooks: hooks, droppedDestroyWindow: owned[2]) try await session.tiles(owned) try await session.apps.focus(owned[0]) try encodeJSON( try session.readFrames(owned), to: session.directory.appendingPathComponent("phantom-before-close-frames.json")) let closed = owned[2] let receipt = try session.apps.validatedLaunchReceipt(for: closed) try await session.apps.requestNativeClose(closed) try await session.expect("The exact native document CG ID disappears while its owned app remains alive") { !$0.contains { $0.id == closed.id } && NSRunningApplication(processIdentifier: receipt.pid)?.isTerminated == false } _ = try session.apps.validatedLaunchReceipt(for: closed) let receiptURL = session.directory.appendingPathComponent("dropped-destroy-receipt.json") let deadline = ContinuousClock.now.advanced(by: .seconds(2)) while !FileManager.default.fileExists(atPath: receiptURL.path), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(30)) } guard FileManager.default.fileExists(atPath: receiptURL.path) else { throw RealityError("Armed dropped-destroy hook produced no product receipt") } let dropped = try JSONDecoder().decode(DroppedDestroyReceipt.self, from: Data(contentsOf: receiptURL)) try dropped.requireMatch(token: hooks.token, window: closed) try session.apps.recordNativeClosure(closed) let stale = try await coverageWindowIDs(session) try encodeJSON(stale, to: session.directory.appendingPathComponent("phantom-stale-window-ids.json")) let survivors = Array(owned.prefix(2)) let gaps = try session.configuredLayout().gaps if !stale.contains(closed.id) { try await session.expect("Activity repairs the dropped destruction with exact real columns before wake") { let frames = try FrameOracle.frames($0, ids: survivors.map(\.id)) return !$0.contains { $0.id == closed.id } && CoverageOracle.repairedGap(frames, visible: session.visible, gaps: gaps) } } try encodeJSON( ["recovery": stale.contains(closed.id) ? "wake-required" : "activity-before-wake"], to: session.directory.appendingPathComponent("phantom-recovery-path.json")) DistributedNotificationCenter.default().postNotificationName( hooks.notification, object: nil, userInfo: nil, deliverImmediately: true) try await hooks.requireWakeReceipt(in: session.directory) try await session.expect("Acknowledged wake completes or preserves exact recovery of the dropped destruction") { let frames = try FrameOracle.frames($0, ids: survivors.map(\.id)) return !$0.contains { $0.id == closed.id } && CoverageOracle.repairedGap(frames, visible: session.visible, gaps: gaps) } let reconciled = try await coverageWindowIDs(session) guard !reconciled.contains(closed.id) else { throw RealityError("Reconciliation retained the vanished CG window ID") } try encodeJSON(reconciled, to: session.directory.appendingPathComponent("phantom-reconciled-window-ids.json")) } @MainActor private func coverageWindowIDs(_ session: RealitySession) async throws -> [UInt32] { struct Row: Decodable { let id: UInt32 } let result = try await session.cli(["query", "--json", "windows"]) guard result.status == 0 else { throw RealityError("Phantom precondition query failed: \(result.errors)") } return try JSONDecoder().decode([Row].self, from: Data(result.output.utf8)).map(\.id) } struct DroppedDestroyReceipt: Codable, Sendable { let token: String let pid: Int32 let windowID: UInt32 func requireMatch(token: String, window: OwnedWindow) throws { guard self.token == token, pid == window.pid, windowID == window.id else { throw RealityError("Dropped-destroy receipt does not match the armed token and owned PID/CG ID") } } } struct PrivacyLifecycleReceipt: Codable, Sendable { let backdropCount: Int let panelCount: Int enum CodingKeys: String, CodingKey { case backdropCount = "clean_space_backdrop_count" case panelCount = "privacy_panel_count" } } @MainActor func checkCleanSpaceSimulatedSleep(_ session: RealitySession) async throws { let capture = ProcessInfo.processInfo.environment["PARCEL_REALITY_SCREEN_CAPTURE"] == "1" let hooks = try RealityRecoveryHooks(kind: .simulatedSleep, token: UUID().uuidString) try session.configure() let owned = try await session.startingWindows([.textEdit, .textEdit]) try await session.start(recoveryHooks: hooks) try await session.tiles(owned) try await session.apps.focus(owned[0]) let before = try session.readFrames(owned) let pixels = capture ? try await captureRealityPixels(session, stage: "sleep-before") : nil try await session.command("clean-space-toggle") try await session.expect("Clean Space retains both independently observed native tile frames") { CoverageOracle.unchanged(try FrameOracle.frames($0, ids: owned.map(\.id)), baseline: before) } if let pixels { let enabled = try await captureRealityPixels(session, stage: "sleep-enabled") guard try VisualOracle.graphite(enabled.metrics(in: before[1].inset(40))), try enabled.difference(from: pixels, in: before[0].inset(40)) < 0.03 else { throw RealityError("Clean Space pixels did not establish a protected document and opaque backdrop") } } guard let pid = session.parcel?.processIdentifier else { throw RealityError("Missing tested Parcel identity") } let display = try RealityDisplays.primaryFrame() try await session.expect("Clean Space creates opaque CG overlay surfaces at exact display bounds") { try CoverageOracle.unchanged(FrameOracle.frames($0, ids: owned.map(\.id)), baseline: before) && !VisualOracle.overlayWindows(try FrameOracle.read(allLayers: true), pid: pid, display: display).isEmpty } let overlays = VisualOracle.overlayWindows(try FrameOracle.read(allLayers: true), pid: pid, display: display) guard !overlays.isEmpty else { throw RealityError("Clean Space has no CG-observed display overlay") } let enabledIDs = Set(overlays.map(\.id)) try encodeJSON(overlays, to: session.directory.appendingPathComponent("sleep-enabled-overlays.json")) let active = try await privacyLifecycle(session, stage: "enabled") guard active.backdropCount > 0 else { throw RealityError("Clean Space did not report an active backdrop") } DistributedNotificationCenter.default().postNotificationName( hooks.notification, object: nil, userInfo: nil, deliverImmediately: true) try await session.expect("Simulated sleep removes the exact CG backdrop surfaces without moving native windows") { try !FrameOracle.read(allLayers: true).contains { enabledIDs.contains($0.id) && $0.onscreen } && CoverageOracle.unchanged(try FrameOracle.frames($0, ids: owned.map(\.id)), baseline: before) } let suspended = try await privacyLifecycle(session, stage: "suspended") guard suspended.backdropCount == 0, suspended.panelCount == 0 else { throw RealityError("Simulated sleep retained privacy panels or backdrops") } if let pixels { let restored = try await captureRealityPixels(session, stage: "sleep-restored") for frame in before { guard try restored.difference(from: pixels, in: frame.inset(40)) < 0.03 else { throw RealityError("Simulated sleep did not restore native document pixels") } } } DistributedNotificationCenter.default().postNotificationName( hooks.wakeNotification, object: nil, userInfo: nil, deliverImmediately: true) try await hooks.requireWakeReceipt(in: session.directory) try await session.expect("Wake keeps Clean Space off until explicitly re-enabled, with native frames intact") { try VisualOracle.overlayWindows(FrameOracle.read(allLayers: true), pid: pid, display: display).isEmpty && CoverageOracle.unchanged(try FrameOracle.frames($0, ids: owned.map(\.id)), baseline: before) } let awake = try await privacyLifecycle(session, stage: "awake-kept-off") guard awake.backdropCount == 0, awake.panelCount == 0 else { throw RealityError("Wake unexpectedly restored suspended privacy surfaces") } try await requireCoverageFramesStay( session, owned: owned, baseline: before, evidence: "wake-clean-space-stays-off") try await session.command("clean-space-toggle") try await session.expect("After wake, explicit Clean Space re-enable recreates display-bounded CG surfaces") { try !VisualOracle.overlayWindows(FrameOracle.read(allLayers: true), pid: pid, display: display).isEmpty && CoverageOracle.unchanged(try FrameOracle.frames($0, ids: owned.map(\.id)), baseline: before) } try encodeJSON( VisualOracle.overlayWindows(try FrameOracle.read(allLayers: true), pid: pid, display: display), to: session.directory.appendingPathComponent("wake-reenabled-overlays.json")) let reenabled = try await privacyLifecycle(session, stage: "wake-reenabled") guard reenabled.backdropCount > 0 else { throw RealityError("Wake left Clean Space unable to recreate a backdrop") } session.recordExpectation( "Token sleep/wake verified CG surfaces, display bounds and kept-off recovery; pixels optional, no physical sleep requested" ) } @MainActor private func privacyLifecycle(_ session: RealitySession, stage: String) async throws -> PrivacyLifecycleReceipt { let result = try await session.cli(["query", "--json", "config"]) guard result.status == 0 else { throw RealityError("Privacy lifecycle query failed: \(result.errors)") } let receipt = try JSONDecoder().decode(PrivacyLifecycleReceipt.self, from: Data(result.output.utf8)) try encodeJSON(receipt, to: session.directory.appendingPathComponent("sleep-\(stage)-privacy.json")) return receipt }