// // EngineGate.swift // Museion // // Created by Alexander Kucera on 03.09.26. // import Foundation import Observation /// One completed discovery+health check of the Engine (tickets #35/#36/#39). nonisolated enum EngineCheckResult: Equatable, Sendable { case pass(version: String, binaryPath: String) case fail(firstProbePath: String, stderrExcerpt: String) } /// Synchronous, nonisolated probe machinery — the unit-test seam. /// /// Runs the documented probe order (ticket #36), versions the winner (ticket #35), /// then wholesale-replaces state.json (ticket #39). Concrete enum + parameters; /// no protocols, no globals. nonisolated enum EngineProbe { /// Documented probe order (ticket #36); ~ is expanded at use. static let defaultProbePaths = [ "~/.local/bin/hermes", "~/.local/bin/hermes-acp", "~/.hermes/hermes-agent/venv/bin/hermes", "/opt/homebrew/bin/hermes", "/usr/local/bin/hermes", "/usr/local/lib/hermes-agent/venv/bin/hermes", ] /// Run discovery + health + version synchronously and record state.json. /// - Parameters: /// - probePaths: candidates in priority order (tests pass fakes). /// - shellFallback: run the `zsh -l -c 'command -v hermes'` last resort; tests pass `false`. /// - timeout: seconds before a hung `acp --check` is killed and treated as fail. /// - appSupportDir: directory for state.json; default the real Application Support. static func perform( probePaths: [String] = defaultProbePaths, shellFallback: Bool = true, timeout: TimeInterval = 5, appSupportDir: String? = nil, ) -> EngineCheckResult { let candidates = probePaths.map { ($0 as NSString).expandingTildeInPath } // ponytail: firstProbePath is the first path probed — first candidate, or the first // absolute probe when nothing exists (ticket #39 not-found case). let firstProbePath = candidates.first ?? "" var found: String? var stderrExcerpt = "" var sawFailure = false for candidate in candidates { let run = execute([candidate, "acp", "--check"], timeout: timeout) if run.exitCode == 0 { found = candidate break } // #36: all-fail reports the first (highest-priority) candidate's stderr. if !sawFailure { sawFailure = true stderrExcerpt = run.stderr } } if found == nil, shellFallback { let path = execute(["/bin/zsh", "-l", "-c", "command -v hermes"], timeout: 10) .stdout.trimmingCharacters(in: .whitespacesAndNewlines) if !path.isEmpty, execute([path, "acp", "--check"], timeout: timeout).exitCode == 0 { found = path } } let result: EngineCheckResult if let binaryPath = found { // A failing `acp --version` still passes the gate; "unknown" keeps the copy honest. let versionRun = execute([binaryPath, "acp", "--version"], timeout: 10) let version = versionRun.exitCode == 0 ? versionRun.stdout.trimmingCharacters(in: .whitespacesAndNewlines) : "unknown" result = .pass(version: version, binaryPath: binaryPath) } else { result = .fail(firstProbePath: firstProbePath, stderrExcerpt: stderrExcerpt) } writeState(result, appSupportDir: appSupportDir) return result } /// Run a process with stdin closed, capture stdout/stderr, kill after `timeout`. private static func execute(_ arguments: [String], timeout: TimeInterval) -> ProcessOutput { let path = arguments[0] guard FileManager.default.isExecutableFile(atPath: path) else { return ProcessOutput(exitCode: -1) } let process = Process() process.executableURL = URL(fileURLWithPath: path) process.arguments = Array(arguments.dropFirst()) process.standardInput = FileHandle.nullDevice let stdoutPipe = Pipe(), stderrPipe = Pipe() process.standardOutput = stdoutPipe process.standardError = stderrPipe do { try process.run() } catch { return ProcessOutput(exitCode: -1) } let deadline = Date().addingTimeInterval(timeout) while process.isRunning, Date() < deadline { Thread.sleep(forTimeInterval: 0.01) } if process.isRunning { terminateAndReap(process, pipes: [stdoutPipe.fileHandleForReading, stderrPipe.fileHandleForReading]) return ProcessOutput(exitCode: -1, stderr: "timed out after \(Int(timeout)) s") } // ponytail: sequential post-exit reads; would deadlock past ~64 KB of child output. // acp --check/--version emit one line (broken installs: a bounded traceback) — fine. // Swap for concurrent pipe drains if an engine ever logs volume here. let stdout = String(data: stdoutPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" let stderr = String(data: stderrPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" return ProcessOutput(exitCode: process.terminationStatus, stdout: stdout, stderr: stderr) } /// Kill an overdue child: SIGTERM, 0.5 s grace, SIGKILL, then reap so no zombie lingers. private static func terminateAndReap(_ process: Process, pipes: [FileHandle]) { process.terminate() let grace = Date().addingTimeInterval(0.5) while process.isRunning, Date() < grace { Thread.sleep(forTimeInterval: 0.01) } if process.isRunning { kill(process.processIdentifier, SIGKILL) } process.waitUntilExit() for pipe in pipes { try? pipe.close() } } /// Captured output of one child process run. private struct ProcessOutput { let exitCode: Int32 var stdout: String = "" var stderr: String = "" } /// Wholesale-replace state.json after every completed check (ticket #39). static func writeState(_ result: EngineCheckResult, appSupportDir: String? = nil) { let dir = appSupportDir ?? ("~/Library/Application Support/Museion" as NSString).expandingTildeInPath let record = StateRecord(result, checkedAt: ISO8601DateFormatter().string(from: Date())) do { try FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) try JSONEncoder().encode(record).write( to: URL(fileURLWithPath: dir).appendingPathComponent("state.json"), options: .atomic, ) } catch { // ponytail: state.json is advisory; a write failure must not crash the gate. } } /// Last completed check's record — what About mirrors (ticket #39: readers never check). static func readStateRecord(appSupportDir: String? = nil) -> StateRecord? { let dir = appSupportDir ?? ("~/Library/Application Support/Museion" as NSString).expandingTildeInPath let url = URL(fileURLWithPath: dir).appendingPathComponent("state.json") guard let data = try? Data(contentsOf: url) else { return nil } return try? JSONDecoder().decode(StateRecord.self, from: data) } /// schemaVersion-1 record; nil fields are omitted so a fail never carries a stale version. struct StateRecord: Codable { let schemaVersion: Int let status: String let checkedAt: String let engineVersion: String? let binaryPath: String? let firstProbePath: String? let stderrExcerpt: String? init(_ result: EngineCheckResult, checkedAt: String) { schemaVersion = 1 self.checkedAt = checkedAt switch result { case let .pass(version, binaryPath): status = "pass" engineVersion = version self.binaryPath = binaryPath firstProbePath = nil stderrExcerpt = nil case let .fail(firstProbePath, stderrExcerpt): status = "fail" engineVersion = nil binaryPath = nil self.firstProbePath = firstProbePath self.stderrExcerpt = String(stderrExcerpt.prefix(500)) } } } } /// SwiftUI-observable gate state for the gate UI. @MainActor @Observable final class EngineGateModel { enum Phase: Equatable { case idle case checking case pass(engineVersion: String, binaryPath: String) case fail(firstProbePath: String, stderrExcerpt: String) } private(set) var phase: Phase = .idle /// Fires once per runCheck that passes — the #13 provisioning seam (ticket #41). var onPass: (@MainActor @Sendable () -> Void)? private var hasStarted = false private var running = false /// Runs the probe loop off the main actor, then updates phase. Guards double-run. func runCheck( probePaths: [String] = EngineProbe.defaultProbePaths, shellFallback: Bool = true, timeout: TimeInterval = 5, appSupportDir: String? = nil, ) async { guard !running else { return } running = true phase = .checking let result = await Task.detached(priority: .userInitiated) { EngineProbe.perform(probePaths: probePaths, shellFallback: shellFallback, timeout: timeout, appSupportDir: appSupportDir) }.value switch result { case let .pass(engineVersion, binaryPath): phase = .pass(engineVersion: engineVersion, binaryPath: binaryPath) onPass?() case let .fail(firstProbePath, stderrExcerpt): phase = .fail(firstProbePath: firstProbePath, stderrExcerpt: stderrExcerpt) } running = false } /// Launch auto-check — once per app-launch regardless of how many windows open (ticket #41). func beginAutomaticCheck( probePaths: [String] = EngineProbe.defaultProbePaths, shellFallback: Bool = true, timeout: TimeInterval = 5, appSupportDir: String? = nil, ) async { guard !hasStarted else { return } hasStarted = true await runCheck(probePaths: probePaths, shellFallback: shellFallback, timeout: timeout, appSupportDir: appSupportDir) } }