Files
museion/MuseionTests/EngineLifecycleTests.swift
T
AlexKucera 5bf09552f6
CI / ci (push) Canceled after 0s
refactor(posts): route every library write through one rail
#179: every library-reflecting store write (draft save, session-born
post, rename, move to project, archive/restore, trash, convert,
project creation, import batch, pass advance) now rides one internal
seam — performWrite pairs the write with exactly one rescan and owns
the error strip (cleared BEFORE the write so importFiles' per-file
failure messages survive the success tail; a nil-Home refusal writes
nothing). The model owns the Home: watchedHome is private(set), set
only by bind (construction + the Settings repoint); no public method
takes a Home parameter — 14 view call sites and ~115 test call sites
swept, dead home plumbing cut. The editor's debounced flush, the card
closes, the pass substrate and the micropub publish stay off the rail
by design (own error semantics, no library regroup).

A converged review finding is closed with a guard: the pass advance
re-resolves watchedHome after the engine's minutes-long turn, so a
mid-pass Settings repoint now refuses the advance with an honest strip
message instead of silently stamping pass state into the repointed
library (wrong-piece write on a slug collision). createProject
failures now surface in the sheet AND the strip — the rail-owns-the-
strip posture supersedes the #108 sheet-only rule.

Five rail pins (PostsModelWriteRailTests, suite members): write → one
library refresh + strip cleared, failed write owns the strip, nil-Home
refusal, import batch keeps per-file messages, mid-pass repoint
refuses the advance — the last two flip-verified against their guards.
ScriptedEngine gains endHeldPrompt (release a held turn as ended).

Verification: suite 657/657 the evening this landed; the next-morning
re-run could not start — both test runners hung before establishing
connection (#134 testmanagerd wedge; an untouched control suite hangs
identically — machine state, not this diff; reboot pending). Rail pins
5/5 isolated after the last test-only edit; swiftlint at baseline
parity; swiftformat clean.

Closes #179

[Generated by AI]
2026-11-10 08:45:04 +01:00

365 lines
17 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).
// #178: runs IN-PROCESS over ScriptedEngines rigs at the EngineTransport
// seam — the rig's spawnedProfiles pin WHICH engine ran; pid pins became
// transport-identity/closed pins (host.chat/host.oneShot identity +
// ScriptedEngine.isClosed).
//
import Foundation
@testable import Museion
import Testing
/// Poll for the pass engine's transport while the run is in flight —
/// host.oneShot is only observable mid-run (the host nils it at teardown).
/// For HELD passes only: a full-mode scripted pass can complete inside a
/// single 20 ms poll sleep, so completed runs capture via spawnedProfiles.
@MainActor
private func pollOneShot(of mentor: MentorSessionModel) async throws -> ScriptedEngine? {
var engine: ScriptedEngine?
var polls = 0
while engine == nil, polls < 250 {
if let transport = mentor.host.oneShot, let scripted = transport as? ScriptedEngine {
engine = scripted
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
return engine
}
// 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 makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let chatBefore = rig.mentor.host.chat
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)
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 — a full-mode scripted pass can complete inside one poll
// sleep (no child-process latency anymore), so the pass ENGINE is
// captured after the run from the spawn records, not polled mid-flight.
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
_ = await run.value
let passEngine = rig.engines.engines.last { $0.spawnedProfile == "museion-pass1" }
let passEngineClosed = try #require(passEngine, "pass engine never spawned")
// 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.
#expect(rig.engines.spawnedProfiles.contains("museion-pass1"))
#expect(rig.engines.spawnedProfiles.contains("museion"))
// Nothing pass-shaped stays resident…
#expect(rig.mentor.roster.count == rosterBefore)
#expect(!rig.mentor.isPassEngineRunning)
#expect(rig.mentor.host.oneShot == nil)
#expect(passEngineClosed.isClosed) // the in-process reaped pin
// …and the chat engine is untouched (identity, not pid).
#expect(rig.mentor.host.chat === chatBefore)
#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 engine is torn down, 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 makeScriptedRig(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)
let run = Task { await rig.model.runPass(.pass1, mentor: rig.mentor) }
let heldEngine = try #require(await pollOneShot(of: rig.mentor), "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(rig.mentor.host.oneShot == nil)
#expect(heldEngine.isClosed) // the in-process reaped pin
#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 engine closed, new
/// transport resident, 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 makeScriptedRig(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 oldEngine = try #require(rig.mentor.host.chat as? ScriptedEngine)
rig.mentor.requestRestart()
var newChat: (any EngineTransport)?
var polls = 0
while newChat == nil, polls < 250 {
if rig.mentor.phase.isReady, let chat = rig.mentor.host.chat, chat !== oldEngine {
newChat = chat
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
let respawned = try #require(newChat, "chat engine never re-spawned")
#expect(oldEngine.isClosed) // the in-process reaped pin
#expect(rig.mentor.host.chat === respawned) // the new engine stays resident
// 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
/// transport, still streaming) until the turn ends — the engine swap
/// happens only AFTER the turn.
@Test @MainActor func `requestRestart mid-turn defers the respawn until the turn ends`() async throws {
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let chatBefore = rig.mentor.host.chat
let oldEngine = try #require(chatBefore as? ScriptedEngine)
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 engine: the restart deferred, never mid-reply.
#expect(rig.mentor.isStreaming)
#expect(rig.mentor.host.chat === chatBefore)
rig.mentor.stopStreaming() // ends the held turn — the restart fires now
_ = await turn.value
#expect(!rig.mentor.isStreaming)
var newChat: (any EngineTransport)?
var polls = 0
while newChat == nil, polls < 250 {
if rig.mentor.phase.isReady, let chat = rig.mentor.host.chat, chat !== chatBefore {
newChat = chat
} else {
polls += 1
try await Task.sleep(nanoseconds: 20_000_000)
}
}
#expect(newChat != nil, "the deferred engine swap never happened after turn end")
#expect(oldEngine.isClosed) // the in-process reaped pin
}
// 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).
// Scenario: Keyless Nous pass readiness — From user story #175
// Given a pass surface switched to Nous Portal and hermes logged into
// the Portal (the shared auth.json session — the engine's credential;
// the .env key is optional and bills the same account credits)
// When refreshPassReadiness runs
// Then the pass reads .ready with NO key (the session agent_key stands
// in), and with no login either it names the missing key honestly.
@Test @MainActor func `nous pass readiness rides the portal login without a key`() async throws {
let mentor = MentorSessionModel()
let writer = RecordingWriter()
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .nous, model: "anthropic/claude-sonnet-5", effort: nil), nil)
mentor.passReadinessWriter = writer
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-readiness-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let authPath = dir.appendingPathComponent("auth.json").path
try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8)
mentor.portalAuthPath = authPath
await mentor.refreshPassReadiness()
#expect(mentor.readiness(for: .pass1) == .ready)
// No key and no login — the honest missing-key verdict.
mentor.portalAuthPath = dir.appendingPathComponent("missing.json").path
await mentor.refreshPassReadiness()
#expect(mentor.readiness(for: .pass1) == .missingKey(providerLabel: "Nous Portal"))
}
/// 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 makeScriptedRig()
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)
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, 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 releaseHeldLoad() (the rig's
/// 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 makeScriptedRig(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)
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 engine 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 rig's mode to hangOnPrompt BEFORE the
// pass engine spawns (each spawn reads the mode at factory time) — the
// pass prompt then HOLDS, so isStreaming is guaranteed when the parked
// load completes, and the #124 Cancel rail frees it afterwards.
rig.engines.mode = "hangOnPrompt"
let run = Task { await rig.model.runPass(.pass1, 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).
rig.engines.releaseHeldLoad()
// 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))
}