Files
museion/MuseionTests/BlindReadTests.swift
T
AlexKucera 627ecf515e
CI / ci (push) Canceled after 0s
refactor(session): extract the engine host
Engine lifecycle policy — spawn, handshake, respawn-on-crash, teardown,
and the per-surface residency rules (resident chat engine; one-shot
pass engines spawned per run, torn down at the verdict, ADR-0014) —
moves out of MentorSessionModel into EngineHost behind the
EngineTransport seam. The model keeps session + turn coordination and
stays the only observable the panes see; ACPEngineClient becomes the
seam's production adapter, and a scripted in-process engine
(ScriptedEngine) becomes the second adapter — engine-behaviour tests
(streaming, crash, cancel, restart, per-surface spawn) now run without
child processes, retiring the zsh fake-server rigs from logic tests
(#30 flake family). Exactly one real-process wire smoke per LLM
surface survives (chat two-act + parameterized pass1/pass2): the
held-turn cancel contract, hung-child SIGTERM teardown, handshake,
streamed turn, crash, restart.

One-shot teardown is structural (withOneShot closes at body end, every
exit path); the one-shot slot is claimed before the first suspension so
the at-most-one invariant holds across the spawn/handshake awaits.

Suite: 652 executed / 652 passed / 0 failed (653 argument cases),
counted from the xcresult; swiftformat idempotent, swiftlint clean on
touched files.

Closes #178
2026-11-09 18:26:16 +01:00

290 lines
12 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// BlindReadTests.swift
// MuseionTests
//
// #122: the Blind Read — a writer-triggered, whole-document A/B judgment
// (advisory). From user story #122 / decision #120. #178: the advisory
// run rides the in-process ScriptedEngines rig — the rig's spawnedProfiles
// pin which engine judged, the engines' promptLog pins what it was asked.
//
// ## Scenario: the blind judge prompt
// Given a Pass-start snapshot and the current document
// When the writer triggers a Blind Read
// Then both versions travel inline in one prompt — origin-free labels,
// randomized order — so the judge cannot tell which is which.
//
// ## Scenario: snapshot selection
// Given a piece whose Passes left snapshots in `<piece>/passes/`
// When a Blind Read triggers
// Then the newest snapshot (either pass kind) is the comparison base;
// with none, the read refuses honestly.
//
// ## Scenario: the advisory run
// Given an open piece with a snapshot and edits since
// When the writer clicks Blind Read
// Then a fresh one-shot engine on the museion profile judges, the verdict
// and a reveal row land in the transient transcript, the roster stays
// untouched, and nothing on disk changes.
//
import Foundation
@testable import Museion
import Testing
@MainActor
struct BlindReadTests {
// MARK: Scenario 1 — the blind judge prompt
@Test func `prompt carries both bodies inline in the given order`() {
let prompt = BlindRead.prompt(
snapshot: "The snapshot prose.",
current: "The current prose.",
snapshotFirst: true,
)
#expect(prompt.contains("Version A:\nThe snapshot prose."))
#expect(prompt.contains("Version B:\nThe current prose."))
}
@Test func `prompt flip swaps which version leads`() {
let prompt = BlindRead.prompt(
snapshot: "The snapshot prose.",
current: "The current prose.",
snapshotFirst: false,
)
#expect(prompt.contains("Version A:\nThe current prose."))
#expect(prompt.contains("Version B:\nThe snapshot prose."))
}
@Test func `prompt never names an origin or a path`() {
let prompt = BlindRead.prompt(
snapshot: "One body.",
current: "Another body.",
snapshotFirst: true,
)
// Blindness: the judge must not learn which version is the
// rewrite — no origin words, no file paths.
#expect(!prompt.lowercased().contains("snapshot"))
#expect(!prompt.lowercased().contains("current"))
#expect(!prompt.lowercased().contains("original"))
#expect(!prompt.lowercased().contains("revised"))
}
@Test func `prompt asks for a pick and one line why`() {
let prompt = BlindRead.prompt(snapshot: "One body.", current: "Another body.", snapshotFirst: true)
#expect(prompt.contains(#""A" or "B""#))
#expect(prompt.lowercased().contains("one line"))
}
@Test func `reveal names the mapping per kind and flip`() {
#expect(
BlindRead.reveal(kind: .pass1, snapshotFirst: true)
== "A = Pass 1 start snapshot · B = current document",
)
#expect(
BlindRead.reveal(kind: .pass2, snapshotFirst: false)
== "A = current document · B = Pass 2 start snapshot",
)
}
// MARK: Scenario 2 — snapshot selection
@Test func `latest snapshot is the newest on disk either kind`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Judged\n\nThe base text.", home: home)
// Only pass-1's snapshot exists for the first read.
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "The pass-one start.", home: home)
#expect(PostStore.latestPassSnapshot(id: post.id, home: home)?.body == "The pass-one start.")
// pass-2's snapshot goes decisively newer on disk — it becomes the base.
try PostStore.snapshotPass(id: post.id, kind: .pass2, body: "The pass-two start.", home: home)
let piece = try #require(PostStore.folder(of: post.id, home: home))
let pass2 = piece.appendingPathComponent("passes/pass-2.md")
try FileManager.default.setAttributes(
[.modificationDate: Date().addingTimeInterval(60)],
ofItemAtPath: pass2.path,
)
let latest = PostStore.latestPassSnapshot(id: post.id, home: home)
#expect(latest?.kind == .pass2)
#expect(latest?.body == "The pass-two start.")
}
// MARK: Scenario 3 — the advisory run (mentor rail)
/// Open a piece with a planted snapshot and a differing buffer — the
/// blind read's given state. Returns the piece id.
@discardableResult
private func openJudgedPiece(on model: PostsModel, home: URL, snapshot: String, current: String) async throws -> String {
let post = try PostStore.writeNew(body: current, home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: snapshot, home: home)
model.select(post.id, home: home)
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
return post.id
}
/// How many `museion` (chat-profile) engines spawned — the fresh-judge
/// pin's countable (was: grep of the fake's spawn log).
private func museionSpawns(_ rig: ScriptedRig) -> Int {
rig.engines.spawnedProfiles.filter { $0 == "museion" }.count
}
@Test func `blind read judges on a fresh chat-profile engine never rostered`() async throws {
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let rosterBefore = rig.mentor.roster.count
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "# Judged\n\nNewer prose.")
let outcome = await rig.mentor.runBlindRead(
prompt: BlindRead.prompt(snapshot: "Older prose.", current: "# Judged\n\nNewer prose.", snapshotFirst: true),
pieceTitle: "Judged",
reveal: BlindRead.reveal(kind: .pass1, snapshotFirst: true),
)
#expect(outcome == .ended(stopReason: "end_turn"))
// The verdict + reveal render in the transient transcript.
#expect(textRows(of: rig.mentor).contains("Blind Read · Judged"))
#expect(textRows(of: rig.mentor).contains("A = Pass 1 start snapshot · B = current document"))
// The roster never grew — records nothing (#129 posture).
#expect(rig.mentor.roster.count == rosterBefore)
// A fresh CHAT-profile engine judged (the resident engine is the
// only other `museion` spawn; pass profiles never ran).
#expect(museionSpawns(rig) == 2)
#expect(!rig.engines.spawnedProfiles.contains { $0.contains("museion-pass") })
}
@Test func `cancelled blind read leaves no reveal`() async throws {
let rig = try makeScriptedRig(mode: "cancelOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
let outcome = await rig.mentor.runBlindRead(
prompt: "prompt",
pieceTitle: "Judged",
reveal: BlindRead.reveal(kind: .pass1, snapshotFirst: true),
)
#expect(outcome == .cancelled)
#expect(!textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
}
// MARK: Audit pins (finish-audit: the refusal gate + the Cancel rail)
@Test func `refused blind read reveals nothing`() async throws {
let rig = try makeScriptedRig(mode: "refuseOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
// A refusal still ENDS .ended — the reveal must gate on the
// stopReason (runPass's advance posture), never on the outcome
// alone. Realistic path: a 2×-document prompt can refuse on length.
let outcome = await rig.mentor.runBlindRead(
prompt: "prompt",
pieceTitle: "Judged",
reveal: BlindRead.reveal(kind: .pass1, snapshotFirst: true),
)
#expect(outcome == .ended(stopReason: "refusal"))
#expect(textRows(of: rig.mentor).contains { $0.contains("(refused the prompt)") })
#expect(!textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
}
@Test func `cancel ends a held blind read and the rail is exclusive`() async throws {
let rig = try makeScriptedRig(mode: "hangOnPrompt")
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(on: rig.model, home: rig.home, snapshot: "Older prose.", current: "Newer prose.")
let run = Task { await rig.model.blindRead(home: rig.home, mentor: rig.mentor) }
for _ in 0 ..< 250 where !rig.model.runningBlindRead {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(rig.model.runningBlindRead)
// Mutual exclusion — a pass refuses while the read owns the rail.
await rig.model.runPass(.pass1, home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("already running") == true)
// The pass bar's Cancel rail ends the held read — no reveal,
// nothing on disk.
rig.model.cancelPass(mentor: rig.mentor)
for _ in 0 ..< 250 where rig.model.runningBlindRead {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(!rig.model.runningBlindRead)
rig.mentor.shutdown() // frees the held turn if the rail regressed — bounds the await
_ = await run.value
#expect(!textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
let onDisk = try String(
contentsOf: rig.home.appendingPathComponent("projects/posts/\(rig.model.selectedPostID!)/post.md"),
encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
}
// MARK: Scenario 3 (model half) — the advisory orchestration
@Test func `blind read sends both bodies blind and records nothing`() async throws {
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
_ = try await openJudgedPiece(
on: rig.model, home: rig.home,
snapshot: "MARKER-the-older-text", current: "# Judged\n\nMARKER-the-newer-text",
)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
// The prompt carried BOTH bodies inline — and no path: the judge
// cannot learn which file is which (the engines' prompt log).
let asked = rig.engines.engines.flatMap(\.promptLog).map(\.text).joined()
#expect(asked.contains("MARKER-the-older-text"))
#expect(asked.contains("MARKER-the-newer-text"))
#expect(!asked.contains(".md"))
// The reveal landed below the verdict.
#expect(textRows(of: rig.mentor).contains { $0.contains("start snapshot") })
// Records nothing: Pass State untouched, rail idle, no error.
let onDisk = try String(
contentsOf: rig.home.appendingPathComponent("projects/posts/\(rig.model.selectedPostID!)/post.md"),
encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(rig.model.runningBlindRead == false)
#expect(rig.model.lastError == nil)
}
@Test func `blind read refuses without a snapshot or without edits`() async throws {
let rig = try makeScriptedRig()
defer { rig.mentor.shutdown() }
await rig.mentor.openSession()
let post = try PostStore.writeNew(body: "# Fresh\n\nNo pass yet.", 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)
}
// No pass ever ran — refuse, spawn nothing beyond the resident engine.
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("run a Pass") == true)
#expect(museionSpawns(rig) == 1)
// Snapshot exists but the document is unchanged since — a vacuous
// read refuses honestly.
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Fresh\n\nNo pass yet.", home: rig.home)
await rig.model.blindRead(home: rig.home, mentor: rig.mentor)
#expect(rig.model.lastError?.contains("No edits") == true)
}
/// A throwaway Home (PostLibraryTests' temp-dir pattern).
private func storeHome() throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("blindread-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
}