CI / ci (push) Canceled after 0s
Profiles S4: passes run on their OWN one-shot engines — `hermes acp -p museion-passN` spawns per pass run and tears down at the verdict, so a model switch costs nothing (the next spawn reads fresh config). The verdict streams into a TRANSIENT unrostered transcript (#129's ruling: one Sessions surface over the chat engine; a rostered pass session would be unresumable by the chat engine). `beginPassSession` died with it — passes never mint sessions; the #28 roster pins flipped to the transient posture. The chat engine stays resident (adopted museion profile): a Chat model change in Settings fires onChatSurfaceWrite after a successful chat-surface write only, wired to requestRestart — re-spawn in place when idle (resuming the pre-restart active session), deferred to turn end while any turn streams (#129). Missing-key posture (#132): refreshPassReadiness reads both pass profiles' providers and their .env keys at pane entry; Run Pass disables naming the provider with an Open Settings link, .unknown never blocks, and the guard refuses before anything touches disk. Finish-audit (ponytail/security/general fanout) applied: the general reviewer's Medium — a session/new/load/fork completing mid-pass stole the active surface and lost the Cancel to the wrong engine — fixed with ONE claimActive gate across the post-await activation writers, pinned deterministically via the fake's loadReplayHold park + a mode-file flip (flip-verified: guard off fails on the steal observables and the misrouted-cancel hang). Also fixed: a spawn-window cancel loss in stopStreaming (keyed on the transient entry, not the late-arriving wire id), and a PRE-EXISTING rescan bug where a stale scan snapshot "vanished" a just-opened piece and killed its session, cancelling the edit debounce — the vanish-kill now re-checks disk and the watched home. Ponytail cut ~59 lines of test duplication; the app target's only force-unwrap is gone. Suite 477 (was 472): EngineLifecycleTests new (own-engine end-to-end, held-pass cancel, idle + deferred restart ordering, readiness, steal pin), +3 Settings hook pins, one duplicate pin deduplicated. swiftformat clean, swiftlint at HEAD baseline. Closes #137
368 lines
16 KiB
Swift
368 lines
16 KiB
Swift
//
|
||
// EngineLifecycleTests.swift
|
||
// MuseionTests
|
||
//
|
||
// #137 (Profiles S4): per-surface engine lifecycle — passes run on their
|
||
// own ONE-SHOT engines (spawned per run on the pass profile, torn down at
|
||
// the verdict, never rostered per #129) and the Chat model-change restart
|
||
// posture (restart in place when idle, defer to turn end while streaming).
|
||
// Real client + fake ACP path; the fake's spawn log pins WHICH engine ran.
|
||
//
|
||
|
||
import Foundation
|
||
@testable import Museion
|
||
import Testing
|
||
|
||
/// makePassRig's shape plus the fake's directory — the spawn log beside
|
||
/// the fake is the "which engine (profile) spawned" observable (#137).
|
||
@MainActor
|
||
private struct EngineRig {
|
||
let model: PostsModel
|
||
let home: URL
|
||
let mentor: MentorSessionModel
|
||
let fakeDir: String
|
||
}
|
||
|
||
@MainActor
|
||
private func makeEngineRig(mode: String = "full") throws -> EngineRig {
|
||
let (model, home) = try makeModelHome()
|
||
let dir = acpTempDir("engine-lifecycle")
|
||
let fake = makeFakeACP(at: dir, mode: mode)
|
||
return EngineRig(model: model, home: home, mentor: MentorSessionModel(binaryPath: fake), fakeDir: dir)
|
||
}
|
||
|
||
/// Bounded poll until a child is reaped (kill(pid, 0) fails) — the house
|
||
/// 250×20 ms pattern, 100 rounds for a close() that reaps synchronously.
|
||
@MainActor
|
||
private func pollReaped(_ pid: pid_t) async throws -> Bool {
|
||
for _ in 0 ..< 100 where kill(pid, 0) == 0 {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
return kill(pid, 0) != 0
|
||
}
|
||
|
||
// Scenario: A pass run lives on its own engine
|
||
// From user story #137 acceptance 1
|
||
// Given a saved piece is open and the chat engine is resident
|
||
// When the writer runs Pass 1
|
||
// Then Museion spawns `hermes acp -p museion-pass1`, streams the verdict
|
||
// into the pane's transcript, tears that engine down at the verdict
|
||
// (nothing pass-shaped stays resident), rosters nothing, and the chat
|
||
// engine keeps running untouched.
|
||
|
||
@Test @MainActor func `a pass run lives on its own engine and rosters nothing`() async throws {
|
||
let rig = try makeEngineRig()
|
||
defer { rig.mentor.shutdown() } // #124: at rig creation — the children die with the test
|
||
await rig.mentor.openSession()
|
||
let chatPid = try #require(rig.mentor.childProcessIdentifier)
|
||
let rosterBefore = rig.mentor.roster.count
|
||
let post = try PostStore.writeNew(body: "# Own Engine\n\nVerdict me.", home: rig.home)
|
||
rig.model.select(post.id, home: rig.home)
|
||
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
|
||
// In a Task — the pass child's pid is only observable while it runs.
|
||
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
|
||
var passPid: pid_t?
|
||
var polls = 0
|
||
while passPid == nil, polls < 250 {
|
||
passPid = rig.mentor.passEngineChildPid
|
||
polls += 1
|
||
if passPid == nil {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
}
|
||
_ = await run.value
|
||
|
||
// The run completed as today: snapshot landed, Pass-1 Done stamped.
|
||
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
|
||
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
|
||
#expect(snapshot.contains("Verdict me."))
|
||
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
|
||
#expect(onDisk.contains("pass_state: Pass-1 Done"))
|
||
// The pass engine spawned under its own profile; the chat engine under museion.
|
||
let lines = try String(
|
||
contentsOfFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-spawn-log"),
|
||
encoding: .utf8,
|
||
).split(separator: "\n").map(String.init)
|
||
#expect(lines.contains("acp -p museion-pass1"))
|
||
#expect(lines.contains("acp -p museion"))
|
||
// Nothing pass-shaped stays resident…
|
||
#expect(rig.mentor.roster.count == rosterBefore)
|
||
#expect(!rig.mentor.isPassEngineRunning)
|
||
if let passPid {
|
||
#expect(try await pollReaped(passPid))
|
||
} else {
|
||
Issue.record("pass engine pid never observed while the run was in flight")
|
||
}
|
||
// …and the chat engine is untouched.
|
||
#expect(kill(chatPid, 0) == 0)
|
||
#expect(rig.mentor.phase.isReady)
|
||
// The label row and the streamed critique rendered on the active surface.
|
||
#expect(textRows(of: rig.mentor).contains("Pass 1 · \(post.title)"))
|
||
#expect(!textRows(of: rig.mentor).contains { $0.contains("Critique the piece") })
|
||
var streamed = false
|
||
for _ in 0 ..< 250 {
|
||
streamed = textRows(of: rig.mentor).contains { $0.contains("Hello mentor.") }
|
||
if streamed {
|
||
break
|
||
}
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
#expect(streamed)
|
||
}
|
||
|
||
/// A1 cancel: the pass bar's Cancel reaches the PASS engine — the held turn
|
||
/// ends cancelled, the pass child is reaped, the roster never grew, and the
|
||
/// pre-pass snapshot still landed (pre-pass is unconditional).
|
||
@Test @MainActor func `cancelling a live pass cancels the turn and reaps the pass engine`() async throws {
|
||
let rig = try makeEngineRig(mode: "hangOnPrompt")
|
||
defer { rig.mentor.shutdown() }
|
||
await rig.mentor.openSession()
|
||
let rosterBefore = rig.mentor.roster.count
|
||
let post = try PostStore.writeNew(body: "# Held Pass\n\nCancel me.", home: rig.home)
|
||
rig.model.select(post.id, home: rig.home)
|
||
|
||
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
|
||
var passPid: pid_t?
|
||
var polls = 0
|
||
while passPid == nil, polls < 250 {
|
||
passPid = rig.mentor.passEngineChildPid
|
||
polls += 1
|
||
if passPid == nil {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
}
|
||
let heldPid = try #require(passPid, "pass engine never spawned")
|
||
#expect(rig.mentor.isPassEngineRunning)
|
||
|
||
rig.model.cancelPass(mentor: rig.mentor) // the pass bar's Cancel rail
|
||
for _ in 0 ..< 250 where rig.model.runningPass != nil {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
#expect(rig.model.runningPass == nil)
|
||
_ = await run.value
|
||
|
||
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
|
||
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
|
||
#expect(snapshot.contains("Cancel me."))
|
||
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
|
||
#expect(onDisk.contains("pass_state: First Draft"))
|
||
#expect(!rig.mentor.isPassEngineRunning)
|
||
#expect(try await pollReaped(heldPid))
|
||
#expect(rig.mentor.roster.count == rosterBefore)
|
||
}
|
||
|
||
// Scenario: A Chat model change restarts the resident engine, but never mid-reply
|
||
// From user story #137 acceptance 2
|
||
// Given the resident chat engine is mid-turn (streaming)
|
||
// When a chat model change is requested (Settings fires it; this slice
|
||
// exposes the engine-side API)
|
||
// Then the restart waits for the turn to end, then re-spawns the engine in
|
||
// place and replays the active rostered session — while idle, it restarts
|
||
// immediately.
|
||
|
||
/// A2 idle: requestRestart re-spawns in place — old child reaped, new child
|
||
/// alive, phase back to .ready, and the PRE-restart active rostered session
|
||
/// is resumed with its transcript replayed from the engine.
|
||
@Test @MainActor func `idle requestRestart respawns in place and replays the active rostered session`() async throws {
|
||
let rig = try makeEngineRig(mode: "loadReplay")
|
||
defer { rig.mentor.shutdown() }
|
||
await rig.mentor.openSession()
|
||
let active = try #require(rig.mentor.activeEntry)
|
||
_ = await rig.mentor.sendPrompt("hello mentor") // history in the active session
|
||
let oldPid = try #require(rig.mentor.childProcessIdentifier)
|
||
|
||
rig.mentor.requestRestart()
|
||
|
||
var newPid: pid_t?
|
||
var polls = 0
|
||
while newPid == nil, polls < 250 {
|
||
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != oldPid {
|
||
newPid = pid
|
||
} else {
|
||
polls += 1
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
}
|
||
let respawned = try #require(newPid, "chat engine never re-spawned")
|
||
#expect(try await pollReaped(oldPid))
|
||
#expect(kill(respawned, 0) == 0)
|
||
// The writer stays where they were: same rostered session, replayed.
|
||
#expect(rig.mentor.activeEntry == active)
|
||
var replayed = false
|
||
for _ in 0 ..< 250 {
|
||
replayed = !rig.mentor.transcriptRows(of: active).isEmpty
|
||
if replayed {
|
||
break
|
||
}
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
#expect(replayed)
|
||
}
|
||
|
||
/// A2 deferred ordering pin: requested mid-turn, the restart holds (same
|
||
/// child, still streaming) until the turn ends — the pid swap happens only
|
||
/// AFTER the turn.
|
||
@Test @MainActor func `requestRestart mid-turn defers the respawn until the turn ends`() async throws {
|
||
let rig = try makeEngineRig(mode: "hangOnPrompt")
|
||
defer { rig.mentor.shutdown() }
|
||
await rig.mentor.openSession()
|
||
let chatPid = try #require(rig.mentor.childProcessIdentifier)
|
||
|
||
let turn = Task { await rig.mentor.sendPrompt("hold this") }
|
||
for _ in 0 ..< 250 where !rig.mentor.isStreaming {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
#expect(rig.mentor.isStreaming)
|
||
|
||
rig.mentor.requestRestart() // Settings fires — mid-turn
|
||
try await Task.sleep(for: .milliseconds(300))
|
||
// Still streaming, same child: the restart deferred, never mid-reply.
|
||
#expect(rig.mentor.isStreaming)
|
||
#expect(rig.mentor.childProcessIdentifier == chatPid)
|
||
#expect(kill(chatPid, 0) == 0)
|
||
|
||
rig.mentor.stopStreaming() // ends the held turn — the restart fires now
|
||
_ = await turn.value
|
||
#expect(!rig.mentor.isStreaming)
|
||
|
||
var newPid: pid_t?
|
||
var polls = 0
|
||
while newPid == nil, polls < 250 {
|
||
if rig.mentor.phase.isReady, let pid = rig.mentor.childProcessIdentifier, pid != chatPid {
|
||
newPid = pid
|
||
} else {
|
||
polls += 1
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
}
|
||
#expect(newPid != nil, "the deferred pid swap never happened after turn end")
|
||
#expect(try await pollReaped(chatPid))
|
||
}
|
||
|
||
// Scenario: Run Pass names the missing key instead of failing silently
|
||
// From user story #137 acceptance 3
|
||
// Given Pass 1's provider has no key in the profiles' .env
|
||
// When the writer opens the mentor pane
|
||
// Then Run Pass is disabled with the reason named (provider) and a Settings
|
||
// link; once the key is provided via Settings, Run Pass re-enables (pane
|
||
// re-entry refreshes).
|
||
|
||
/// B1 readiness pins: refreshPassReadiness over the injected RecordingWriter
|
||
/// — keyed provider reads .ready, an unkeyed one reads .missingKey with its
|
||
/// label, a key landing re-enables on the next refresh (the pane's .task),
|
||
/// and a surface we can't read reads .unknown (never blocks on our own
|
||
/// failure — the spawn's honest failure row owns that path).
|
||
@Test @MainActor func `pass readiness names the missing provider key and re-enables on rekey`() async {
|
||
let mentor = MentorSessionModel()
|
||
let writer = RecordingWriter()
|
||
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5", effort: nil), nil)
|
||
writer.cannedKeys[.anthropic] = "sk-live"
|
||
writer.cannedReads[.pass2] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), nil)
|
||
mentor.passReadinessWriter = writer
|
||
await mentor.refreshPassReadiness()
|
||
#expect(mentor.readiness(for: .pass1) == .ready)
|
||
#expect(mentor.readiness(for: .pass2) == .missingKey(providerLabel: "z.ai"))
|
||
// The Settings path: the key lands, pane re-entry re-fires the
|
||
// refresh — Run Pass re-enables.
|
||
writer.cannedKeys[.zai] = "sk-z"
|
||
await mentor.refreshPassReadiness()
|
||
#expect(mentor.readiness(for: .pass2) == .ready)
|
||
// Unreadable surfaces read .unknown — a read failure of OURS never
|
||
// blocks the run.
|
||
mentor.passReadinessWriter = RecordingWriter()
|
||
await mentor.refreshPassReadiness()
|
||
#expect(mentor.readiness(for: .pass1) == .unknown)
|
||
#expect(mentor.readiness(for: .pass2) == .unknown)
|
||
}
|
||
|
||
/// B1 guard pin: with readiness .missingKey the runPass guard names the
|
||
/// provider in lastError — and fires BEFORE the open-piece guard's
|
||
/// snapshot, so nothing lands on disk.
|
||
@Test @MainActor func `run pass names the missing provider key and writes nothing`() async throws {
|
||
let rig = try makeEngineRig()
|
||
defer { rig.mentor.shutdown() }
|
||
await rig.mentor.openSession()
|
||
let writer = RecordingWriter()
|
||
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), nil)
|
||
rig.mentor.passReadinessWriter = writer
|
||
await rig.mentor.refreshPassReadiness()
|
||
let post = try PostStore.writeNew(body: "# No Key\n\nPass me.", home: rig.home)
|
||
rig.model.select(post.id, home: rig.home)
|
||
for _ in 0 ..< 250 where rig.model.session?.postID != post.id {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
// The piece must be OPEN — otherwise the open-piece guard would pass
|
||
// this pin vacuously.
|
||
try #require(rig.model.session?.postID == post.id)
|
||
|
||
await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor)
|
||
|
||
#expect(rig.model.lastError == "Pass 1 needs a z.ai API key — add it in Settings → Provider Keys.")
|
||
let piece = rig.home.appendingPathComponent("projects/posts/\(post.id)")
|
||
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("passes/pass-1.md").path))
|
||
#expect(rig.model.runningPass == nil)
|
||
}
|
||
|
||
/// #137 audit (finish): a session/load that STARTED before a pass and
|
||
/// COMPLETES mid-pass must not steal the pass surface — the post-await
|
||
/// claimActive guard refuses, Cancel keeps routing to the pass engine.
|
||
/// loadReplayHold parks the load until `load-go` lands beside the fake
|
||
/// (SessionLifecycleTests' in-flight seam), which makes the interleaving
|
||
/// deterministic instead of lucky.
|
||
@Test @MainActor func `a resume completing mid-pass does not steal the pass surface`() async throws {
|
||
let rig = try makeEngineRig(mode: "loadReplayHold")
|
||
defer { rig.mentor.shutdown() }
|
||
await rig.mentor.openSession() // default Mentor session (sess-1)
|
||
_ = await rig.mentor.newSession(name: "Second", pieceTitle: nil) // sess-2 active
|
||
let target = try #require(rig.mentor.roster.last) // sess-1, NOT active
|
||
let post = try PostStore.writeNew(body: "# Held Load\n\nResume races a pass.", home: rig.home)
|
||
rig.model.select(post.id, home: rig.home)
|
||
for _ in 0 ..< 250 where !rig.model.posts.contains(where: { $0.id == post.id }) {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
|
||
// Park a resume of sess-1. The fake announces the park with a
|
||
// `hold-load` stderr line (the chat engine's stderrTail surfaces it).
|
||
let resume = Task { await rig.mentor.resumeSession(target) }
|
||
for _ in 0 ..< 250 where !rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
try #require(rig.mentor.stderrTail.contains(where: { $0.contains("hold-load") }))
|
||
|
||
// Deterministic window: flip the mode file to hangOnPrompt BEFORE the
|
||
// pass engine spawns (each child reads the mode at startup) — the pass
|
||
// prompt then HOLDS, so isStreaming is guaranteed when the parked load
|
||
// completes, and the #124 Cancel rail frees it afterwards.
|
||
try "hangOnPrompt".write(
|
||
toFile: (rig.fakeDir as NSString).appendingPathComponent("hermes-acp-mode"),
|
||
atomically: true,
|
||
encoding: .utf8,
|
||
)
|
||
let run = Task { await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor) }
|
||
for _ in 0 ..< 250 where !rig.mentor.isPassEngineRunning {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
try #require(rig.mentor.isPassEngineRunning)
|
||
|
||
// Free the parked load — its completion lands while the pass holds
|
||
// (nothing blocks the load; the held pass makes the direct await safe).
|
||
try Data().write(to: URL(fileURLWithPath: (rig.fakeDir as NSString).appendingPathComponent("load-go")))
|
||
// The resume refused post-await while the pass still held the surface…
|
||
#expect(await resume.value == false)
|
||
#expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey)
|
||
|
||
// …and Cancel still routes to the pass engine (#124 rail) — the held
|
||
// turn ends cancelled, the pass never advances.
|
||
rig.model.cancelPass(mentor: rig.mentor)
|
||
for _ in 0 ..< 250 where rig.model.runningPass != nil {
|
||
try await Task.sleep(nanoseconds: 20_000_000)
|
||
}
|
||
_ = await run.value
|
||
#expect(rig.mentor.activeEntry?.sessionId == MentorSessionModel.passTranscriptKey)
|
||
#expect(textRows(of: rig.mentor).contains("Resume refused — the mentor is mid-turn."))
|
||
#expect(rig.mentor.roster.contains(target))
|
||
}
|