Files
museion/Museion/EngineGate.swift
T
AlexKucera 683ddf8426
CI / ci (push) Canceled after 0s
feat(mentor): museion-tools MCP server (#23)
Headless --serve-mcp role in the app binary: NDJSON JSON-RPC on stdio
exposing query_learnings and submit_fix_cards (ADR-0006 cards,
anchor-validated; stale lands flagged, never rejected), registered
into the museion profile at provisioning. Cards persist per piece
under <piece>/cards/ and surface in a floating Fix Cards palette
with pass-stamped provenance.

Live dogfood drove the shape: session/prompt waits pass length (the
15 s request default abandoned working turns), a liveness row and a
persisted Debug checkbox (off) split writing sessions from debug
chatter, the verdict references findings by title only while the
cards carry the detail (persona v1.3 — tools work in silence), and
the #24 pass rails (pass bar, TurnOutcome seam, snapshots) ride in.

Three-reviewer audit round: piece-path shape guard closes the
JSON-drop and substring-oracle holes, nested submit rawInput parsing
(the flat parser never matched the live rail), missing stopReason
never advances a pass, 1 MB stdin cap, card scan off MainActor.
296 tests green; every behavioral fix flip-verified.

Closes #23
2026-10-20 12:20:54 +02:00

278 lines
10 KiB
Swift

//
// 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, capture stdout/stderr, kill after `timeout`. `stdin` (when
/// set) is written to the child then closed — for interactive prompts like
/// the mcp add's "Enable all tools? [Y/n]"; otherwise stdin is /dev/null.
static func execute(_ arguments: [String], timeout: TimeInterval, stdin: String? = nil) -> 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())
// The parent holds the pipe's read end until dealloc, so this small
// pre-spawn write can't hit EPIPE; closing our write end gives the
// child one line + EOF. Ceiling (audit INFO-6): a pre-spawn write
// must stay well under the 64 KB pipe buffer or it deadlocks before
// the watchdog exists — chunked write or spawn-then-write if a
// caller ever needs more.
var stdinPipe: Pipe?
if let stdin {
let pipe = Pipe()
process.standardInput = pipe
try? pipe.fileHandleForWriting.write(contentsOf: Data(stdin.utf8))
try? pipe.fileHandleForWriting.close()
stdinPipe = pipe
} else {
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 {
var pipes = [stdoutPipe.fileHandleForReading, stderrPipe.fileHandleForReading]
if let stdinPipe {
pipes.append(stdinPipe.fileHandleForReading)
}
terminateAndReap(process, pipes: pipes)
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.
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
/// The gate's winning binary path — handed to provisioning (#47) so the
/// profile-create spawn uses the exact binary the gate just health-checked.
private(set) var currentBinaryPath: String?
/// 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)
currentBinaryPath = 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)
}
}