refactor(session): type the transcript rail
CI / ci (push) Canceled after 0s

SessionRow text rows carry (body, speaker, notice) as data — agent/
user/system plus refused/interrupted/connectionLost/kickoff/failed/
plain — typed at every append site; no stored row holds a speaker
prefix (pinned). The two wire-only classifications are sniffed once at
the append seam: a replayed pass kick-off ('Pass Pass N…') and the
engine's 'Operation interrupted:' notice. The transcript view, the
writing-session filter, and the New Post prefill switch on typed data;
rendering is identical (refusal/connection-lost rows stay agent prose
by pinned render).

Fix Card and Research Note payloads decode through one shared
ToolPayloads decoder: lenient for the transcript rail (both the nested
card-rail shape and the flat #14-era fake kept), strict for the
museion-tools MCP trust boundary with named CardErrors. Three
intentional wire tightenings at the strict entry: empty cards/notes
arrays throw instead of no-op succeeding, the camelCase
diagnosticQuestion alias is rejected (schema is snake_case), and
decode failures answer short named errors instead of DecodingError
dumps. quote/note type parity restored (present-but-wrong-type throws).
Every wire-shape fact is pinned in ToolPayloadsTests.

Full suite 653/653, swiftformat/swiftlint clean. Audit flip-verified.

Closes #177
This commit is contained in:
AlexKucera committed 2026-11-09 16:01:53 +01:00
1 parent c2eb9573db
commit d14cb40e73
18 files changed
+912 -358

No files matched your search

+125 -109
View File
@@ -2,6 +2,18 @@
// MentorSessionModel.swift
// Museion
//
// ## Scenario: typed transcript rail
// From #177
//
// Given a session transcript built from live turns and engine replay
// When rows are appended
// Then every text row carries its speaker and notice as data — no stored
// row holds a "Mentor: "/"You: " prefix — the replayed pass kick-off is
// typed at the append seam, and the transcript view, writing-session
// filter, and New Post prefill switch on typed data with identical
// rendering.
//
// M0 ACP bridge (#14): the pane's @Observable model — lazy bridge lifecycle,
// prompt streaming, fix-card render, crash → restart prompt.
// #28 (S2.3): multi-session — a persisted roster of engine-owned sessions
@@ -24,10 +36,33 @@ import Observation
import os
/// One rendered row in the pane transcript. Text + tool calls first-class,
/// the rest raw (map decision: rendering fidelity).
struct SessionRow: Identifiable {
enum Content {
case text(String)
/// the rest raw (map decision: rendering fidelity). Nonisolated (#177 S2,
/// the SessionEntry rule): a pure transcript value asserted from tests
/// off the main actor.
nonisolated struct SessionRow: Identifiable {
/// #177 (S2): who spoke a text row — the render seam's three voices.
nonisolated enum Speaker: Equatable {
case agent
case user
case system
}
/// #177 (S2): the operational notice a text row carries — pure
/// consumers (draft extraction, the warning treatment) switch on this
/// data, never on prefix matching.
nonisolated enum NoticeKind: Equatable {
case refused
case interrupted
case connectionLost
case kickoff
case failed
case plain
}
nonisolated enum Content: Equatable {
/// #177 (S2): the body is UNPREFIXED display text; speaker and
/// notice travel as data.
case text(String, Speaker, NoticeKind)
/// #24 fix: the engine's thinking for one turn — rendered collapsed,
/// never mixed into the critique text.
case thought(String)
@@ -45,8 +80,10 @@ struct SessionRow: Identifiable {
/// A Fix Card as defined by CONTEXT.md — pattern, problem, diagnostic
/// question, fix, anchor, provenance, status — riding a typed tool call
/// (ADR-0006), parsed from `rawInput` as data, never prose.
struct FixCard {
/// (ADR-0006), parsed from `rawInput` as data, never prose. Nonisolated:
/// a wire value parsed by ToolPayloads (#177) and asserted from tests
/// (SessionEntry rule). Equatable (#177 S2): typed-row equality pins.
nonisolated struct FixCard: Equatable {
var pattern: String
var problem: String
var diagnosticQuestion: String
@@ -470,7 +507,7 @@ final class MentorSessionModel {
// active session out from under a live turn — Stop would then cancel
// the wrong session.
guard !isStreaming else {
appendRow(.text("Session refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
appendRow(.text("Session refused — the mentor is mid-turn.", .system, .refused), to: activeEntry?.sessionId)
return nil
}
guard let client else { return nil }
@@ -489,7 +526,7 @@ final class MentorSessionModel {
// resume/fork append honest rows; New Session must never be a
// silent nil. (Nothing active yet → the row drops; the crash
// posture owns that path in ensureDefaultSession.)
appendRow(.text("Session refused — the engine returned no id."), to: activeEntry?.sessionId)
appendRow(.text("Session refused — the engine returned no id.", .system, .refused), to: activeEntry?.sessionId)
return nil
}
let entry = SessionEntry(sessionId: sid, name: name, pieceTitle: pieceTitle, createdAt: Date())
@@ -504,7 +541,7 @@ final class MentorSessionModel {
saveRoster()
return entry
} catch {
appendRow(.text("Session refused — \(error.localizedDescription)"), to: activeEntry?.sessionId)
appendRow(.text("Session refused — \(error.localizedDescription)", .system, .refused), to: activeEntry?.sessionId)
return nil
}
}
@@ -519,7 +556,7 @@ final class MentorSessionModel {
guard !isStreaming else {
// "Not now" refusals target the ACTIVE session — they are about
// the writer's action right now, not the entry's state.
appendRow(.text("Resume refused — the mentor is mid-turn."), to: activeEntry?.sessionId)
appendRow(.text("Resume refused — the mentor is mid-turn.", .system, .refused), to: activeEntry?.sessionId)
return false
}
guard replayingSessionId == nil else {
@@ -527,7 +564,7 @@ final class MentorSessionModel {
// second session/load in flight would divert the first's replayed
// chunks into live streaming buffers. Refuse; the winner's
// completion frees the slot and the next click just works.
appendRow(.text("Resume refused — another session is loading."), to: activeEntry?.sessionId)
appendRow(.text("Resume refused — another session is loading.", .system, .refused), to: activeEntry?.sessionId)
return false
}
do {
@@ -571,7 +608,7 @@ final class MentorSessionModel {
// The refusal belongs to the ENTRY — attributed, and visible
// on its next row click (the store is kept, not discarded).
appendRow(
.text("The engine does not know “\(entry.name)” — its history is no longer on the engine."),
.text("The engine does not know “\(entry.name)” — its history is no longer on the engine.", .system, .refused),
to: entry.sessionId,
)
return false
@@ -591,7 +628,7 @@ final class MentorSessionModel {
firePendingScopeIfRequested()
// Partial replay rows (if any) + the failure row stay in the
// ENTRY's store — attributed, visible on its next row click.
appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId)
appendRow(.text("Resume failed — \(error.localizedDescription)", .system, .failed), to: entry.sessionId)
return false
}
}
@@ -649,7 +686,7 @@ final class MentorSessionModel {
]),
)
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
appendRow(.text("Fork refused — the engine returned no new session."), to: source.sessionId)
appendRow(.text("Fork refused — the engine returned no new session.", .system, .refused), to: source.sessionId)
return nil
}
let entry = SessionEntry(
@@ -667,7 +704,7 @@ final class MentorSessionModel {
saveRoster()
return entry
} catch {
appendRow(.text("Fork failed — \(error.localizedDescription)"), to: source.sessionId)
appendRow(.text("Fork failed — \(error.localizedDescription)", .system, .failed), to: source.sessionId)
return nil
}
}
@@ -701,7 +738,7 @@ final class MentorSessionModel {
/// (fresh or replay-filled transcript) otherwise.
private func claimActive(_ entry: SessionEntry, freshTranscript: Bool = true, refusedNote: String) -> Bool {
guard !isStreaming else {
appendRow(.text(refusedNote), to: activeEntry?.sessionId)
appendRow(.text(refusedNote, .system, .refused), to: activeEntry?.sessionId)
return false
}
if freshTranscript {
@@ -831,7 +868,7 @@ extension MentorSessionModel {
// engine is gone after teardown, so the composer must refuse with
// the words visible, never silently drop the text.
guard sid != Self.passTranscriptKey else {
appendRow(.text("Pick or start a session to chat — the pass transcript is read-only."), to: sid)
appendRow(.text("Pick or start a session to chat — the pass transcript is read-only.", .system, .refused), to: sid)
return .failed
}
guard let client else { return .failed }
@@ -849,22 +886,27 @@ extension MentorSessionModel {
wireSid: sid,
key: sid,
prompt: prompt,
label: label ?? "You: \(prompt)",
// #177 (S2): the label row — an explicit label ("Compact…") is
// the system's status voice, exactly as its unprefixed render
// read before the typed rail; a plain prompt is the user
// capsule with the prompt text as the body.
labelContent: .text(label ?? prompt, label == nil ? .user : .system, .plain),
)
}
/// The ONE turn pipeline behind sendPrompt and the pass run (#137): the
/// label row, session/prompt, stopReason mapping, and the streaming-
/// buffer flush — one implementation, two engines.
/// buffer flush — one implementation, two engines. #177 (S2): the label
/// row arrives fully typed; its body is the display text alone.
private func turnCore(
client: ACPEngineClient,
wireSid: String,
key: String,
prompt: String,
label: String,
labelContent: SessionRow.Content,
) async -> TurnOutcome {
lastPrompt = prompt
appendRow(.text(label), to: key)
appendRow(labelContent, to: key)
isStreaming = true
defer {
// Flush the thinking first (it preceded the message), collapsed.
@@ -874,7 +916,8 @@ extension MentorSessionModel {
}
// Flush any streamed-but-unfinished agent text into a row.
if let pending = transcripts[key], !pending.streamingText.isEmpty {
appendRow(.text("Mentor: \(pending.streamingText)"), to: key)
let (speaker, notice) = Self.agentSpeakerNotice(pending.streamingText)
appendRow(.text(pending.streamingText, speaker, notice), to: key)
transcripts[key]?.streamingText = ""
}
isStreaming = false
@@ -894,7 +937,10 @@ extension MentorSessionModel {
// must not advance on a maybe (review: empty-stopReason bug).
guard !stopReason.isEmpty else { return .failed }
if stopReason == "refusal" {
appendRow(.text("Mentor: (refused the prompt)"), to: key)
// #177 (S2): agent voice with a refusal notice — renders as
// serif prose exactly as before; the notice lets pure
// consumers exclude it by data.
appendRow(.text("(refused the prompt)", .agent, .refused), to: key)
}
if stopReason == "cancelled" {
return .cancelled
@@ -906,7 +952,7 @@ extension MentorSessionModel {
if case .crashed = phase {
// Crash card already owns the failure surface.
} else {
appendRow(.text("Mentor: connection lost — \(error.localizedDescription)"), to: key)
appendRow(.text("connection lost — \(error.localizedDescription)", .agent, .connectionLost), to: key)
}
return .failed
}
@@ -951,7 +997,7 @@ extension MentorSessionModel {
// advance posture; a 2×-document prompt makes context-length
// refusals a realistic path).
if case let .ended(stopReason) = outcome, stopReason != "refusal" {
appendRow(.text(reveal), to: Self.passTranscriptKey)
appendRow(.text(reveal, .system, .plain), to: Self.passTranscriptKey)
}
return outcome
}
@@ -1015,21 +1061,22 @@ extension MentorSessionModel {
"mcpServers": .array([]),
]))
guard let sid = result?.objectValue?["sessionId"]?.stringValue, !sid.isEmpty else {
appendRow(.text("\(label) failed — the engine refused a session."), to: Self.passTranscriptKey)
appendRow(.text("\(label) failed — the engine refused a session.", .system, .failed), to: Self.passTranscriptKey)
return .failed
}
passWireId = sid
} catch {
appendRow(.text("\(label) failed — \(error.localizedDescription)"), to: Self.passTranscriptKey)
appendRow(.text("\(label) failed — \(error.localizedDescription)", .system, .failed), to: Self.passTranscriptKey)
return .failed
}
// Cancel clicked while the engine was spawning: stop before the
// prompt — the run ends cancelled, nothing streams.
if passCancelRequested {
appendRow(.text("\(label) cancelled."), to: Self.passTranscriptKey)
appendRow(.text("\(label) cancelled.", .system, .plain), to: Self.passTranscriptKey)
return .cancelled
}
return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey, prompt: prompt, label: label)
return await turnCore(client: pass, wireSid: passWireId ?? "", key: Self.passTranscriptKey,
prompt: prompt, labelContent: .text(label, .system, .plain))
}
/// Kill the pass engine and clear its rail — at the verdict (the defer
@@ -1131,6 +1178,36 @@ extension MentorSessionModel {
nonisolated static func baseVersion(of version: String) -> String {
version.split(separator: "+", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? version
}
/// #177 (S2): the ONE agent-text sniff, shared by the live flush
/// (turnCore) and the replayed agent chunk (handleNotification) — the
/// engine's operational "Operation interrupted:" notice is system
/// status; every other agent body is conversation. Static,
/// nonisolated — pure, test-pinned.
nonisolated static func agentSpeakerNotice(
_ body: String,
) -> (speaker: SessionRow.Speaker, notice: SessionRow.NoticeKind) {
body.hasPrefix("Operation interrupted:")
? (.system, .interrupted)
: (.agent, .plain)
}
/// #177 (S2): the replayed user turn's typed content — a pass kick-off
/// body is the system's status pill; any other body is the user's
/// capsule. Static, nonisolated — pure, test-pinned.
nonisolated static func replayedUserContent(_ body: String) -> SessionRow.Content {
isPassKickoff(body)
? .text(body, .system, .kickoff)
: .text(body, .user, .plain)
}
/// #177 (S2): a replayed pass kick-off — the engine replays the pass
/// prompt as a user turn whose body opens with PassContext's fixed
/// "Pass Pass N — <level>." line. Moved from SessionTranscriptView:
/// the sniff lives at the append seam now. Static, nonisolated — pure.
nonisolated static func isPassKickoff(_ body: String) -> Bool {
body.hasPrefix("Pass Pass ")
}
}
// MARK: - Crash, stderr, and notification decoding (same-file extension —
@@ -1178,7 +1255,9 @@ extension MentorSessionModel {
// ponytail: one row per replayed chunk — a chunked engine message
// renders as several rows; wire order stays faithful. Coalesce
// only if a real adapter chunks replayed turns.
appendRow(.text("Mentor: \(text)"), to: key)
// #177 (S2): typed at the append seam — the shared agent sniff.
let (speaker, notice) = Self.agentSpeakerNotice(text)
appendRow(.text(text, speaker, notice), to: key)
} else {
transcripts[key]?.streamingText += text
}
@@ -1193,9 +1272,11 @@ extension MentorSessionModel {
// Live: the engine echoes the user message; the label row already
// rendered. During replay there IS no rendered row — the engine
// owns the turn, so it renders (#28: user turns included).
// #177 (S2): the pass kick-off is typed AT THE APPEND SEAM — the
// one place a replayed user turn is classified.
if replaying {
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
appendRow(.text("You: \(text)"), to: key)
appendRow(Self.replayedUserContent(text), to: key)
}
case "tool_call":
appendToolCall(update, to: key)
@@ -1221,7 +1302,7 @@ extension MentorSessionModel {
// research parser; a batch that fails to parse falls through.
var candidates: [ResearchCandidate] = []
if case .array? = rawInput?.objectValue?["notes"] {
candidates = ResearchCandidate.batch(rawInput)
candidates = ToolPayloads.researchCandidates(from: rawInput)
}
if !candidates.isEmpty {
for candidate in candidates {
@@ -1229,7 +1310,7 @@ extension MentorSessionModel {
}
return
}
if let card = FixCard(rawInput: rawInput) {
if let card = ToolPayloads.fixCard(from: rawInput) {
appendRow(.fixCard(card), to: sid)
return
}
@@ -1244,33 +1325,6 @@ extension MentorSessionModel {
}
}
/// Fix Card parsing from a tool call's rawInput — the fields per CONTEXT.md.
private extension FixCard {
init?(rawInput: JSONValue?) {
guard let object = rawInput?.objectValue else { return nil }
// Two shapes reach here: the museion-tools submit arguments
// {piece_path, cards: [{pattern, …, anchor: {quote}}]} (snake_case,
// the live rail) and the flat #14-era fake {pattern, problem, …}.
// Card rail first; flat shape stays for older engines/tests.
var card = object
if case let .array(items)? = object["cards"], let nested = items.first?.objectValue {
card = nested
}
// A fix-card-shaped payload carries at least pattern + problem.
guard let patternValue = card["pattern"]?.stringValue,
let problemValue = card["problem"]?.stringValue else { return nil }
pattern = patternValue
problem = problemValue
diagnosticQuestion = card["diagnosticQuestion"]?.stringValue
?? card["diagnostic_question"]?.stringValue ?? ""
fix = card["fix"]?.stringValue ?? ""
anchor = card["anchor"]?.stringValue
?? card["anchor"]?.objectValue?["quote"]?.stringValue ?? ""
provenance = card["provenance"]?.stringValue ?? "engine"
status = card["status"]?.stringValue ?? "proposed"
}
}
/// Flip a research candidate's disposition (#29 S8.3): replaces the
/// row's content in the ACTIVE session's transcript (rows are structs;
/// the store is keyed by wire sessionId). No-op on an unknown row id.
@@ -1293,63 +1347,25 @@ extension MentorSessionModel {
extension MentorSessionModel {
/// The draft candidate for New Post from Session: the ACTIVE session's
/// last mentor text row, "Mentor: " prefix stripped. Feeds the ask
/// sheet's prefill.
/// last agent text row. Feeds the ask sheet's prefill.
func draftCandidateText() -> String? {
Self.draftCandidateText(in: rows)
}
/// The pure extraction (test seam): scan backwards — the LAST mentor
/// text row wins; user rows and thought/card/research/raw rows never
/// prefill. Blank bodies are skipped so a whitespace leftover can't
/// blank the prefill while an earlier real reply still exists.
/// The pure extraction (test seam): scan backwards — the LAST agent
/// conversation row (.agent, .plain) wins; user rows, noticed agent
/// rows (refusals, connection losses — data, not prefixes), and
/// thought/card/research/raw rows never prefill. Blank bodies are
/// skipped so a whitespace leftover can't blank the prefill while an
/// earlier real reply still exists.
static func draftCandidateText(in rows: [SessionRow]) -> String? {
for row in rows.reversed() {
guard case let .text(text) = row.content, text.hasPrefix("Mentor: ") else { continue }
// ponytail: refusal/connection rows share the display prefix —
// excluded by their known shapes until SessionRow carries speaker
// identity (an enum reshape is its own ticket).
if text.hasPrefix("Mentor: (refused") || text.hasPrefix("Mentor: connection lost") {
continue
}
let body = text.dropFirst("Mentor: ".count).trimmingCharacters(in: .whitespacesAndNewlines)
if !body.isEmpty {
return String(body)
guard case let .text(body, .agent, .plain) = row.content else { continue }
let trimmed = body.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty {
return trimmed
}
}
return nil
}
}
/// Research-candidate batch parsing (#29): the submit_research_notes wire
/// shape {piece_path, notes: [{title, url, quote?, note?}]} — one candidate
/// PER note. Lenient: a missing piece_path, an empty/absent notes array, or
/// any note missing a NON-BLANK title/url yields NO candidates
/// (appendToolCall falls through to the raw row) — the same trim rule the
/// MCP wire enforces, so both boundaries agree (audit: a whitespace title
/// used to render an invisible-titled card and keep as `-untitled.md`).
/// Absent quote/note become "".
nonisolated extension ResearchCandidate {
static func batch(_ rawInput: JSONValue?) -> [ResearchCandidate] {
guard let object = rawInput?.objectValue,
let piecePath = object["piece_path"]?.stringValue,
case let .array(notes)? = object["notes"],
!notes.isEmpty
else { return [] }
var candidates: [ResearchCandidate] = []
for note in notes {
guard let fields = note.objectValue,
let title = fields["title"]?.stringValue, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
let url = fields["url"]?.stringValue, !url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else { return [] }
candidates.append(ResearchCandidate(
piecePath: piecePath,
title: title,
url: url,
quote: fields["quote"]?.stringValue ?? "",
note: fields["note"]?.stringValue ?? "",
))
}
return candidates
}
}