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

+19 -24
View File
@@ -364,7 +364,7 @@ struct ACPClientTests {
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let streamed = model.rows.contains { row in
if case let .text(text) = row.content {
if case let .text(text, _, _) = row.content {
return text.contains("Hello mentor.")
}
return false
@@ -382,7 +382,7 @@ struct ACPClientTests {
await model.sendPrompt("STUB-WIRE-PROMPT that must never surface", label: "Pass 1 · My Post")
var texts: [String] = []
for row in model.rows {
if case let .text(text) = row.content {
if case let .text(text, _, _) = row.content {
texts.append(text)
}
}
@@ -423,7 +423,7 @@ struct ACPClientTests {
/// #23 dogfood: the writing-session filter — prose + card events stay,
/// raw session/tool rows and thinking are debug-only.
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece", .system, .plain))))
#expect(SessionTranscriptView.isWritingRow(SessionRow(content: .fixCard(
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
))))
@@ -431,25 +431,12 @@ struct ACPClientTests {
#expect(!SessionTranscriptView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
}
/// #155 (map #153): the editorial-voice classifier — the model's speaker
/// prefixes map onto the contract's three voices (agent prose / user
/// capsule / system status box); everything else is the system's mono
/// voice (refusals, pass kick-off labels, reveals).
@Test func `speaker classifier maps prefixes onto the contract voices`() {
#expect(SessionTranscriptView.speaker(of: "Mentor: The opening earns its place.") == .agent)
#expect(SessionTranscriptView.speaker(of: "Mentor: (refused the prompt)") == .agent)
#expect(SessionTranscriptView.speaker(of: "You: What would you cut first?") == .user)
#expect(SessionTranscriptView.speaker(of: "Pass 1 · The piece") == .system)
#expect(SessionTranscriptView.speaker(of: "Session refused — the mentor is mid-turn.") == .system)
#expect(SessionTranscriptView.speaker(of: "A = Pass 1 start snapshot · B = current document") == .system)
}
/// Round-6 ui-polish (all seats): the warning row's headline/detail
/// split — speaker prefix dropped, then the first ": " separates the
/// headline from the muted detail line (no ": " → headline only).
/// split — the first ": " separates the headline from the muted detail
/// line (no ": " → headline only). #177 (S2): bodies arrive unprefixed.
@Test func `warningParts splits headline from detail`() {
let interrupted = SessionTranscriptView.warningParts(
"Mentor: Operation interrupted: waiting for model response (61.6s elapsed).",
"Operation interrupted: waiting for model response (61.6s elapsed).",
)
#expect(interrupted.headline == "Operation interrupted")
#expect(interrupted.detail == "waiting for model response (61.6s elapsed).")
@@ -458,6 +445,14 @@ struct ACPClientTests {
#expect(lost.detail == nil)
}
/// #177 (S2): the kick-off pill's display text — first line only, the
/// doubled "Pass Pass N" collapsed to "Pass N". Precondition: the body
/// of a .kickoff row (the append seam already sniffed it — the prefix
/// is unconditional here).
@Test func `kickoffDisplayText collapses to first line`() {
#expect(SessionTranscriptView.kickoffDisplayText("Pass Pass 2 — deep.\nThe full prompt never renders.") == "Pass 2 — deep.")
}
/// Round-8 ui-polish (argon#8 — calm copy): the engine's own
/// interruption detail, rephrased verbatim-safe — only the known
/// "waiting for model response (X elapsed)" phrasing rewrites; any
@@ -507,7 +502,7 @@ struct ACPClientTests {
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "refusal"))
let refused = model.rows.contains { row in
if case let .text(text) = row.content {
if case let .text(text, _, _) = row.content {
return text.contains("(refused the prompt)")
}
return false
@@ -571,14 +566,14 @@ struct ACPClientTests {
#expect(thought)
// The critique text stays clean — thinking never bleeds into it.
let critique = model.rows.contains { row in
if case let .text(text) = row.content {
return text == "Mentor: Hello mentor."
if case let .text(text, _, _) = row.content {
return text == "Hello mentor."
}
return false
}
#expect(critique)
#expect(!model.rows.contains { row in
if case let .text(text) = row.content {
if case let .text(text, _, _) = row.content {
return text.contains("weighing")
}
return false
@@ -637,7 +632,7 @@ struct ACPClientTests {
}
#expect(hasCard)
let hasText = model.rows.contains { row in
if case let .text(text) = row.content {
if case let .text(text, _, _) = row.content {
return text.contains("Hello mentor.")
}
return false
+2 -2
View File
@@ -35,9 +35,9 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them).
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, learnings pane, decay.
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle.
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests` — model orchestration: passes, blind read, per-surface engines, session lifecycle, scoped hosting.
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration: passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the fake ACP, prefix-free invariant, append-seam classifiers).
- `DeslopLintTests` (with the `DeslopLintWiringTests` member) — native lint findings, config story, emit loop.
- `EditorSessionTests`, `ReadingPresenterTests`, `ProsePresenterTests`, `FocusModeTests`, `ImportExternalTests`, `ImageIngestTests` — editor session, reading pipeline, editing-surface parity, focus math, import + image ingest.
- `OutlineTreeTests`, `OutlinePresenterTests`, `OutlineDragTests`, `EscEventProbeTests` — outliner model, projection, drag plumbing, Esc delivery probe.
+8 -25
View File
@@ -7,6 +7,14 @@
// under <piece>/cards/), scan ordering, and the learnings reader.
// Temp-home convention (PostStoreTests).
//
// ## Scenario: one tool-payload decoder (mirror — source: ToolPayloads.swift)
// From #177
//
// Given the submit_fix_cards / submit_research_notes wire shapes
// When the museion-tools MCP server and the session model's transcript rail both decode a payload
// Then both read the same ToolPayloads decoder — the MCP side throws named CardErrors on required-field
// violations, the transcript rail falls back to a raw row — and a wire-shape change fails in exactly one
// test suite.
import Foundation
@testable import Museion
@@ -77,31 +85,6 @@ struct MCPToolsTests {
#expect(FixCardStore.anchorStatus(text: "a a a", quote: "a a", occurrence: 2) == .stale)
}
@Test func `input decode defaults occurrence and rejects unknown enums`() throws {
let minimal = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}"#
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(minimal.utf8))
#expect(input.anchor.occurrence == 1)
#expect(input.diagnosticQuestion == nil)
let badLane = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"nope","emitter":"lint"}"#
#expect(throws: DecodingError.self) {
_ = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(badLane.utf8))
}
}
/// #23 follow-up: pass differentiation — `provenance.pass` rides the
/// wire; pre-schema cards (no pass key) decode to nil, never error.
@Test func `provenance pass rides the wire and old cards decode without it`() throws {
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":"#
+ #"{"piece":"posts/a","pass":2}}"#
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(wire.utf8))
#expect(input.provenance?.pass == 2)
let old = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a"}}"#
let oldInput = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(old.utf8))
#expect(oldInput.provenance?.pass == nil)
}
@Test func `submit writes snake case card file`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
+1 -1
View File
@@ -29,7 +29,7 @@ func makePassRig(mode: String = "full") throws -> (PostsModel, URL, MentorSessio
@MainActor
func textRows(of model: MentorSessionModel) -> [String] {
model.rows.compactMap {
if case let .text(text) = $0.content {
if case let .text(text, _, _) = $0.content {
text
} else {
nil
+2 -43
View File
@@ -4,7 +4,8 @@
//
// #29 (S8.1–S8.3): the research-candidate pins, own file —
// SessionLifecycleTests crossed its type-body ceiling (MCPToolsPromoteTests
// precedent). Reuses the shared fake ACP harness.
// precedent). Reuses the shared fake ACP harness. The payload SHAPE pins
// live in ToolPayloadsTests (#177); this file pins the curation behavior.
//
import Foundation
@@ -14,48 +15,6 @@ import Testing
// #29 suite: candidate parsing, curation, and replay survival.
struct ResearchCandidateTests {
/// #29 (S8.2): the batch parser — two notes → two candidates with ""
/// defaults; a missing piece_path, an empty/absent notes array, or a
/// note missing title/url yields NO candidates (the raw row owns it).
@Test func `research batch parses notes and refuses garbage`() {
let good: JSONValue = .object([
"piece_path": .string("/tmp/piece"),
"notes": .array([
.object(["title": .string("A"), "url": .string("https://a"), "quote": .string("q"), "note": .string("n")]),
.object(["title": .string("B"), "url": .string("https://b")]),
]),
])
let batch = ResearchCandidate.batch(good)
#expect(batch.count == 2)
#expect(batch[0] == ResearchCandidate(piecePath: "/tmp/piece", title: "A", url: "https://a", quote: "q", note: "n"))
#expect(batch[1].quote == "")
#expect(batch[1].note == "")
#expect(batch[1].disposition == .pending)
// Garbage: no piece_path / empty notes / absent notes / note missing url / not an object.
#expect(ResearchCandidate.batch(.object([
"notes": .array([.object(["title": .string("A"), "url": .string("https://a")])]),
])).isEmpty)
#expect(ResearchCandidate.batch(.object(["piece_path": .string("/tmp/piece"), "notes": .array([])])).isEmpty)
#expect(ResearchCandidate.batch(.object(["piece_path": .string("/tmp/piece")])).isEmpty)
#expect(ResearchCandidate.batch(.object([
"piece_path": .string("/tmp/piece"),
"notes": .array([.object(["title": .string("A")])]),
])).isEmpty)
// Audit pin: whitespace-only title/url are the wire's refusal too —
// both boundaries must agree (an invisible-titled card used to be
// keepable as `-untitled.md`).
#expect(ResearchCandidate.batch(.object([
"piece_path": .string("/tmp/piece"),
"notes": .array([.object(["title": .string(" "), "url": .string("https://a")])]),
])).isEmpty)
#expect(ResearchCandidate.batch(.object([
"piece_path": .string("/tmp/piece"),
"notes": .array([.object(["title": .string("A"), "url": .string(" ")])]),
])).isEmpty)
#expect(ResearchCandidate.batch(nil).isEmpty)
}
/// #29 AC (S8.2): candidates live in their session — resume
/// re-materializes them from the replayed transcript (engine-owned
/// cargo). The planted session's history carries one research tool call
+28 -22
View File
@@ -132,14 +132,19 @@ struct SessionLifecycleTests {
}
let replayed = mentor.transcriptRows(of: resumedEntry)
#expect(settled)
#expect(texts(in: replayed).first == "You: earlier ask")
// #177 (S2): the replayed rows land typed at the append seam — a
// plain replayed user turn is (.user, .plain), the agent chunk
// (.agent, .plain); the stored bodies are unprefixed.
#expect(replayed.contains { $0.content == .text("earlier ask", .user, .plain) })
#expect(replayed.contains { $0.content == .text("earlier verdict", .agent, .plain) })
#expect(texts(in: replayed).first == "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"))
#expect(texts(in: replayed).contains("earlier verdict"))
// The wire calls went out over session/load.
await drainStderr(mentor, containing: "load ghost")
#expect(mentor.stderrTail.contains { $0.contains("load ghost") })
@@ -304,7 +309,7 @@ struct SessionLifecycleTests {
// 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 {
if case let .text(text, _, _) = row.content {
return text.contains("earlier ask")
}
return false
@@ -452,7 +457,7 @@ struct SessionLifecycleTests {
// 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 {
if case let .text(text, _, _) = row.content {
return text.contains("earlier ask")
}
return false
@@ -460,17 +465,18 @@ struct SessionLifecycleTests {
}
}
// 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.
// Scenario: draft candidate — from #30 (S2.7), retyped #177 (S2). Given a
// session transcript, when the sheet prefills, then the last agent
// conversation row (.agent, .plain) is the draft candidate; noticed agent
// rows, user rows, and thought/card/research/raw rows never prefill.
// File-scope extension — type_body_length posture; same suite, same file.
@MainActor
extension SessionLifecycleTests {
@Test func `draft candidate is the last mentor text row`() {
@Test func `draft candidate is the last agent plain text row`() {
let rows: [SessionRow] = [
SessionRow(content: .text("You: help me draft this")),
SessionRow(content: .text("help me draft this", .user, .plain)),
SessionRow(content: .thought("thinking hard about angles")),
SessionRow(content: .text("Mentor: first reply")),
SessionRow(content: .text("first reply", .agent, .plain)),
SessionRow(content: .researchNote(ResearchCandidate(
piecePath: "/tmp/piece", title: "T", url: "https://x", quote: "", note: "",
))),
@@ -479,32 +485,32 @@ extension SessionLifecycleTests {
anchor: "a", provenance: "engine", status: "open",
))),
SessionRow(content: .raw(kind: "tool call", json: "{}")),
SessionRow(content: .text("Mentor: second and latest reply")),
SessionRow(content: .text("second and latest reply", .agent, .plain)),
]
#expect(MentorSessionModel.draftCandidateText(in: rows) == "second and latest reply")
}
@Test func `no mentor text yields no draft candidate`() {
@Test func `no agent plain 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: .text("hello", .user, .plain)),
SessionRow(content: .thought("hm")),
]) == nil)
// A trailing blank mentor row doesn't blank the prefill — the
// A trailing blank agent body 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: ")),
SessionRow(content: .text("the real reply", .agent, .plain)),
SessionRow(content: .text(" ", .agent, .plain)),
]) == "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.
// #177 (S2): noticed agent rows are excluded BY NOTICE — an error
// is not the draft; an earlier reply still wins, error-only nil.
#expect(MentorSessionModel.draftCandidateText(in: [
SessionRow(content: .text("Mentor: the real reply")),
SessionRow(content: .text("Mentor: connection lost — broken pipe")),
SessionRow(content: .text("the real reply", .agent, .plain)),
SessionRow(content: .text("connection lost — broken pipe", .agent, .connectionLost)),
]) == "the real reply")
#expect(MentorSessionModel.draftCandidateText(in: [
SessionRow(content: .text("Mentor: (refused the prompt)")),
SessionRow(content: .text("(refused the prompt)", .agent, .refused)),
]) == nil)
}
}
@@ -512,7 +518,7 @@ extension SessionLifecycleTests {
@MainActor
private func texts(in rows: [SessionRow]) -> [String] {
rows.compactMap {
if case let .text(text) = $0.content {
if case let .text(text, _, _) = $0.content {
text
} else {
nil
+1 -1
View File
@@ -79,7 +79,7 @@ struct SessionScopeTests {
#expect(held)
await model.scopeHostedSession(toOpenPieceTitle: "Piece A")
let refused = model.rows.contains { row in
if case let .text(text) = row.content {
if case let .text(text, _, _) = row.content {
return text.contains("Resume refused")
}
return false
+253
View File
@@ -0,0 +1,253 @@
//
// ToolPayloadsTests.swift
// MuseionTests
//
// #177 (slice 1): the tool-payload decoder's own pins — the strict MCP
// trust boundary (piece_path / cards presence, the exact CardError
// messages) and the decode facts that used to ride FixCardStore.Input's
// Codable directly (occurrence default, unknown lane, provenance.pass).
// MCPToolsTests.swift hosts the store-side pins (MCPToolsPromoteTests
// split precedent — this file keeps MCPToolsTests under its lint caps).
//
// ## Scenario: one tool-payload decoder (mirror — source: ToolPayloads.swift)
// From #177
//
// Given the submit_fix_cards / submit_research_notes wire shapes
// When the museion-tools MCP server and the session model's transcript rail both decode a payload
// Then both read the same ToolPayloads decoder — the MCP side throws named CardErrors on required-field
// violations, the transcript rail falls back to a raw row — and every wire-shape fact (lenient and strict)
// is pinned in this one suite: ToolPayloadsTests.
//
import Foundation
@testable import Museion
import Testing
/// #177: the strict submit entry's arguments as a JSONValue — one
/// card wrapped in the {piece_path, cards:[…]} envelope.
private func submitArguments(_ card: JSONValue) -> JSONValue {
.object(["piece_path": .string("/tmp/piece"), "cards": .array([card])])
}
struct ToolPayloadsTests {
/// #177: the strict decode rides ToolPayloads (one tool-payload
/// decoder) — same facts as the old direct-Codable pins: occurrence
/// defaults to 1, absent diagnostic_question decodes nil, an unknown
/// lane enum throws a CardError.
@Test func `input decode defaults occurrence and rejects unknown enums`() throws {
let minimal = submitArguments(.object([
"pattern": .string("p"),
"problem": .string("q"),
"anchor": .object(["quote": .string("x")]),
"lane": .string("mechanical"),
"emitter": .string("lint"),
]))
let args = try ToolPayloads.submitFixCards(from: minimal)
#expect(args.cards.count == 1)
#expect(args.cards[0].anchor.occurrence == 1)
#expect(args.cards[0].diagnosticQuestion == nil)
let badLane = submitArguments(.object([
"pattern": .string("p"),
"problem": .string("q"),
"anchor": .object(["quote": .string("x")]),
"lane": .string("nope"),
"emitter": .string("lint"),
]))
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitFixCards(from: badLane)
}
}
/// #23 follow-up: pass differentiation — `provenance.pass` rides the
/// wire; pre-schema cards (no pass key) decode to nil, never error.
@Test func `provenance pass rides the wire and old cards decode without it`() throws {
let wire = submitArguments(.object([
"pattern": .string("p"),
"problem": .string("q"),
"anchor": .object(["quote": .string("x")]),
"lane": .string("mechanical"),
"emitter": .string("engine"),
"provenance": .object(["piece": .string("posts/a"), "pass": .number(2)]),
]))
let input = try ToolPayloads.submitFixCards(from: wire)
#expect(input.cards[0].provenance?.pass == 2)
let old = submitArguments(.object([
"pattern": .string("p"),
"problem": .string("q"),
"anchor": .object(["quote": .string("x")]),
"lane": .string("mechanical"),
"emitter": .string("engine"),
"provenance": .object(["piece": .string("posts/a")]),
]))
let oldInput = try ToolPayloads.submitFixCards(from: old)
#expect(oldInput.cards[0].provenance?.pass == nil)
}
/// #177: the strict entry's own refusals — a missing piece_path and
/// an empty cards array are CardErrors, never empty successes (the
/// old decode accepted both; an empty submit used to mkdir an empty
/// cards/ dir).
@Test func `strict submit refuses missing piece path and empty cards`() {
let card = JSONValue.object([
"pattern": .string("p"),
"problem": .string("q"),
"anchor": .object(["quote": .string("x")]),
"lane": .string("mechanical"),
"emitter": .string("lint"),
])
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitFixCards(from: .object(["cards": .array([card])]))
}
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitFixCards(from: .object(["piece_path": .string("/tmp/piece"), "cards": .array([])]))
}
}
/// #177: the notes rail's trim rule at the strict entry — a MISSING
/// or blank title/url answers the EXACT CardErrors the wire has
/// always sent (behavior-pinned messages).
@Test func `research notes refuse blank titles and urls with the exact errors`() {
func noteArguments(_ note: JSONValue) -> JSONValue {
.object(["piece_path": .string("/tmp/piece"), "notes": .array([note])])
}
#expect {
_ = try ToolPayloads.submitResearchNotes(from: noteArguments(.object(["title": .string("T")])))
} throws: { error in
error as? FixCardStore.CardError == FixCardStore.CardError(message: "note url must not be empty")
}
#expect {
_ = try ToolPayloads.submitResearchNotes(from: noteArguments(.object([
"title": .string(" "), "url": .string("https://example.org"),
])))
} throws: { error in
error as? FixCardStore.CardError == FixCardStore.CardError(message: "note title must not be empty")
}
}
/// #177: the notes rail's ENVELOPE refusals — a missing piece_path, a
/// missing notes array, and an empty notes array are CardErrors (the
/// old decode answered `{"received": 0}` to an empty array).
@Test func `strict research submit refuses missing piece path and empty notes`() throws {
let note = JSONValue.object(["title": .string("T"), "url": .string("https://a")])
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitResearchNotes(from: .object(["notes": .array([note])]))
}
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitResearchNotes(from: .object(["piece_path": .string("/tmp/piece")]))
}
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitResearchNotes(from: .object(["piece_path": .string("/tmp/piece"), "notes": .array([])]))
}
// The happy envelope: the validated count comes back (the rail is
// decode-validate only — no fields travel).
let count = try ToolPayloads.submitResearchNotes(from: .object([
"piece_path": .string("/tmp/piece"),
"notes": .array([note]),
]))
#expect(count == 1)
}
/// #177 audit: the hand-rolled type guards — a present-but-wrong-typed
/// value throws a named CardError, never a silent nil/truncation (the
/// old DecodingError's job). Also the notes rail's quote/note: a
/// non-string quote is an error at the strict boundary, not "".
@Test func `strict decode refuses wrong-typed values`() {
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitFixCards(from: submitArguments(.object([
"pattern": .string("p"), "problem": .string("q"),
"anchor": .object(["quote": .string("x"), "occurrence": .number(1.5)]),
"lane": .string("mechanical"), "emitter": .string("lint"),
])))
}
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitFixCards(from: submitArguments(.object([
"pattern": .string("p"), "problem": .string("q"),
"anchor": .object(["quote": .string("x")]),
"lane": .string("mechanical"), "emitter": .string("lint"),
"diagnostic_question": .number(3),
])))
}
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitFixCards(from: submitArguments(.object([
"pattern": .string("p"), "problem": .string("q"),
"anchor": .object(["quote": .string("x")]),
"lane": .string("mechanical"), "emitter": .string("lint"),
"provenance": .string("nope"),
])))
}
#expect(throws: FixCardStore.CardError.self) {
_ = try ToolPayloads.submitResearchNotes(from: .object([
"piece_path": .string("/tmp/piece"),
"notes": .array([.object(["title": .string("T"), "url": .string("https://a"), "quote": .number(123)])]),
]))
}
}
/// #177 audit: the lenient card rail keeps BOTH shapes — the nested
/// card-rail envelope (pinned end-to-end by ACPClientTests' fake) and
/// the flat #14-era fake shape (kept per the ticket; pinned here so
/// the branch can't silently die).
@Test func `lenient fix card accepts the flat shape`() {
let card = ToolPayloads.fixCard(from: .object([
"pattern": .string("p"),
"problem": .string("q"),
"diagnosticQuestion": .string("d"),
"fix": .string("f"),
"anchor": .string("the anchor line"),
]))
#expect(card?.pattern == "p")
#expect(card?.problem == "q")
#expect(card?.diagnosticQuestion == "d")
#expect(card?.fix == "f")
#expect(card?.anchor == "the anchor line")
#expect(card?.provenance == "engine")
#expect(card?.status == "proposed")
}
/// #29 (S8.2), #177: the LENIENT batch parser the transcript rail
/// rides — moved from ResearchCandidateTests so every wire-shape fact
/// (lenient and strict) is pinned in this one suite. Two notes → two
/// candidates with "" defaults; a missing piece_path, an empty/absent
/// notes array, or a note missing a NON-BLANK title/url yields NO
/// candidates (the raw row owns it).
@Test func `research batch parses notes and refuses garbage`() {
let good: JSONValue = .object([
"piece_path": .string("/tmp/piece"),
"notes": .array([
.object(["title": .string("A"), "url": .string("https://a"), "quote": .string("q"), "note": .string("n")]),
.object(["title": .string("B"), "url": .string("https://b")]),
]),
])
let batch = ToolPayloads.researchCandidates(from: good)
#expect(batch.count == 2)
#expect(batch[0] == ResearchCandidate(piecePath: "/tmp/piece", title: "A", url: "https://a", quote: "q", note: "n"))
#expect(batch[1].quote == "")
#expect(batch[1].note == "")
#expect(batch[1].disposition == .pending)
// Garbage: no piece_path / empty notes / absent notes / note missing url / not an object.
#expect(ToolPayloads.researchCandidates(from: .object([
"notes": .array([.object(["title": .string("A"), "url": .string("https://a")])]),
])).isEmpty)
#expect(ToolPayloads.researchCandidates(from: .object(["piece_path": .string("/tmp/piece"), "notes": .array([])])).isEmpty)
#expect(ToolPayloads.researchCandidates(from: .object(["piece_path": .string("/tmp/piece")])).isEmpty)
#expect(ToolPayloads.researchCandidates(from: .object([
"piece_path": .string("/tmp/piece"),
"notes": .array([.object(["title": .string("A")])]),
])).isEmpty)
// Audit pin: whitespace-only title/url are the wire's refusal too —
// both boundaries must agree (an invisible-titled card used to be
// keepable as `-untitled.md`).
#expect(ToolPayloads.researchCandidates(from: .object([
"piece_path": .string("/tmp/piece"),
"notes": .array([.object(["title": .string(" "), "url": .string("https://a")])]),
])).isEmpty)
#expect(ToolPayloads.researchCandidates(from: .object([
"piece_path": .string("/tmp/piece"),
"notes": .array([.object(["title": .string("A"), "url": .string(" ")])]),
])).isEmpty)
#expect(ToolPayloads.researchCandidates(from: nil).isEmpty)
}
}
+83
View File
@@ -0,0 +1,83 @@
//
// TranscriptRailTests.swift
// MuseionTests
//
// #177 (S2): the typed transcript rail's pins, own file — ACPClientTests
// crossed its type-body ceiling with them (MCPToolsPromoteTests split
// precedent; the shared fake-ACP helpers stay in ACPClientTests).
//
// ## Scenario: typed transcript rail (mirror — source: MentorSessionModel.swift)
// 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.
//
import Foundation
@testable import Museion
import Testing
struct TranscriptRailTests {
/// #177 (S2): the typed rail's type-fact pins, driven through the fake
/// ACP — a completed turn's rows carry speaker and notice as data: the
/// prompt renders as the user row (unprefixed), the streamed reply as
/// agent conversation, and NO stored body holds a speaker prefix.
@MainActor
@Test func `completed turn types rows and stores no speaker prefix`() async {
let fake = makeFakeACP(at: acpTempDir("typed-turn"))
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
await model.sendPrompt("hello mentor")
#expect(model.rows.contains { row in
row.content == .text("hello mentor", .user, .plain)
})
#expect(model.rows.contains { row in
row.content == .text("Hello mentor.", .agent, .plain)
})
// The scenario's core invariant: prefixes are display-only, never stored.
#expect(!model.rows.contains { row in
if case let .text(body, _, _) = row.content {
return body.hasPrefix("Mentor: ") || body.hasPrefix("You: ")
}
return false
})
}
/// #177 (S2): the refusal mode lands the typed refusal row — agent voice
/// with a .refused notice (renders serif prose; pure consumers exclude it
/// by data).
@MainActor
@Test func `refusal mode lands the typed agent refusal row`() async {
let fake = makeFakeACP(at: acpTempDir("typed-refusal"), mode: "refuseOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
defer { model.shutdown() }
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "refusal"))
#expect(model.rows.contains { row in
row.content == .text("(refused the prompt)", .agent, .refused)
})
}
/// #177 (S2): the append seam's pure classifiers — the pass kick-off
/// sniff (moved to the model) and the shared agent-text sniff.
@Test func `append seam classifiers type kickoff and interrupted bodies`() {
#expect(MentorSessionModel.isPassKickoff("Pass Pass 1 — bold. The rest of the prompt."))
#expect(!MentorSessionModel.isPassKickoff("Pass 1 — bold"))
#expect(!MentorSessionModel.isPassKickoff("an ordinary ask"))
// The replayed user turn's append seam: a kick-off body lands
// (.system, .kickoff); any other body (.user, .plain).
#expect(MentorSessionModel.replayedUserContent("Pass Pass 1 — bold.\nThe rest.")
== .text("Pass Pass 1 — bold.\nThe rest.", .system, .kickoff))
#expect(MentorSessionModel.replayedUserContent("an ordinary ask") == .text("an ordinary ask", .user, .plain))
#expect(MentorSessionModel.agentSpeakerNotice("Operation interrupted: waiting for model response (61.6s elapsed).")
== (speaker: .system, notice: .interrupted))
#expect(MentorSessionModel.agentSpeakerNotice("The opening earns its place.")
== (speaker: .agent, notice: .plain))
}
}