Files
museion/MuseionTests/EngineGateTests.swift
AlexKuceraandCipher c0b2cb0b93
CI / ci (push) Canceled after 0s
feat(provisioning): add S2.1 pass with failure alert & retry (fixes #47, #48)
Idempotent per-gate pass: create the museion Hermes profile only when
missing (exit-1 "already exists" = success), then additively seed the
bundled writing skills from seed-manifest.txt — temp-copy+rename, present
skills never touched, orphaned temps swept, manifest entries validated
kebab-case at the trust boundary.

Failures surface a separate phase-named alert ("couldn't set up the
writing profile" / "couldn't copy the writing skills"), never re-raising
the gate: excerpt behind Technical details (stdout per #43, stderr
fallback), Retry re-runs the whole pass, Not Now defers to the next
launch's silent retry. The card presents only after the gate sheet's
dismissal completes and snapshots its failure so a successful Retry
doesn't blank it mid-animation.

Provisioning writes nothing to the profile config (no mcp_servers entry,
#44) and leaves state.json engine-gate-only. 30/30 tests green.

Co-Authored-By: Cipher <cipher@babylondreams.de>
2026-09-05 15:03:01 +02:00

233 lines
8.6 KiB
Swift

//
// 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,
// ponytail: 3 s, not 1 — a zsh fake's startup can exceed 1 s under
// parallel-suite load and the good candidate would be killed too.
timeout: 3,
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
}
}