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

+11 -1
View File
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (411 symbols, 416 relationships, 0 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. This project is indexed by GitNexus as **museion** (621 symbols, 860 relationships, 6 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -169,3 +169,13 @@ This project is indexed by GitNexus as **museion** (411 symbols, 416 relationshi
| Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` | | Index, status, clean, wiki CLI commands | `.claude/skills/gitnexus/gitnexus-cli/SKILL.md` |
<!-- gitnexus:end --> <!-- gitnexus:end -->
## Session Logs
Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Full history: [`docs/devlog/INDEX.md`](docs/devlog/INDEX.md). The 10 most recent:
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-09-03 | [20260903-issue42-engine-gate-s2-1_log.md](docs/devlog/20260903-issue42-engine-gate-s2-1_log.md) |
<!-- write-log: window-end -->
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format
### Added ### Added
- **gate:** Engine gate (launch gate, PRD S2.1) — discovers the user-installed Hermes engine via the documented six-path probe, health-checks it (`hermes acp --check`), and blocks app launch behind a sheet on every launch: checking/pass/fail cards with install instructions and re-check on fail, engine version in the pass card, About window, and a `state.json` record of every completed check (issue #42)
- Initial project scaffold: Xcode project (SwiftUI, macOS 26.5+, Swift 6), unit + UI smoke tests, GPL-3.0-or-later license, Gitea Actions CI (dormant until a macOS runner registers), DOX agent documentation tree, ADRs 0001–0003 (stack, license, forge). - Initial project scaffold: Xcode project (SwiftUI, macOS 26.5+, Swift 6), unit + UI smoke tests, GPL-3.0-or-later license, Gitea Actions CI (dormant until a macOS runner registers), DOX agent documentation tree, ADRs 0001–0003 (stack, license, forge).
- **skills:** Pass and Session container persona skills — mentor manner by blend arithmetic (constant Knife floor, silent Learnings, voice anchor) - **skills:** Pass and Session container persona skills — mentor manner by blend arithmetic (constant Knife floor, silent Learnings, voice anchor)
- **skills:** Demonstrator doctrine skill — master-study demonstrations as named-master variants on the writer's own bounded span, annotated and desloped before display; the picked variant feeds Learnings (issue #3) - **skills:** Demonstrator doctrine skill — master-study demonstrations as named-master variants on the writer's own bounded span, annotated and desloped before display; the picked variant feeds Learnings (issue #3)
+10 -2
View File
@@ -10,13 +10,21 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Local Contracts ## 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). - `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`. - 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. - 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. - 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 ## Work Guidance
- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001). - 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 { struct ContentView: View {
@Environment(AppGateState.self) private var gate
var body: some View { var body: some View {
@Bindable var gate = gate
VStack(spacing: 8) { VStack(spacing: 8) {
Image(systemName: "books.vertical") Image(systemName: "books.vertical")
.font(.largeTitle) .font(.largeTitle)
@@ -25,5 +29,14 @@ struct ContentView: View {
} }
.padding(32) .padding(32)
.frame(minWidth: 480, minHeight: 320) .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 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 @main
struct MuseionApp: App { struct MuseionApp: App {
@State private var gate = AppGateState()
var body: some Scene { var body: some Scene {
WindowGroup { WindowGroup {
ContentView() 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)
}
}
+1
View File
@@ -17,6 +17,7 @@ Owned by the root AGENTS.md contract.
## Work Guidance ## Work Guidance
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked. - Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
## Verification ## Verification
+230
View File
@@ -0,0 +1,230 @@
//
// EngineGateTests.swift
// MuseionTests
//
// Created by Alexander Kucera on 03.09.26.
//
import Foundation
@testable import Museion
import Testing
/// Builds fake `hermes` executables at runtime so probes hit real processes.
/// Args seen by the fake: `acp --check` → exit checkExit; `acp --version` → "9.9.9".
/// Non-empty `stderr` overrides the check path to fail with that message on stderr.
private func makeFake(at dir: String, name: String, checkExit: Int32, stderr: String = "") -> String {
let path = (dir as NSString).appendingPathComponent(name)
let checkBlock = stderr.isEmpty
? "exit \(checkExit)"
: "print -u2 -- '\(stderr)'; exit \(checkExit)"
let script = """
#!/bin/zsh
if [[ "$*" == *--check* ]]; then
\(checkBlock)
elif [[ "$*" == *--version* ]]; then
print 9.9.9
exit 0
fi
exit 97
"""
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
try? script.write(toFile: path, atomically: true, encoding: .utf8)
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: path)
return path
}
private func tempDir(_ label: String) -> String {
let dir = NSTemporaryDirectory() + "museion-gate-\(label)-\(UUID().uuidString)"
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
return dir
}
private func readState(_ dir: String) -> [String: Any]? {
let url = URL(fileURLWithPath: dir).appendingPathComponent("state.json")
guard let data = try? Data(contentsOf: url), let json = try? JSONSerialization.jsonObject(with: data) else { return nil }
return json as? [String: Any]
}
private extension [String: Any] {
func str(_ key: String) -> String? {
self[key] as? String
}
}
@Suite("EngineGateTests")
struct EngineGateTests {
@Test func `first passing candidate wins and versions the winner`() {
let fake = makeFake(at: tempDir("pass"), name: "hermes", checkExit: 0)
let result = EngineProbe.perform(
probePaths: ["/nonexistent-hermes", fake],
shellFallback: false,
appSupportDir: tempDir("state"),
)
#expect(result == .pass(version: "9.9.9", binaryPath: fake))
}
@Test func `broken first candidate is skipped`() {
let dir = tempDir("skip")
let broken = makeFake(at: dir, name: "broken", checkExit: 1, stderr: "broken shim")
let good = makeFake(at: dir, name: "good", checkExit: 0)
let result = EngineProbe.perform(
probePaths: [broken, good],
shellFallback: false,
appSupportDir: tempDir("state"),
)
#expect(result == .pass(version: "9.9.9", binaryPath: good))
}
@Test func `all candidates fail reports first candidate stderr`() {
let dir = tempDir("allfail")
let first = makeFake(at: dir, name: "first", checkExit: 1, stderr: "alpha broken")
let second = makeFake(at: dir, name: "second", checkExit: 1, stderr: "beta broken")
let result = EngineProbe.perform(
probePaths: [first, second],
shellFallback: false,
appSupportDir: tempDir("state"),
)
guard case let .fail(path, stderr) = result else {
Issue.record("expected fail, got \(result)")
return
}
#expect(path == first)
#expect(stderr.contains("alpha broken"))
}
@Test func `not found yields empty stderr and first probe path`() {
let result = EngineProbe.perform(
probePaths: ["/nonexistent/alpha/hermes", "/nonexistent/beta/hermes"],
shellFallback: false,
appSupportDir: tempDir("state"),
)
guard case let .fail(path, stderr) = result else {
Issue.record("expected fail, got \(result)")
return
}
#expect(path == "/nonexistent/alpha/hermes")
#expect(stderr.isEmpty)
}
@Test func `timeout kills hung candidate and moves on`() {
let dir = tempDir("timeout")
let hung = (dir as NSString).appendingPathComponent("hung")
try? "#!/bin/zsh\nsleep 30\n".write(toFile: hung, atomically: true, encoding: .utf8)
_ = try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: hung)
let good = makeFake(at: dir, name: "good", checkExit: 0)
let result = EngineProbe.perform(
probePaths: [hung, good],
shellFallback: false,
timeout: 1,
appSupportDir: tempDir("state"),
)
#expect(result == .pass(version: "9.9.9", binaryPath: good))
}
@Test func `state json pass record`() {
let fake = makeFake(at: tempDir("json-pass"), name: "hermes", checkExit: 0)
let stateDir = tempDir("state")
_ = EngineProbe.perform(probePaths: [fake], shellFallback: false, appSupportDir: stateDir)
let json = readState(stateDir)
#expect(json?["schemaVersion"] as? Int == 1)
#expect(json?["status"] as? String == "pass")
#expect(json?["engineVersion"] as? String == "9.9.9")
#expect(json?["binaryPath"] as? String == fake)
#expect(json?["firstProbePath"] == nil)
#expect(json?["stderrExcerpt"] == nil)
let checkedAt = json?.str("checkedAt") ?? ""
#expect(ISO8601DateFormatter().date(from: checkedAt) != nil)
}
@Test func `fail record after pass carries no stale version`() {
let dir = tempDir("json-flip")
let good = makeFake(at: dir, name: "hermes", checkExit: 0)
let broken = makeFake(at: dir, name: "later-broken", checkExit: 1, stderr: "later breakage")
let stateDir = tempDir("state")
_ = EngineProbe.perform(probePaths: [good], shellFallback: false, appSupportDir: stateDir)
_ = EngineProbe.perform(probePaths: [broken], shellFallback: false, appSupportDir: stateDir)
let json = readState(stateDir)
#expect(json?["status"] as? String == "fail")
#expect(json?["engineVersion"] == nil)
#expect(json?["binaryPath"] == nil)
#expect(json?["firstProbePath"] as? String == broken)
let excerpt = json?.str("stderrExcerpt") ?? ""
#expect(excerpt.contains("later breakage"))
}
@Test func `not-found state record keeps first probe path`() {
let stateDir = tempDir("state")
_ = EngineProbe.perform(
probePaths: ["/nonexistent/alpha/hermes", "/nonexistent/beta/hermes"],
shellFallback: false,
appSupportDir: stateDir,
)
let json = readState(stateDir)
#expect(json?["status"] as? String == "fail")
#expect(json?["firstProbePath"] as? String == "/nonexistent/alpha/hermes")
let excerpt = json?.str("stderrExcerpt") ?? ""
#expect(excerpt.isEmpty)
}
@Test func `readStateRecord round-trips the About mirror`() {
let fake = makeFake(at: tempDir("roundtrip"), name: "hermes", checkExit: 0)
let stateDir = tempDir("state")
_ = EngineProbe.perform(probePaths: [fake], shellFallback: false, appSupportDir: stateDir)
let record = EngineProbe.readStateRecord(appSupportDir: stateDir)
#expect(record?.schemaVersion == 1)
#expect(record?.status == "pass")
#expect(record?.engineVersion == "9.9.9")
#expect(record?.binaryPath == fake)
}
@MainActor
@Test func `model runs a check and reaches pass phase`() async {
let fake = makeFake(at: tempDir("model"), name: "hermes", checkExit: 0)
let model = EngineGateModel()
await model.runCheck(probePaths: [fake], shellFallback: false, appSupportDir: tempDir("state"))
guard case let .pass(version, binaryPath) = model.phase else {
Issue.record("expected pass phase, got \(model.phase)")
return
}
#expect(version == "9.9.9")
#expect(binaryPath == fake)
}
@MainActor
@Test func `automatic check runs once per model`() async {
let fake = makeFake(at: tempDir("once"), name: "hermes", checkExit: 0)
let model = EngineGateModel()
await model.beginAutomaticCheck(probePaths: [fake], shellFallback: false, appSupportDir: tempDir("state"))
await model.beginAutomaticCheck(probePaths: ["/nonexistent"], shellFallback: false, appSupportDir: tempDir("state"))
guard case let .pass(_, binaryPath) = model.phase else {
Issue.record("expected pass phase, got \(model.phase)")
return
}
// Second begin call must be a no-op — still the first (passing) fake, not re-resolved to fail.
#expect(binaryPath == fake)
}
@MainActor
@Test func `onPass fires exactly once per passing check`() async {
let fake = makeFake(at: tempDir("onpass"), name: "hermes", checkExit: 0)
let model = EngineGateModel()
let fired = LockedCounter()
model.onPass = { fired.increment() }
await model.runCheck(probePaths: [fake], shellFallback: false, appSupportDir: tempDir("state"))
await model.runCheck(probePaths: [fake], shellFallback: false, appSupportDir: tempDir("state"))
#expect(fired.value == 2) // once per passing check; the #13 seam fires every pass
}
}
/// MainActor-safe counter for closure capture in tests.
private final class LockedCounter: @unchecked Sendable {
private let lock = NSLock()
private var count = 0
var value: Int {
lock.lock(); defer { lock.unlock() }; return count
}
func increment() {
lock.lock(); defer { lock.unlock() }; count += 1
}
}
@@ -0,0 +1,64 @@
# #42 M0: Implement Engine gate (S2.1)
> **Date:** 2026-09-03
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/42
## Goal
Build the launch Engine gate exactly as specified by wayfinder map #12 (closed) and its seven child tickets #35–#41: discover the user-installed `hermes` binary via the six-path probe, health-check it with `acp --check`, version it with `acp --version`, record every completed check in `state.json`, and gate the app behind a blocking sheet on every launch — no decisions left to make.
## What Was Done
- `Museion/EngineGate.swift` — `EngineProbe` (nonisolated): six-path absolute probe order, one iterate-until-pass loop over `acp --check` (stdin closed, 5 s per-candidate timeout, exit-status branching, first-candidate stderr on all-fail), SIGTERM→SIGKILL escalation + reap on timeout, `acp --version` with `unknown` fallback on failure, one `zsh -l -c 'command -v hermes'` last-resort fallback, schemaVersion-1 `state.json` written/wholesale-replaced after every completed check. `EngineGateModel` (@MainActor @Observable): phases, `onPass` seam for #13 provisioning, `beginAutomaticCheck()` once-per-app-launch guard.
- `Museion/EngineGateView.swift` — the blocking sheet card: checking (spinner, no buttons) / pass (version + binary path + Start Writing) / fail (#40 copy verbatim: two install steps with copyable curl line, Re-check, collapsed Technical-details disclosure).
- `Museion/MuseionApp.swift` — `AppGateState` (app-scoped; shared `gateModel` so ⌘N can't start a second concurrent check), About window via `CommandGroup(replacing: .appInfo)` + `openWindow` reading `state.json` read-only.
- `Museion/ContentView.swift` — sheet wiring over the workspace.
- `MuseionTests/EngineGateTests.swift` — 12 Swift Testing tests exercising the real `Process` path with runtime-built fake zsh `hermes` binaries.
- DOX: engine-gate section in `Museion/AGENTS.md`, fake-binary test pattern in `MuseionTests/AGENTS.md`.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| About = `Window` + `CommandGroup(replacing: .appInfo)` | Verified against the macOS 26.5 swiftinterface: SwiftUI has no About scene on macOS. Two hallucinated modifiers (`.about`, `.aboutWindow`) failed to compile before the SDK check. |
| Shared `AppGateState.gateModel` + `beginAutomaticCheck()` | Finish-audit found ⌘N during the gate bound two sheets to one flag → two models, two checks, two state.json writes, violating #41/#39. One shared model with a hasStarted guard fixes the class. |
| SIGTERM + 0.5 s grace + SIGKILL + `waitUntilExit` | Audit MED: bare `terminate()` never reaped; a SIGTERM-ignoring child would live forever and the Process never waited. |
| `version == "unknown"` on `acp --version` failure | Audit LOW: empty version rendered "Hermes answered" (double space). A failing version probe must not fail the gate (#35: health is --check's job). |
| Sequential post-exit pipe reads (ponytail comment) | Swift 6 rejects capturing mutable vars in @Sendable reader closures; child output is one line or a bounded traceback, so post-exit reads are correct here with a named ceiling. |
| Model in `AppGateState`, not `@State` in the view | Gate is app-scoped per #41; view-local state would re-create per window. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| First subagent produced a syntactically corrupted test file (`# "expect"(…)`, duplicate args, invented identifiers) and never ran the build | Child hit its iteration cap; provider's 90 s non-streaming timeout killed its final generations (4 child deaths this session) | Rewrote tests in-parent; verified everything with real xcodebuild runs |
| 3-reviewer finish-audit fanout died twice at caps, zero findings delivered | Same child timeout, triggered by long final reports | Retried with hard brevity caps (≤15/20/25 lines) — all three reports then landed |
| `EngineProbe` implicitly MainActor-isolated; `Task.detached` couldn't call it | Project uses `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` | `nonisolated enum` (SE-0449) on both probe enums |
| Patches collided on overlapping matches, mangling braces twice | Rapid-fire fuzzy patches against adjacent regions | Full-file `write_file` rewrites, verified by the next build |
| SwiftLint `nesting` on `CodingKeys` | Only violation; suppression comment | Deleted entirely in audit — synthesized CodingKeys are identical (optionals omit via encodeIfPresent) |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/EngineGate.swift` | new — probe/check/version/state machinery + observable model |
| `Museion/EngineGateView.swift` | new — blocking gate sheet, three cards |
| `MuseionTests/EngineGateTests.swift` | new — 12 tests, fake-binary Process harness |
| `Museion/MuseionApp.swift` | AppGateState, About window, appInfo replacement |
| `Museion/ContentView.swift` | gate sheet wiring |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX for the gate + test pattern |
| `CHANGELOG.md` | Unreleased/Added entry |
## Open Items & Next Steps
- [ ] #13 provisioning — wire into the `onEnginePass` seam (stub comment marks the spot)
- [ ] #42 close + comment on the forge (verification data above)
- [ ] CI note: XCUITest automation-mode timeout flake observed once locally; retry passed — watch for it when the macOS runner registers
- [ ] #14 ACP bridge reads `state.json` (never checks) per #39
**Verification:** `xcodebuild build` + `test` green (12 unit + 1 UI, zero warnings), swiftformat + swiftlint clean, real app launch wrote `{"status":"pass","engineVersion":"0.20.6","binaryPath":"/Users/alex/.local/bin/hermes"}`, gitnexus detect-changes low-risk/expected symbols only, index 411→621 nodes.
---
*Log written by write-log skill*
+8
View File
@@ -0,0 +1,8 @@
# Session Log Index
Complete history of session logs in this directory, newest first. One-line summaries — open a log for full detail.
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-09-03 | issue | [20260903-issue42-engine-gate-s2-1_log.md](20260903-issue42-engine-gate-s2-1_log.md) | Engine gate S2.1 shipped: six-path probe, blocking sheet, state.json, About mirror — 12 tests green |