import AppKit import Darwin import Foundation import RealityDriverSupport struct RealityLaneDecision: Equatable, Sendable { let stopsLane: Bool static func afterScenario(failures: [any Error], cleanupFailed: Bool) -> Self { Self( stopsLane: cleanupFailed || failures.contains { error in String(describing: error).contains("Safety stop:") }) } } struct RealityResult: Codable, Sendable { enum Status: String, Codable { case pass, fail, skip case unsupportedHost = "unsupported-host" } let scenario: String let feature: String let status: Status let evidence: String let artifactPath: String var input: [RealityInputAudit] = [] } @MainActor final class RunSignals { private let sources: [any DispatchSourceSignal] private(set) var interrupted = false init() { sources = [SIGINT, SIGTERM, SIGHUP].map { number in signal(number, SIG_IGN) return DispatchSource.makeSignalSource(signal: number, queue: .main) } for source in sources { source.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.interrupted = true } } source.resume() } } } @MainActor struct RealityStorage { let token: UUID let directory: URL private let inode: UInt64 private let device: Int32 nonisolated static let files = [ "parcel.toml", "workspace-state.json", "minimum-sizes.json", "room-reminders.json", "rule-space-moves.json", "activity.json", "setups.json", "restart-failure.json", ] init(parent: URL) throws { try Self.requireScratchPath(parent.standardizedFileURL) let parent = parent.standardizedFileURL.resolvingSymlinksInPath() try Self.requireScratchPath(parent) token = UUID() directory = parent.appendingPathComponent("parcel-reality-\(token.uuidString)", isDirectory: true) try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) let metadata = try Self.metadata(directory) inode = metadata.st_ino device = metadata.st_dev try validate() } static func requireScratchPath(_ path: URL) throws { guard path.isFileURL, path.path.hasPrefix("/"), !path.pathComponents.contains("Application Support"), !path.pathComponents.contains("Preferences"), !path.pathComponents.contains(".config") else { throw RealityError("Safety stop: reality storage refuses real application state/configuration paths") } } func validate() throws { try Self.requireScratchPath(directory) guard directory.resolvingSymlinksInPath() == directory, directory.lastPathComponent == "parcel-reality-\(token.uuidString)" else { throw RealityError("Safety stop: reality storage directory is redirected") } let value = try Self.metadata(directory) guard value.st_mode & S_IFMT == S_IFDIR, value.st_uid == getuid(), value.st_mode & 0o7777 == 0o700, value.st_ino == inode, value.st_dev == device else { throw RealityError("Safety stop: reality storage directory identity or permissions changed") } let entries = Set(try FileManager.default.contentsOfDirectory(atPath: directory.path)) for name in Self.files where entries.contains(name) { let file = fileURL(name) let value = try Self.metadata(file) guard file.resolvingSymlinksInPath() == file, value.st_mode & S_IFMT == S_IFREG, value.st_uid == getuid(), value.st_nlink == 1 else { throw RealityError("Safety stop: reality state must be an owned regular unshared file") } } } func fileURL(_ name: String) -> URL { precondition(Self.files.contains(name)) return directory.appendingPathComponent(name) } func successor() throws -> Self { try validate() let next = try Self(parent: directory.deletingLastPathComponent()) for name in Self.files where FileManager.default.fileExists(atPath: fileURL(name).path) { try Data(contentsOf: fileURL(name)).write(to: next.fileURL(name), options: .atomic) } let previous = try preferences().persistentDomain(forName: preferencesDomain) let defaults = try next.preferences() guard defaults.persistentDomain(forName: next.preferencesDomain) == nil else { throw RealityError("Safety stop: replacement preferences already exist") } if let previous { defaults.setPersistentDomain(previous, forName: next.preferencesDomain) } guard defaults.synchronize() else { throw RealityError("Replacement preferences could not be synchronized") } try validate() try next.validate() return next } private static func metadata(_ path: URL) throws -> stat { var value = stat() guard path.path.withCString({ lstat($0, &value) }) == 0 else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } return value } struct Receipt: Codable { let token: UUID let directory: URL let config: URL let preferencesDomain: String } var receipt: Receipt { Receipt( token: token, directory: directory, config: fileURL("parcel.toml"), preferencesDomain: preferencesDomain) } var preferencesDomain: String { "dev.vinnymac.parcel.reality.\(token.uuidString)" } var arguments: [String] { ["--reality-isolated"] } var environment: [String: String] { [ "PARCEL_REALITY": "1", "PARCEL_REALITY_ISOLATION_TOKEN": token.uuidString, "PARCEL_REALITY_STATE_DIRECTORY": directory.path, ] } func preferences() throws -> UserDefaults { try validate() guard let defaults = UserDefaults(suiteName: preferencesDomain) else { throw RealityError("Cannot open the owned reality preference domain") } return defaults } func prepare(firstRun: Bool = false) throws { let defaults = try preferences() guard defaults.persistentDomain(forName: preferencesDomain) == nil else { throw RealityError("Owned reality preferences already exist; refusing to overwrite them") } if !firstRun { defaults.setPersistentDomain( ["automaticTilingEnabled": true, "onboardingCompleted": true, "guidedTour.v2.completed": true], forName: preferencesDomain) } guard defaults.synchronize() else { throw RealityError("Owned reality preferences could not be synchronized") } } func removePreferences() throws { let defaults = try preferences() defaults.removePersistentDomain(forName: preferencesDomain) guard defaults.synchronize(), defaults.persistentDomain(forName: preferencesDomain) == nil else { throw RealityError("Owned reality preferences could not be removed") } } } @main struct RealityMain { @MainActor static func main() async { do { exit(try await run(arguments: Array(CommandLine.arguments.dropFirst()))) } catch { FileHandle.standardError.write(Data("Reality harness failed: \(error)\n".utf8)) exit(1) } } @MainActor static func run(arguments: [String]) async throws -> Int32 { if arguments == ["--list"] { for scenario in RealityScenario.all { print("\(scenario.name): \(scenario.feature)") } return 0 } let environment = ProcessInfo.processInfo.environment guard environment["PARCEL_REALITY"] == "1" else { print("Skipped reality: set PARCEL_REALITY=1. No apps launched.") return 0 } let lock = environment["PARCEL_SCREEN_LOCK_PATH"] ?? "/tmp/parcel-screen.lock" let owner = try String(contentsOfFile: "\(lock)/owner", encoding: .utf8) guard owner.split(separator: " ").last.flatMap({ Int32($0.trimmingCharacters(in: .whitespacesAndNewlines)) }) == getppid() else { throw RealityError( "Reality must be launched by Scripts/screen-lock.sh; lock owner is not the parent process") } var preflightOnly = false var filter: String? var report: URL? var recovery: URL? var recoveryKey: UInt16? var index = 0 while index < arguments.count { if arguments[index] == "--preflight-only" { preflightOnly = true index += 1 continue } guard index + 1 < arguments.count else { throw RealityError("Expected value for \(arguments[index])") } switch arguments[index] { case "--scenario": filter = arguments[index + 1] case "--report": report = URL(fileURLWithPath: arguments[index + 1]) case "--recover-owned": recovery = URL(fileURLWithPath: arguments[index + 1]) case "--recover-key": guard let key = UInt16(arguments[index + 1]) else { throw RealityError("Expected a numeric virtual key") } try DriverCommand.recoverKey(pid: 1, windowID: 1, virtualKey: key).validate() recoveryKey = key default: throw RealityError("Unknown argument: \(arguments[index])") } index += 2 } guard (recovery == nil && recoveryKey == nil) || arguments.count == 2 else { throw RealityError("Recovery must be used alone") } if filter == "real-desktop-first-run" { _ = try RealDesktopOptions( environment: environment, fixtureSentinel: FileManager.default.fileExists(atPath: "/tmp/parcel-m3-free") ) } let scenarios = RealityScenario.selected(named: filter) guard !scenarios.isEmpty else { throw RealityError("Unknown scenario: \(filter ?? "")") } try TabViewConsoleSession.requireUnlockedConsole() guard let path = environment["PARCEL_APP_PATH"] else { throw RealityError("Missing PARCEL_APP_PATH") } let appURL = URL(fileURLWithPath: path) guard FileManager.default.isExecutableFile(atPath: appURL.appendingPathComponent("Contents/MacOS/Parcel").path) else { throw RealityError("The real Parcel bundle is missing") } try rejectRunningInstances( NSRunningApplication.runningApplications(withBundleIdentifier: "dev.vinnymac.parcel").count) let settingsBaseline = try AccessibilitySettingsSnapshot.capture() let preflightDriver = RealityDriver(appURL: appURL) var laneInputBaseline: DriverInputState? do { try await preflightDriver.preflight() if let recovery { try await recoverOwnedFinder(directory: recovery, driver: preflightDriver) } if let recoveryKey { try await recoverHeldKey(recoveryKey, driver: preflightDriver) } if recovery == nil, recoveryKey == nil, !preflightOnly { _ = try await preflightDriver.send(.releaseOwnedKeys) let baseline = try await preflightDriver.inputState() try baseline.requireNeutralBaseline() try DriverInputState.capture().requireRestored(to: baseline) laneInputBaseline = baseline } } catch { let preflightError = error do { try await preflightDriver.stop() } catch { throw RealityError("\(preflightError) Driver teardown failed: \(error)") } throw preflightError } try await preflightDriver.stop() if recovery != nil { print("Closed exactly the ledger-owned Finder window; product state was not reset.") return 0 } if recoveryKey != nil { return 0 } if preflightOnly { print("Reality driver Accessibility and HID preflight passed; no test windows opened.") return 0 } guard let laneInputBaseline else { throw RealityError("Safety stop: lane input baseline is unavailable") } try DriverInputState.capture().requireRestored(to: laneInputBaseline) guard let screen = NSScreen.screens.first else { throw RealityError("No real display is available") } let visible = ScreenRect( x: screen.visibleFrame.minX, y: screen.frame.maxY - screen.visibleFrame.maxY, width: screen.visibleFrame.width, height: screen.visibleFrame.height) let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "-") let root = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) .appendingPathComponent("build/reality/\(stamp)-\(UUID().uuidString.prefix(8))") try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) try encodeJSON(visible, to: root.appendingPathComponent("visible-frame.json")) try encodeJSON(laneInputBaseline, to: root.appendingPathComponent("input-baseline.json")) try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: root.path) let signals = RunSignals() try rejectRunningInstances( NSRunningApplication.runningApplications(withBundleIdentifier: "dev.vinnymac.parcel").count) var results: [RealityResult] = [] var terminalError: (any Error)? var settingsGuard = AccessibilitySettingsGuard(baseline: settingsBaseline) @MainActor func checkSettings(stage: String) throws { settingsGuard.observe(try AccessibilitySettingsSnapshot.capture(), stage: stage) try encodeJSON(settingsGuard, to: root.appendingPathComponent("accessibility-settings.json")) try settingsGuard.requireNoDrift() } func writeReport() throws { try encodeJSON(results, to: root.appendingPathComponent("results.json")) let reportData = Data(markdown(results, root: root.path, settings: settingsGuard).utf8) try reportData.write(to: root.appendingPathComponent("report.md"), options: .atomic) if let report { try reportData.write(to: report, options: .atomic) } } try encodeJSON(settingsGuard, to: root.appendingPathComponent("accessibility-settings.json")) try writeReport() do { for scenario in scenarios { try checkSettings(stage: "Before \(scenario.name)") try TabViewConsoleSession.requireUnlockedConsole() if signals.interrupted { throw RealityError("Interrupted; stopping after owned-window cleanup") } try DriverInputState.capture().requireRestored(to: laneInputBaseline) let session = try RealitySession( directory: root.appendingPathComponent(scenario.name), appURL: appURL, visible: visible, inputBaseline: laneInputBaseline) var status: RealityResult.Status = .pass var evidence = "Real window-server observations met every recorded expectation" var failures: [any Error] = [] var cleanupFailed = false do { if scenario.name == "real-desktop-first-run" { try await checkRealDesktopFirstRun(session, interrupted: { signals.interrupted }) } else { try await scenario.run(session) } } catch let error as RealityUnsupportedHostRequirement { status = scenario.skipStatus( explicitlyRequested: filter != nil, unsupportedHostRequirement: error.requirement) evidence = error.description if status == .fail { failures.append(error) } } catch let error as RealitySkip { status = scenario.skipStatus(explicitlyRequested: filter != nil) switch status { case .fail: evidence = "Explicitly requested scenario could not run: \(error)" case .unsupportedHost: evidence = "Unsupported host requirement: \(error). No product pass claimed." case .pass, .skip: evidence = error.description } } catch { status = .fail; evidence = String(describing: error) failures.append(error) } do { try checkSettings(stage: "After \(scenario.name)") } catch { status = .fail; evidence += "; \(error)" failures.append(error) } do { if scenario.name != "real-desktop-first-run" { try await session.artifacts() } } catch { status = .fail; evidence += "; artifact capture failed: \(error)" failures.append(error) } do { let frames = try session.readFrames(session.apps.windows) evidence += "; real=\(frames); expected=\(session.expectations.joined(separator: "; "))" } catch { status = .fail; evidence += "; real-frame read failed: \(error)" failures.append(error) } do { try await session.cleanup() } catch { status = .fail evidence += "; cleanup failed: \(error)" cleanupFailed = true terminalError = error } do { try checkSettings(stage: "After \(scenario.name) cleanup") } catch { status = .fail; evidence += "; \(error)" failures.append(error) } if status == .fail, let directory = session.realDesktopEvidence { do { var desktopReport = try JSONDecoder().decode( RealDesktopReport.self, from: Data(contentsOf: directory.appendingPathComponent("report.json"))) if cleanupFailed || desktopReport.failures.isEmpty { desktopReport.failures.append(evidence) try desktopReport.write(to: directory) } } catch { evidence += "; final desktop report failed: \(error)" } } let result = RealityResult( scenario: scenario.name, feature: scenario.feature, status: status, evidence: evidence, artifactPath: session.directory.path, input: session.driver.inputAudit) results.append(result) print("\(status.rawValue.uppercased()) \(scenario.name): \(evidence)") let safetyStop = RealityLaneDecision.afterScenario( failures: failures, cleanupFailed: cleanupFailed ).stopsLane if safetyStop { for pending in scenarios.dropFirst(results.count) { results.append( RealityResult( scenario: pending.name, feature: pending.feature, status: .skip, evidence: "Not run after \(scenario.name) safety/cleanup failure; no stimulus or CG frame proof produced", artifactPath: root.appendingPathComponent(pending.name).path)) } } try writeReport() if safetyStop { break } } } catch { terminalError = error } var laneInputBalance = RealityInputBalance(baseline: laneInputBaseline) laneInputBalance.observe(DriverInputState.capture(), stage: "Lane end") var inputFailures: [String] = [] do { try laneInputBalance.requireRestored() } catch { inputFailures.append(String(describing: error)) } do { try encodeJSON(laneInputBalance, to: root.appendingPathComponent("input-restoration.json")) } catch { inputFailures.append("Lane input restoration receipt failed: \(error)") } if !inputFailures.isEmpty { terminalError = RealityError( ((terminalError.map { [String(describing: $0)] } ?? []) + inputFailures).joined(separator: "; ")) } do { try checkSettings(stage: "Lane end") } catch { terminalError = RealityError( ((terminalError.map { [String(describing: $0)] } ?? []) + [String(describing: error)]) .joined(separator: "; ")) } if let terminalError { for pending in scenarios.dropFirst(results.count) { results.append( RealityResult( scenario: pending.name, feature: pending.feature, status: .skip, evidence: "Not run after lane safety failure: \(terminalError); no product proof produced", artifactPath: root.appendingPathComponent(pending.name).path)) } } try writeReport() withExtendedLifetime(signals) {} print("Reality artifacts: \(root.path)") if let terminalError { throw terminalError } return results.contains { $0.status == .fail } ? 1 : 0 } static func rejectRunningInstances(_ count: Int) throws { guard count == 0 else { throw RealityError("Quit running Parcel before starting a reality run.") } } static func markdown( _ results: [RealityResult], root: String, settings: AccessibilitySettingsGuard? = nil ) -> String { var text = "# Reality run\n\nArtifacts: `\(root)`\n\n" let pass = results.filter { $0.status == .pass }.count let fail = results.filter { $0.status == .fail }.count let skip = results.filter { $0.status == .skip }.count let unsupported = results.filter { $0.status == .unsupportedHost }.count text += "\(pass) pass, \(fail) fail, \(skip) skip, \(unsupported) unsupported-host. Failures are evidence, not product fixes.\n\n" if let settings { text += settings.markdown } text += "| Feature | Pass/fail | Evidence |\n| --- | --- | --- |\n" for result in results { let evidence = result.evidence.replacingOccurrences(of: "|", with: "\\|").replacingOccurrences( of: "\n", with: " ") text += "| \(result.feature) (`\(result.scenario)`) | \(result.status.rawValue) | \(evidence). Artifact: `\(result.artifactPath)`; compare `real-frames.json`, `expected.json`, and `observations.json`. |\n" } text += "\n## Input audit\n\n" for result in results { text += "### \(result.scenario) (\(result.status.rawValue))\n\n" if result.input.isEmpty { text += "No keys or drags sent.\n\n" } for input in result.input { text += "- \(input.description)\n" } } text += """ ## Harness limits Frames come only from numeric CGWindowList observations and AppKit visible display bounds. Parcel queries and diagnostics are evidence, never the oracle. Focus uses independent frontmost-app and window-server order observations. Terminal frames may undershoot by one independently measured resize increment, but may not overflow the tile at all. Parcel directly spawns its embedded reality helper from a host-only debug instance launched through Launch Services. The helper inherits Parcel's existing Accessibility and HID access; peer PID and parent PID are verified before use. No separate helper grant is needed or requested. The host forwards only the private socket path and never starts the product runtime. Automation is never used. Documents open with open -n -a and Finder folders with open. Pre-existing apps are ignored except unique-token owned documents; singleton apps skip when already running. Finder is never quit. No Peek and Clean Space record all-layer overlay presence, level, bounds, and removal. Those signals alone do not prove the contents of a shared overlay panel. Pixel checks need an existing Screen Recording grant for the responsible Parcel bundle plus PARCEL_REALITY_SCREEN_CAPTURE=1. Only the helper calls ScreenCaptureKit; frame checks and the harness need no Screen Recording. No privacy grant is requested. Downstream scenarios that fail the initial tile prerequisite have not proved their feature broken: their action was blocked by that prerequisite. Spaces require enabled Mission Control chords and driver-owned desktop setup; displays require at least two connected displays. Relaunch memory reopens the same owned documents with changed CG IDs. Only created windows and processes launched by this run are closed. Scenario-local verification failures clean up and continue; unknown external state, unowned movement, input leaks, and cleanup failures stop the lane. One lane-start input baseline is retained in input-baseline.json. Scenario input-restoration.json records state before key release, after release, and after teardown; the lane receipt checks final restoration. Leaks remain failures even if cleanup balances them. Caps Lock is preserved. The run refuses to start while Parcel is already running. Each scenario and explicit harness relaunch uses a distinct owned UUID preference suite, config path, and state directory; only prior owned state is copied. Product language restart retains its current owned scope and isolated argument. Production Parcel configuration, Application Support files, and preference domain are never backed up, reset, or restored. storage-launch-*.json records scopes; storage-cleanup.json verifies owned-suite removal after the owned processes stop. No product code was repaired. """ return text + "\n" } }