feat(gate): add Engine gate launch check (S2.1)
CI / ci (push) Canceled after 0s

Block every app launch behind an Engine gate per wayfinder map #12:
discover the user-installed hermes binary via the documented six-path
probe (#36), health-check it with acp --check (stdin closed, 5 s
per-candidate timeout, exit-status branching), version via
acp --version, and record every completed check in Application
Support state.json (#39). The gate is a blocking sheet with
checking/pass/fail cards (#38/#40), app-scoped so only the first
window per launch auto-checks (#41); an About window mirrors the
state file read-only. Provisioning (#13) has a stub seam at
onEnginePass. 12 unit tests drive the real Process path with fake
hermes binaries; build, tests, swiftformat, swiftlint all green.

Closes #42

[Generated by AI]
This commit is contained in:
AlexKucera committed 2026-09-03 14:53:39 +02:00
1 parent 232ac9d722
commit 753da2135a
11 files changed
+832 -3

No files matched your search

+10 -2
View File
@@ -10,13 +10,21 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Local Contracts
- Entry point: `MuseionApp.swift` (`@main`, single `WindowGroup` scene).
- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state).
- `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project).
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 26.5; bundle id `com.babylondreams.Museion`.
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real.
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exception: the engine gate's `state.json` (see below).
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
## Engine gate (launch gate, tickets #35–#41)
- `EngineGate.swift` — `EngineProbe` (nonisolated): six-path probe order, `acp --check` health (stdin closed, 5 s timeout, exit-status branching), `acp --version` version, `state.json` writer/reader. `EngineGateModel` (@MainActor @Observable): phases for the UI, `onPass` seam for #13 provisioning.
- `EngineGateView.swift` — blocking sheet card: checking / pass (version + Start Writing) / fail (two install steps per #40, Re-check, Technical details disclosure). `interactiveDismissDisabled`; sheet never closes itself.
- `state.json` lives at `~/Library/Application Support/Museion/` — schemaVersion 1, wholesale-replaced after every completed check; fail records carry no `engineVersion`. Gate renders in-memory; About (`AboutEngineView` in `MuseionApp.swift`) reads the file and never triggers a check.
- Gate is app-scoped via `AppGateState` (first window per app-launch only, ticket #41); `EngineGateView.onEnginePass` is where provisioning (#13) will fire in parallel on pass.
- Tests: `MuseionTests/EngineGateTests.swift` builds fake `hermes` shell scripts and exercises the real Process path — probe order, first-stderr reporting, timeout kill, state records.
## Work Guidance
- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001).
+13
View File
@@ -13,7 +13,11 @@ enum AppMetadata {
}
struct ContentView: View {
@Environment(AppGateState.self) private var gate
var body: some View {
@Bindable var gate = gate
VStack(spacing: 8) {
Image(systemName: "books.vertical")
.font(.largeTitle)
@@ -25,5 +29,14 @@ struct ContentView: View {
}
.padding(32)
.frame(minWidth: 480, minHeight: 320)
.sheet(isPresented: $gate.gateRaised) {
EngineGateView(
model: gate.gateModel,
onEnginePass: {
// Ticket #41: provisioning (#13) fires here in parallel — stub until #13 lands.
},
onDismiss: { gate.gateRaised = false },
)
}
}
}
+252
View File
@@ -0,0 +1,252 @@
//
// 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)
}
}
+164
View File
@@ -0,0 +1,164 @@
//
// EngineGateView.swift
// Museion
//
// Ceiling note: a pathological all-hang machine holds the checking card up to
// ~N×5 s (per-candidate timeout, ticket #36) — not 5 s total.
//
import SwiftUI
/// The launch Engine gate: one blocking card, three states (tickets #38/#40/#41).
/// Shown once per app-launch over the first window; the sheet never closes itself.
struct EngineGateView: View {
/// Shared app-scoped model — one check per app-launch even if ⌘N opens more windows (#41).
let model: EngineGateModel
/// Fires the moment a check passes — provisioning (#13) starts here, in parallel (ticket #41).
var onEnginePass: (@MainActor @Sendable () -> Void)?
/// Unlock point: pass-card dismissal (ticket #41). The sheet's only exit.
var onDismiss: (@MainActor @Sendable () -> Void)?
var body: some View {
VStack(spacing: 14) {
switch model.phase {
case .idle, .checking:
checkingCard
case let .pass(engineVersion, binaryPath):
passCard(engineVersion: engineVersion, binaryPath: binaryPath)
case let .fail(firstProbePath, stderrExcerpt):
failCard(firstProbePath: firstProbePath, stderrExcerpt: stderrExcerpt)
}
}
.padding(24)
.frame(width: 460)
.onAppear {
model.onPass = onEnginePass
Task { await model.beginAutomaticCheck() }
}
.interactiveDismissDisabled()
}
// MARK: Checking (ticket #41) — spinner, no buttons; per-candidate timeout flips the card to fail
private var checkingCard: some View {
VStack(spacing: 14) {
ProgressView()
.controlSize(.regular)
.padding(.bottom, 2)
Text("Checking the Engine…")
.font(.title3)
Text("Running hermes acp --check")
.font(.callout)
.foregroundStyle(.secondary)
}
}
// MARK: Pass (ticket #40) — check icon, version, explicit dismiss; no re-check
private func passCard(engineVersion: String, binaryPath: String) -> some View {
VStack(spacing: 14) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 30))
.foregroundStyle(.secondary)
Text("Engine ready")
.font(.title3)
Text("Hermes \(engineVersion) answered the health check. The mentor is available.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
Text(binaryPath)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.tertiary)
.lineLimit(1)
.truncationMode(.middle)
Button("Start Writing") {
onDismiss?()
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
}
}
// MARK: Fail (ticket #40) — two install steps, re-check, collapsed stderr
private func failCard(firstProbePath: String, stderrExcerpt: String) -> some View {
VStack(spacing: 14) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 30))
.foregroundStyle(.orange)
Text("Museion needs its engine")
.font(.title3)
Text("The Hermes engine wasn't found or didn't answer. Museion is paused until it's installed — Passes and Sessions need it.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
installSteps
Button("Re-check") {
Task { await model.runCheck() }
}
.buttonStyle(.borderedProminent)
if !stderrExcerpt.isEmpty {
DisclosureGroup("Technical details") {
VStack(alignment: .leading, spacing: 6) {
Text(stderrExcerpt)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
Text("Probed: \(firstProbePath)")
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.tertiary)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
.frame(maxWidth: .infinity, alignment: .leading)
} else {
Text("Probed: \(firstProbePath)")
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.tertiary)
}
}
}
/// Ticket #40: exactly two steps + the docs link. Nothing else.
private var installSteps: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .top, spacing: 8) {
Text("1.").monospacedDigit().foregroundStyle(.secondary)
VStack(alignment: .leading, spacing: 4) {
Text(installCommand)
.font(.system(size: 11, design: .monospaced))
.textSelection(.enabled)
.fixedSize(horizontal: false, vertical: true)
Button {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(installCommand, forType: .string)
} label: {
Label("Copy", systemImage: "doc.on.doc")
}
.controlSize(.small)
.buttonStyle(.link)
.font(.system(size: 11))
}
}
HStack(alignment: .top, spacing: 8) {
Text("2.").monospacedDigit().foregroundStyle(.secondary)
Text("Come back here and click Re-check.")
}
Link("Installation guide", destination: URL(string: "https://hermes-agent.nousresearch.com/docs")!)
.font(.system(size: 11))
.frame(maxWidth: .infinity)
}
.padding(12)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 8))
}
private let installCommand = "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash"
}
#Preview {
EngineGateView(model: EngineGateModel())
}
+78
View File
@@ -7,11 +7,89 @@
import SwiftUI
/// App-scoped gate state — raised once per app-launch, first window only (ticket #41).
/// The model is shared so ⌘N during the gate can't start a second concurrent check.
@MainActor
@Observable
final class AppGateState {
var gateRaised = true
let gateModel = EngineGateModel()
}
@main
struct MuseionApp: App {
@State private var gate = AppGateState()
var body: some Scene {
WindowGroup {
ContentView()
.environment(gate)
}
Window("About \(AppMetadata.name)", id: "about") {
AboutEngineView()
}
.windowResizability(.contentSize)
.commands {
// SwiftUI has no About scene on macOS; replace the stock panel with our window.
CommandGroup(replacing: .appInfo) {
OpenAboutButton()
}
}
}
}
private struct OpenAboutButton: View {
@Environment(\.openWindow) private var openWindow
var body: some View {
Button("About \(AppMetadata.name)") { openWindow(id: "about") }
}
}
/// Read-only mirror of the last completed check's state.json record (ticket #39).
/// Reads the file when opened; never triggers a check; no re-check button.
struct AboutEngineView: View {
@State private var record: EngineProbe.StateRecord?
var body: some View {
VStack(spacing: 12) {
Image(systemName: "books.vertical")
.font(.largeTitle)
Text(AppMetadata.name)
.font(.title)
.bold()
Text(AppMetadata.tagline)
.foregroundStyle(.secondary)
Divider()
if let record {
VStack(alignment: .leading, spacing: 6) {
aboutRow("Engine", record.status == "pass" ? "Ready" : "Unavailable")
aboutRow("Engine version", record.engineVersion ?? "—")
aboutRow("Last checked", record.checkedAt)
aboutRow("Binary path", record.binaryPath ?? "—")
}
} else {
Text("No engine check recorded yet.")
.foregroundStyle(.secondary)
}
}
.padding(20)
.frame(width: 380)
.onAppear { record = EngineProbe.readStateRecord() }
}
private func aboutRow(_ label: String, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline) {
Text(label)
.foregroundStyle(.secondary)
Spacer(minLength: 12)
Text(value)
.textSelection(.enabled)
.lineLimit(1)
.truncationMode(.middle)
}
.font(.callout)
}
}