Files
museion/MuseionTests/SessionLifecycleTests.swift
T
AlexKucera b02d36bb5d
CI / ci (push) Canceled after 0s
feat(mentor): research & library-light (S8) (#29)
The mentor researches mid-pass and its findings arrive as candidate
source-notes with provenance inside their Session. A third museion-
tools tool, submit_research_notes, is the typed rail (ADR-0006
posture): decode-validate only, reply {"received": N}, write NOTHING
— the session is the holding area, and keeping is the writer's act.

Candidates ride the transcript as first-class rows (researchNote):
parsed from the tool call's rawInput by payload shape — the notes
array routes before the fix-card parse, titles are display text —
one row per note, all-or-nothing per batch, the wire's whitespace
rule mirrored so both boundaries agree. Resume re-materializes them
for free: replays re-run the same parse; dispositions reset honestly
(they were never persisted — engine-owned cargo, ADR-0007).

The writer curates in place (full cards in the shared transcript, no
palette — a handful curates where it lands): Keep opens the
ask-before sheet (G9; PromoteAskSheet posture — inline refusal,
buttons kept) and ONE confirm lands one plain markdown note with
provenance into the piece's research/ via writeResearchNote — the
one folder(of:) id lookup anchors it inside this Home, a symlinked
research/ refuses, collision -2; Reject vanishes, recording nothing.
The pass stub names the rail and forbids the engine writing
candidates itself; kept notes flip hasResearch, so every later pass
sees the research/ path (S8.3 at v1 depth).

Finish-audit (three reviewers) drove the whitespace-parity and
shape-routing fixes, the ResearchNoteContent dedup, and a poll-loop
fix for the debounce rig's sidecar half that the larger suite's load
had pushed past its fixed sleep — full suite green (373 tests).

Closes #29
2026-10-22 14:06:16 +02:00

421 lines
19 KiB
Swift

//
// SessionLifecycleTests.swift
// MuseionTests
//
// #28 (S2.3): the session lifecycle model layer — pass auto-create,
// freeform new + piece association, resume of engine-owned history
// (user turns included) with an honest refusal for unknown sessions,
// fork, compact over the prompt rail, and roster persistence across
// model instances. Runs over the real client + fake ACP server
// (ACPClientTests' fake in its `loadReplay` lifecycle mode).
//
import Foundation
@testable import Museion
import Testing
@Suite("SessionLifecycleTests")
struct SessionLifecycleTests {
/// #28 AC2: the pass's session is rostered newest-first, active, and the
/// pass prompt streams into ITS transcript — the default freeform
/// session stays untouched while Pass State advances exactly as before.
@Test @MainActor func `pass auto-creates its rostered session`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
let defaultSession = try #require(mentor.activeEntry)
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", 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)
}
await model.runPass(.pass1, home: home, mentor: mentor)
// Rostered newest-first, named by convention, and active.
#expect(mentor.roster.first?.name == "Pass 1 · \(post.title)")
#expect(mentor.activeEntry == mentor.roster.first)
// The prompt streamed into ITS transcript; the wire stub never lands.
let entry = try #require(mentor.activeEntry)
#expect(texts(in: mentor.transcriptRows(of: entry)).contains("Pass 1 · \(post.title)"))
// The streamed verdict lands via a client notification Task that can
// settle just after runPass returns under load — bounded settle.
var streamed = false
for _ in 0 ..< 250 {
streamed = texts(in: mentor.transcriptRows(of: entry)).contains(where: { $0.contains("Hello mentor.") })
if streamed {
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
let rows = mentor.transcriptRows(of: entry)
#expect(streamed)
#expect(!texts(in: rows).contains { $0.contains("Critique the piece") })
// The pre-existing freeform session's transcript is untouched.
#expect(mentor.transcriptRows(of: defaultSession).isEmpty)
// Pass State advanced on the completed turn, exactly as before.
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)
}
/// #28 AC2: freeform sessions are wired session/new, rostered
/// newest-first, active; a non-nil pieceTitle rides the entry —
/// association by convention only.
@Test @MainActor func `freeform new session is rostered newest-first and active`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
#expect(!mentor.canStartSession) // never opened — nothing may start
await mentor.openSession()
#expect(mentor.canStartSession)
let free = await mentor.newSession(name: "Doctor", pieceTitle: nil)
#expect(free != nil)
#expect(mentor.roster.first == free)
#expect(mentor.activeEntry == free)
#expect(free?.pieceTitle == nil)
let titled = await mentor.newSession(name: "Notes", pieceTitle: "Essay X")
#expect(titled?.pieceTitle == "Essay X")
#expect(mentor.roster.first == titled)
// Distinct wire ids — every rostered session is its own session.
#expect(Set(mentor.roster.map(\.sessionId)).count == 3)
}
/// #28 AC1+AC4: resume replays the ENGINE's history in wire order (user
/// turns included) into the entry's transcript; a session the engine
/// does not know returns false honestly — entry stays, explanatory row,
/// nothing fabricated.
@Test @MainActor func `resume replays engine history and refuses unknown honestly`() async throws {
let rosterDir = acpTempDir("resume-roster")
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
SessionRoster.save([ghost], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("resume"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
// The rostered entry is back and active — and the default open
// already RESUMED it (#28 review fix): the engine does not know the
// ghost, so the honest refusal row landed during openSession itself.
#expect(mentor.activeEntry == ghost)
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
// The engine does not know it: false, entry stays, explanatory row.
let unknown = await mentor.resumeSession(ghost)
#expect(!unknown)
#expect(mentor.roster.contains(ghost))
#expect(texts(in: mentor.transcriptRows(of: ghost).filter { row in
if case .text = row.content {
return true
}
return false
}).contains { $0.contains("does not know") })
// A session the engine still knows: session/load, then the replayed
// history renders in wire order — user turn first, thought lane kept.
let known = await mentor.newSession(name: "Second", pieceTitle: nil)
#expect(known != nil)
let resumed = try await mentor.resumeSession(#require(known))
#expect(resumed)
#expect(mentor.activeEntry == known)
// The replayed rows ride notification Tasks — bounded settle, then
// the wire-order pins (user turn first, thought lane kept).
let resumedEntry = try #require(known)
var settled = false
for _ in 0 ..< 250 {
settled = mentor.transcriptRows(of: resumedEntry).count >= 3
if settled {
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
let replayed = mentor.transcriptRows(of: resumedEntry)
#expect(settled)
#expect(texts(in: replayed).first == "You: earlier ask")
#expect(replayed.contains { row in
if case let .thought(text) = row.content {
return text == "old thinking"
}
return false
})
#expect(texts(in: replayed).contains("Mentor: earlier verdict"))
// The wire calls went out over session/load.
#expect(mentor.stderrTail.contains { $0.contains("load ghost") })
#expect(mentor.stderrTail.contains { $0.contains("load sess-1") })
}
/// #28 AC1: fork wires session/fork, rosters '<name> (fork)' with the
/// same pieceTitle, activates it with a FRESH transcript, and leaves the
/// original untouched; an empty-string sessionId from the wire is a
/// refusal — honest row, nil return.
@Test @MainActor func `fork activates a fresh transcript and refuses unknown honestly`() async throws {
let rosterDir = acpTempDir("fork-roster")
let source = SessionEntry(sessionId: "sess-1", name: "Essay", pieceTitle: "Pt", createdAt: Date())
SessionRoster.save([source], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("fork"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
_ = await mentor.sendPrompt("hello mentor") // history in the original's transcript
let fork = await mentor.forkActiveSession()
#expect(fork?.sessionId == "F-1")
#expect(fork?.name == "Essay (fork)")
#expect(fork?.pieceTitle == "Pt") // the association travels
#expect(mentor.roster.first == fork)
#expect(mentor.activeEntry == fork)
#expect(try mentor.transcriptRows(of: #require(fork)).isEmpty) // FRESH transcript
#expect(!mentor.transcriptRows(of: source).isEmpty) // original untouched
#expect(mentor.stderrTail.contains { $0.contains("fork sess-1") })
// Refusal rig: a session the engine does not know forks into "".
let refusalDir = acpTempDir("fork-refusal")
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
SessionRoster.save([ghost], directory: refusalDir)
let refuser = MentorSessionModel(
binaryPath: makeFakeACP(at: acpTempDir("fork-refuser"), mode: "loadReplay"),
rosterDirectory: refusalDir,
)
defer { refuser.shutdown() }
await refuser.openSession()
let refused = await refuser.forkActiveSession()
#expect(refused == nil)
#expect(refuser.activeEntry == ghost) // the refusal did not switch sessions
#expect(texts(in: refuser.transcriptRows(of: ghost)).contains { $0.contains("Fork refused") })
}
/// #28 AC1: compact rides the existing sendPrompt rail — the label
/// renders, the raw slash command never does, the summary streams into
/// the transcript — and is refused while a turn streams.
@Test @MainActor func `compact sends the labeled command and is refused while streaming`() async throws {
let (model, home, mentor) = try makePassRig()
defer { mentor.shutdown() }
await mentor.openSession()
await mentor.compactActiveSession()
#expect(texts(in: mentor.rows).contains("Compact…"))
#expect(!texts(in: mentor.rows).contains { $0.contains("/compress") })
#expect(texts(in: mentor.rows).contains { $0.contains("Hello mentor.") }) // summary streamed
// Refusal rig: compact while a turn streams does nothing.
let (busy, busyHome, busyMentor) = try makePassRig(mode: "hangOnPrompt")
defer { busyMentor.shutdown() }
_ = busy
_ = busyHome
await busyMentor.openSession()
let chat = Task { await busyMentor.sendPrompt("just chatting") }
for _ in 0 ..< 250 where !busyMentor.isStreaming {
try await Task.sleep(nanoseconds: 20_000_000)
}
let before = busyMentor.rows.count
await busyMentor.compactActiveSession()
#expect(busyMentor.rows.count == before)
#expect(!texts(in: busyMentor.rows).contains("Compact…"))
busyMentor.shutdown() // frees the held turn — bounds the await below
_ = await chat.value
}
/// #28 AC4 (ownership) + review fix (the default open RESUMES): a new
/// model over the same roster directory restores every entry — the
/// roster FILE carries no transcript payload (pinned against the raw
/// JSON) — and openSession session/load's the newest entry so its
/// history replays from the engine (nothing fabricated locally).
@Test @MainActor func `roster survives relaunch transcripts do not`() async throws {
let rosterDir = acpTempDir("relaunch-roster")
let fake = makeFakeACP(at: acpTempDir("relaunch"), mode: "loadReplay")
let first = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { first.shutdown() }
await first.openSession() // creates + persists the default 'Mentor'
let notes = await first.newSession(name: "Notes", pieceTitle: "Essay X")
#expect(notes != nil)
// The ownership pin: the roster FILE holds names only — exactly the
// four entry keys, no transcript payload of any kind (ADR-0007).
let rosterURL = URL(fileURLWithPath: rosterDir).appendingPathComponent("sessions.json")
let raw = try JSONSerialization.jsonObject(with: Data(contentsOf: rosterURL))
let firstEntry = (raw as? [[String: Any]])?.first ?? [:]
#expect(Set(firstEntry.keys) == ["sessionId", "name", "pieceTitle", "createdAt"])
let second = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { second.shutdown() }
#expect(second.roster.count == 2)
#expect(second.roster.first == notes) // newest-first, all four fields equal
#expect(second.roster.last?.name == "Mentor")
#expect(second.activeEntry == nil) // nothing active before open
await second.openSession()
#expect(second.activeEntry == second.roster.first)
// The default open RESUMED (#28 review fix): the engine's replay
// filled the newest entry's transcript — user turns included — so
// prompt/fork/compact never run against unloaded state.
let rows = try second.transcriptRows(of: #require(second.activeEntry))
#expect(rows.contains { row in
if case let .text(text) = row.content {
return text.contains("earlier ask")
}
return false
})
}
/// #28 AC2, the pane's New-Session choice rail: the open piece in Posts
/// is the association target; nothing open (or no Posts) = free-floating
/// only. Pure SwiftUI layout needs no test (house rule) — this is the
/// posts-coupled helper behind the control.
@Test @MainActor func `new-session choice reads Posts' open piece`() async throws {
let (model, home) = try makeModelHome()
#expect(SessionsPaneView.openPiece(in: model) == nil) // nothing open
#expect(SessionsPaneView.openPiece(in: nil) == nil) // no Posts at all
let post = try PostStore.writeNew(body: "# Open Piece\n", 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)
}
#expect(SessionsPaneView.openPiece(in: model)?.id == post.id)
}
/// Finish-audit (converged, 3 reviewers): ONE replay slot — a second
/// resume while a session/load is in flight refuses instead of diverting
/// the first's replayed chunks into live streaming buffers.
/// `loadReplayHold` parks the load until `load-go` lands beside the
/// fake; the pre-hold "hold-load" stderr line is the in-flight
/// observable.
@Test @MainActor func `concurrent resume refuses while a replay is in flight`() async throws {
let dir = acpTempDir("hold-load")
let fake = makeFakeACP(at: dir, mode: "loadReplayHold")
let rosterDir = acpTempDir("hold-roster")
let known = SessionEntry(sessionId: "sess-9", name: "Known", pieceTitle: nil, createdAt: Date())
SessionRoster.save([known], directory: rosterDir)
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { mentor.shutdown() }
_ = Task { await mentor.openSession() } // parks inside the auto-resume's load
var inFlight = false
for _ in 0 ..< 250 {
if mentor.stderrTail.contains(where: { $0.contains("hold-load") }) {
inFlight = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(inFlight)
// The slot is taken: the second resume refuses honestly.
let other = SessionEntry(sessionId: "ghost-2", name: "Other", pieceTitle: nil, createdAt: Date())
let ok = await mentor.resumeSession(other)
#expect(!ok)
#expect(texts(in: mentor.transcriptRows(of: known)).contains { $0.contains("another session is loading") })
// Release the hold: the parked resume completes and replays.
try "go".write(toFile: (dir as NSString).appendingPathComponent("load-go"), atomically: true, encoding: .utf8)
var replayed = false
for _ in 0 ..< 250 {
if texts(in: mentor.transcriptRows(of: known)).contains(where: { $0.contains("earlier ask") }) {
replayed = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(replayed)
}
/// Finish-audit: resume refusals belong to the ENTRY — a dead row's
/// refusal lands in its own store, never in the active session's
/// transcript.
@Test @MainActor func `resume refusal is attributed to the entry not the active session`() async throws {
let rosterDir = acpTempDir("attrib-roster")
let ghost = SessionEntry(sessionId: "ghost", name: "Ghost", pieceTitle: nil, createdAt: Date())
SessionRoster.save([ghost], directory: rosterDir)
let fake = makeFakeACP(at: acpTempDir("attrib"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession() // activates ghost; its load refuses (unknown id)
let second = await mentor.newSession(name: "Second", pieceTitle: nil)
#expect(second != nil)
_ = await mentor.resumeSession(ghost) // refuses again
#expect(texts(in: mentor.transcriptRows(of: ghost)).contains { $0.contains("does not know") })
let secondEntry = try #require(second)
#expect(!texts(in: mentor.transcriptRows(of: secondEntry)).contains { $0.contains("does not know") })
}
/// Finish-audit: the creation rail refuses while a turn streams — a
/// programmatic caller must not switch the active session out from
/// under a live turn (Stop would cancel the wrong session).
@Test @MainActor func `new session refuses while a turn streams`() async throws {
let (_, _, mentor) = try makePassRig(mode: "hangOnPrompt")
defer { mentor.shutdown() }
await mentor.openSession()
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)
let created = await mentor.newSession(name: "Sneaky", pieceTitle: nil)
#expect(created == nil)
#expect(texts(in: mentor.rows).contains { $0.contains("Session refused — the mentor is mid-turn.") })
mentor.shutdown() // frees the held turn — bounds the await below
_ = await chat.value
}
/// Finish-audit: the roster file is writer-only (0600) — names carry
/// piece titles, and the default umask is group/world-readable.
@Test @MainActor func `roster file is writer only`() throws {
let rosterDir = acpTempDir("perm-roster")
SessionRoster.save([SessionEntry(sessionId: "s", name: "N", pieceTitle: "T", createdAt: Date())], directory: rosterDir)
let url = URL(fileURLWithPath: rosterDir).appendingPathComponent("sessions.json")
let perms = try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? Int
#expect(perms == 0o600)
}
/// Finish-audit: restart() REPLAYS the active transcript from the
/// engine (ADR-0007 — the engine owns the words; the pre-crash local
/// rows are replaced by the replay, not preserved).
@Test @MainActor func `restart replays the active transcript from the engine`() async throws {
let rosterDir = acpTempDir("restart-roster")
let fake = makeFakeACP(at: acpTempDir("restart"), mode: "loadReplay")
let mentor = MentorSessionModel(binaryPath: fake, rosterDirectory: rosterDir)
defer { mentor.shutdown() }
await mentor.openSession()
_ = await mentor.sendPrompt("hello") // a turn lands in the active session
#expect(try !mentor.transcriptRows(of: #require(mentor.activeEntry)).isEmpty)
if let pid = mentor.childProcessIdentifier {
kill(pid, SIGKILL) // crash the child
}
var crashed = false
for _ in 0 ..< 250 {
if case .crashed = mentor.phase {
crashed = true
break
}
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(crashed)
await mentor.restart()
// The post-restart transcript is the ENGINE's replay — the replay
// marker proves the words came from the engine, not the local copy.
let rows = try mentor.transcriptRows(of: #require(mentor.activeEntry))
#expect(rows.contains { row in
if case let .text(text) = row.content {
return text.contains("earlier ask")
}
return false
})
}
}
@MainActor
private func texts(in rows: [SessionRow]) -> [String] {
rows.compactMap {
if case let .text(text) = $0.content {
text
} else {
nil
}
}
}