Files
museion/MuseionTests/PassRunTests.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

347 lines
14 KiB
Swift

//
// PassRunTests.swift
// MuseionTests
//
// #24 (S3.1): the pass orchestration — PostsModel.runPass over the
// in-process scripted engine (#178: ScriptedEngines rig at the
// EngineTransport seam, no child process; makePassRig keeps its
// (model, home, mentor) shape). Pre-pass snapshot before the engine sees
// the text, Pass State advancing only on a completed turn, order-free.
// #124: teardown defers at rig creation.
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home + model + mentor over the scripted engines
/// (makeModelHome + makeScriptedRig, one rig; the 3-tuple shape is what
/// the tests below read).
@MainActor
// swiftlint:disable:next large_tuple
func makePassRig(mode: String = "full") throws -> (PostsModel, URL, MentorSessionModel) {
let rig = try makeScriptedRig(mode: mode)
return (rig.model, rig.home, rig.mentor)
}
/// Internal (shared-helper convention): EngineLifecycleTests reads the same
/// transcript projection over its rigs.
@MainActor
func textRows(of model: MentorSessionModel) -> [String] {
model.rows.compactMap {
if case let .text(text, _, _) = $0.content {
text
} else {
nil
}
}
}
@Test @MainActor func `runPass snapshots streams and advances pass state`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() } // #124: at rig creation — the child dies with the test, however it exits
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
model.select(post.id)
// Wait for the bind rescan to surface the piece — the pass label reads
// the library's title for it (the PostsModelTests poll pattern).
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("The body under pass."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// The label renders as the user row; the wire stub never lands.
#expect(textRows(of: mentor).contains("Pass 1 · \(post.title)"))
#expect(!textRows(of: mentor).contains { $0.contains("Critique the piece") })
#expect(model.runningPass == nil)
#expect(model.lastError == nil)
// The library regroups after the (async) rescan.
for _ in 0 ..< 250 where model.posts.first(where: { $0.id == post.id })?.passState != .pass1Done {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.posts.first(where: { $0.id == post.id })?.passState == .pass1Done)
}
@Test @MainActor func `cancelled pass does not advance`() async throws {
let (model, home, mentor) = try makePassRig(mode: "cancelOnPrompt")
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Cancel Me\n\nStill first draft.", home: home)
model.select(post.id)
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
// Pre-pass is unconditional — the snapshot landed anyway.
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("Still first draft."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(model.runningPass == nil)
}
@Test @MainActor func `refused pass does not advance`() async throws {
let (model, home, mentor) = try makePassRig(mode: "refuseOnPrompt")
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Refused\n\nAlso first draft.", home: home)
model.select(post.id)
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(model.runningPass == nil)
}
@Test @MainActor func `runPass requires an open saved post`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
model.newPost() // draft staged — no folder exists
await model.runPass(.pass1, mentor: mentor)
#expect(model.lastError?.contains("post") == true)
// Nothing landed on disk — the draft never even materialized a folder.
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts").path))
}
@Test @MainActor func `second pass while one runs refuses and cancel ends it`() async throws {
let (model, home, mentor) = try makePassRig(mode: "hangOnPrompt")
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Held\n\nMid-pass.", home: home)
model.select(post.id)
let first = Task { await model.runPass(.pass1, mentor: mentor) }
for _ in 0 ..< 250 where model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.runningPass == .pass1)
await model.runPass(.pass1, mentor: mentor) // one pass at a time
#expect(model.lastError?.contains("already running") == true)
model.cancelPass(mentor: mentor) // the pass bar's Cancel rail
mentor.shutdown() // bound only — the cancel-acknowledging fake ends the turn on the notification
_ = await first.value
#expect(model.runningPass == nil)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
}
@Test @MainActor func `cancelling a held pass ends the turn cancelled with no advance`() async throws {
let (model, home, mentor) = try makePassRig(mode: "hangOnPrompt")
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Held\n\nCancel me.", home: home)
model.select(post.id)
let run = Task { await model.runPass(.pass1, mentor: mentor) }
for _ in 0 ..< 250 where model.runningPass == nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.runningPass == .pass1)
model.cancelPass(mentor: mentor) // the pass bar's Cancel rail — no teardown assist
// #124: the cancel-acknowledging fake answers the held prompt, the turn
// ends cancelled, runningPass clears. Bounded poll — an emptied Cancel
// handler fails here instead of hanging the suite.
for _ in 0 ..< 250 where model.runningPass != nil {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.runningPass == nil)
mentor.shutdown() // frees the turn if the rail regressed — bounds the await
_ = await run.value
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
}
@Test @MainActor func `pass refuses while the mentor is mid-reply`() async throws {
let (model, home, mentor) = try makePassRig(mode: "hangOnPrompt")
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Busy\n\nMentor chatting.", home: home)
model.select(post.id)
let chat = Task { await mentor.sendPrompt("just chatting") }
for _ in 0 ..< 250 where !mentor.isStreaming {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(mentor.isStreaming)
await model.runPass(.pass1, mentor: mentor)
#expect(model.lastError?.contains("mid-reply") == true)
// The guard fired before the snapshot — nothing on disk.
#expect(!FileManager.default.fileExists(
atPath: home.appendingPathComponent("projects/posts/\(post.id)/passes").path,
))
mentor.shutdown() // frees the held chat turn — bounds the await below
_ = await chat.value
}
@Test @MainActor func `pass refuses when the engine is not ready`() async throws {
let (model, home, mentor) = try makePassRig() // never opened — engine idle
defer { mentor.shutdown() }
let post = try PostStore.writeNew(body: "# Cold\n\nNo engine yet.", home: home)
model.select(post.id)
await model.runPass(.pass1, mentor: mentor)
#expect(model.lastError?.contains("isn't ready") == true)
#expect(!FileManager.default.fileExists(
atPath: home.appendingPathComponent("projects/posts/\(post.id)/passes").path,
))
}
@Test @MainActor func `dirty session flushes before the snapshot`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Flush First\n\nOriginal.", home: home)
model.select(post.id)
model.session?.edit("# Flush First\n\nEdited on the way.") // inside the debounce window
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("Edited on the way."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("Edited on the way."))
}
@Test @MainActor func `pass runs in any order from first draft`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Free Order\n\nStraight to two.", home: home)
model.select(post.id)
await model.runPass(.pass2, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
#expect(onDisk.contains("pass_state: Pass-2 Done"))
}
// MARK: First-draft stats capture (#31, S5.1)
@Test @MainActor func `pass on a writer first draft piece captures stats and still completes`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Stats Piece\n\nOne two three. Four five! Six?", home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
// Capture fired at the invocation — the five keys ride post.md…
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] != nil)
#expect(matter["stats_burstiness"] != nil)
#expect(matter["stats_type_token_ratio"] != nil)
#expect(matter["stats_sentence_variation"] != nil)
#expect(matter["stats_trigram_repetition"] != nil)
// …and the pass itself completed untouched.
#expect(onDisk.contains("pass_state: Pass-1 Done"))
#expect(model.lastError == nil)
}
@Test @MainActor func `cancelled pass still captured stats at invocation`() async throws {
let (model, home, mentor) = try makePassRig(mode: "cancelOnPrompt")
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Cancelled Stats\n\nOne two three. Four five!", home: home)
model.select(post.id)
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
// Stats fire at INVOCATION, not completion — a cancelled pass has them anyway…
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] != nil)
#expect(matter["stats_burstiness"] != nil)
// …while the Pass State never advanced.
#expect(matter["pass_state"] == "First Draft")
}
@Test @MainActor func `pass on an ai origin piece completes with no stats`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
let post = try PostStore.writeNew(body: "# AI Piece\n\nMachine-born prose.", origin: .ai, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
// The pass ran (origin alone decides, never the outcome)…
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// …but nothing was stamped — ai-origin is never stats-eligible.
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] == nil)
#expect(matter["stats_burstiness"] == nil)
}
// MARK: Native deslop lint (#6, S3.4)
@Suite("DeslopLintWiringTests")
struct DeslopLintWiringTests {
/// #6 (S3.4): the lint fires AT the invocation — stats capture and lint
/// cards both land before the engine turn, no engine round-trip.
@Test @MainActor func `a pass invocation seeds lint cards`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
let body = "# Lint Piece\n\nUtilize the index — and delve twice — notably once, and again — "
+ "and again — and once more — to clear the dash budget. Utilize it twice."
let post = try PostStore.writeNew(body: body, home: home)
model.select(post.id)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let cards = FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md"))
#expect(cards.contains { $0.emitter == .lint && $0.status == .open })
#expect(cards.contains { $0.pattern == "utilize" && $0.lane == .mechanical })
// Stats capture fired at the same invocation — both hooks, one seam.
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
let matter = Post.frontmatter(of: onDisk)
#expect(matter["stats_captured"] != nil)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
}
}