CI / ci (push) Canceled after 0s
A freeform Session births a Post. "New Post" in the Sessions pane opens an ask-before sheet prefilled with the session's last mentor reply (editable, G9); ONE confirm materializes the piece under projects/posts/ stamped origin: ai - immutable frontmatter, never stats-eligible - and opens it in Posts; a failed write keeps the sheet up with the reason inline and the draft intact. writeNew gains an origin parameter (additive default .writer, every existing caller compiles). "New Brainstorm" is a session started with an opener prompt - no new machinery (beginBrainstormSession over the normal new+prompt rails). The freeform composer (input, liveness, Stop) moved from MentorPaneView into the shared SessionTranscriptView: one conversation surface, two panes - the Sessions pane stops being a read-only transcript. Drill offers (S2.8) wire as one pass-persona section (v1.4): the seeded micro-drill doctrine owns the motivation moment, the two-minute bound, the single shelf, and the vanish - session flavor, no machinery beyond S2.3. Resume now speaks the real adapter wire. Live-probed against the engine: 0.21.5 answers session/load with the id at _meta.hermes.sessionProvenance.acpSessionId and NO top-level sessionId - resumeSession accepts both shapes; every prior real-engine resume misread as "engine does not know this session". The fake ACP server answers load in the real shape (a loadReplayLegacy knob pins the older contract), so the whole resume suite guards the live wire. New pins: draft-candidate extraction (last mentor row wins; thought/ card/research/raw lanes and refusal/connection rows never prefill), ai-stamp write + immutability through overwrite, brainstorm roster + labeled opener, legacy-shape resume. Finish-audit (three reviewers, parallel) converged on the confirm() dismissal that destroyed the edited draft on a failed write - fixed with sheet-local error state (stale-refusal re-show dies with the presentation) - and surfaced the missing brainstorm and legacy-shape pins; the resume fix was flip-verified (removing the provenance fallback fails the provenance pins). Full suite green (379 tests). Closes #30
515 lines
23 KiB
Swift
515 lines
23 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
|
|
}
|
|
|
|
// Scenario: Brainstorm session — from #30 (S2.7). Given a ready engine,
|
|
// when the writer picks "New Brainstorm", then a rostered "Brainstorm"
|
|
// session activates and the mentor receives the opener — a session
|
|
// started with a prompt, no new machinery.
|
|
@Test @MainActor func `brainstorm opens a rostered session with the labeled opener`() async throws {
|
|
let (model, home, mentor) = try makePassRig()
|
|
defer { mentor.shutdown() }
|
|
await mentor.openSession()
|
|
_ = model
|
|
_ = home
|
|
|
|
let entry = try #require(await mentor.beginBrainstormSession(pieceTitle: "Draft Piece"))
|
|
|
|
// Rostered newest-first, named "Brainstorm", piece-associated, active.
|
|
#expect(mentor.roster.first?.name == "Brainstorm")
|
|
#expect(entry.pieceTitle == "Draft Piece")
|
|
#expect(mentor.activeEntry?.id == entry.id)
|
|
// The opener rides the labeled rail — the raw prompt never renders.
|
|
#expect(texts(in: mentor.transcriptRows(of: entry)).contains("Brainstorm"))
|
|
#expect(!texts(in: mentor.transcriptRows(of: entry)).contains { $0.contains("Let's brainstorm together") })
|
|
// The mentor's reply streams into the NEW session's transcript.
|
|
var streamed = false
|
|
for _ in 0 ..< 250 {
|
|
streamed = texts(in: mentor.transcriptRows(of: entry)).contains { $0.contains("Hello mentor.") }
|
|
if streamed {
|
|
break
|
|
}
|
|
try await Task.sleep(nanoseconds: 20_000_000)
|
|
}
|
|
#expect(streamed)
|
|
}
|
|
|
|
/// #30 audit pin: the real 0.21.5 wire answers load with the provenance
|
|
/// shape (pinned by every other resume test via the fake's default);
|
|
/// the OLDER top-level-sessionId contract stays accepted — the knob
|
|
/// flips the fake to that shape and the resume must still succeed.
|
|
@Test @MainActor func `resume accepts the legacy top-level sessionId shape`() async throws {
|
|
let (model, home, mentor) = try makePassRig(mode: "loadReplayLegacy")
|
|
defer { mentor.shutdown() }
|
|
await mentor.openSession()
|
|
_ = model
|
|
_ = home
|
|
|
|
let entry = try #require(await mentor.newSession(name: "Legacy", pieceTitle: nil))
|
|
let resumed = await mentor.resumeSession(entry)
|
|
#expect(resumed)
|
|
#expect(mentor.activeEntry?.id == entry.id)
|
|
}
|
|
|
|
/// #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
|
|
})
|
|
}
|
|
|
|
// Scenario: draft candidate — from #30 (S2.7). Given a session
|
|
// transcript, when the sheet prefills, then the last mentor text row is
|
|
// the draft candidate; thought/card/research/raw rows never prefill.
|
|
@Test @MainActor func `draft candidate is the last mentor text row`() {
|
|
let rows: [SessionRow] = [
|
|
SessionRow(content: .text("You: help me draft this")),
|
|
SessionRow(content: .thought("thinking hard about angles")),
|
|
SessionRow(content: .text("Mentor: first reply")),
|
|
SessionRow(content: .researchNote(ResearchCandidate(
|
|
piecePath: "/tmp/piece", title: "T", url: "https://x", quote: "", note: "",
|
|
))),
|
|
SessionRow(content: .fixCard(FixCard(
|
|
pattern: "p", problem: "pr", diagnosticQuestion: "d", fix: "f",
|
|
anchor: "a", provenance: "engine", status: "open",
|
|
))),
|
|
SessionRow(content: .raw(kind: "tool call", json: "{}")),
|
|
SessionRow(content: .text("Mentor: second and latest reply")),
|
|
]
|
|
#expect(MentorSessionModel.draftCandidateText(in: rows) == "second and latest reply")
|
|
}
|
|
|
|
@Test @MainActor func `no mentor text yields no draft candidate`() {
|
|
// Empty transcript, user-only, and non-text lanes never prefill.
|
|
#expect(MentorSessionModel.draftCandidateText(in: []) == nil)
|
|
#expect(MentorSessionModel.draftCandidateText(in: [
|
|
SessionRow(content: .text("You: hello")),
|
|
SessionRow(content: .thought("hm")),
|
|
]) == nil)
|
|
// A trailing blank mentor row doesn't blank the prefill — the
|
|
// earlier real reply is still the candidate.
|
|
#expect(MentorSessionModel.draftCandidateText(in: [
|
|
SessionRow(content: .text("Mentor: the real reply")),
|
|
SessionRow(content: .text("Mentor: ")),
|
|
]) == "the real reply")
|
|
// Refusal/connection rows share the display prefix — an error is
|
|
// not the draft; an earlier reply still wins, error-only yields nil.
|
|
#expect(MentorSessionModel.draftCandidateText(in: [
|
|
SessionRow(content: .text("Mentor: the real reply")),
|
|
SessionRow(content: .text("Mentor: connection lost — broken pipe")),
|
|
]) == "the real reply")
|
|
#expect(MentorSessionModel.draftCandidateText(in: [
|
|
SessionRow(content: .text("Mentor: (refused the prompt)")),
|
|
]) == nil)
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private func texts(in rows: [SessionRow]) -> [String] {
|
|
rows.compactMap {
|
|
if case let .text(text) = $0.content {
|
|
text
|
|
} else {
|
|
nil
|
|
}
|
|
}
|
|
}
|