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

+3 -2
View File
@@ -65,14 +65,15 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
## museion-tools MCP server
- `MCPServer.swift` — the binary's second role (headless, never AppKit). NDJSON JSON-RPC on stdio: `initialize` echoes the client's protocolVersion; notifications never answered; three tools with typed schemas — `query_learnings` (serves the visible learnings files), `submit_fix_cards` (ranked ≤10 ceiling; an over-ceiling reply carries `dropped_over_ceiling`), `submit_research_notes` (decode-validate ONLY — research is engine-owned session cargo, NOTHING is written; the only path to disk is the writer's keep). Lines over 1 MB → `-32600`; fflush after every stdout line; `run(lines:write:)` is the test seam.
- `MCPServer.swift` — the binary's second role (headless, never AppKit). NDJSON JSON-RPC on stdio: `initialize` echoes the client's protocolVersion; notifications never answered; three tools with typed schemas — `query_learnings` (serves the visible learnings files), `submit_fix_cards` (ranked ≤10 ceiling; an over-ceiling reply carries `dropped_over_ceiling`), `submit_research_notes` (decode-validate ONLY — research is engine-owned session cargo, NOTHING is written; the only path to disk is the writer's keep). Lines over 1 MB → `-32600`; fflush after every stdout line; `run(lines:write:)` is the test seam. #177: both submit tools decode through `ToolPayloads` (below) — the strict entry throws named `CardError`s (an empty cards/notes array is an error, never a silent no-op; the strict side takes snake_case only, no camelCase alias).
- `FixCardStore.swift` — `StoredFixCard` (ADR-0006 fields verbatim, snake_case, ISO dates). `submit`: the piece must resolve to a `post.md` under a `projects/`|`archive/` component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinked `cards/` dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head; `rank` stamped in submit order. `appliedText` = the pure nth-occurrence mechanical apply (nil, never a wrong-span patch); `close` flips status in place. `learnings` serves only visible (non-decayed) files. `promote`: ONE confirm = ONE Learning — the on-disk card is the truth (not-found or already-stamped throws before anything is written); symlinked learnings components refuse; the Learning is written first, then the card stamped; `learningMarkdown` is the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).
- `LearningDecay.swift` — the pass clock `learnings/pass-counts.json` (lenient read, clamped values); `passesHidden` is the ONE visibility verdict (interval doubles per re-dismiss, capped; garbage dismiss state means VISIBLE — a malformed dismiss never hides a Learning forever); `dismiss` stamps decay in the Learning's own frontmatter behind write-path guards (traversal/hidden/symlinked/foreign-dir/already-hidden refusals).
- `ToolPayloads.swift` — #177: THE tool-payload decoder, one home for the `submit_fix_cards`/`submit_research_notes` wire shapes; the MCP server (strict — required fields throw `CardError`) and the session model's transcript rail (lenient — the nested card-rail shape first, the flat #14-era fake shape kept; unparseable payloads fall to a raw row) both read through it. Every wire-shape fact, lenient and strict, is pinned in `ToolPayloadsTests` — a shape change fails one suite.
## ACP bridge
- `ACPEngineClient.swift` — hand-rolled thin NDJSON JSON-RPC stdio client (`hermes acp -p <profile>`; no Swift SDK exists). Wire facts: stdout = wire, stderr = logs (never parsed for state); `session/new` REQUIRES `mcpServers` (Museion sends `[]`); `session/cancel` is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire `onCrash` exactly once (latched); `close()` = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored.
- `MentorSessionModel.swift` — @MainActor @Observable. Lazy spawn on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state). Handshake compares BASE versions (the gate records the derived `0.21.5+build`, the handshake answers the base — raw equality fabricates drift; never blocks). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); fix-card tool calls parse the nested `submit_fix_cards` argument shape (flat fallback). Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot`) over their own client into a TRANSIENT unrostered transcript, torn down at the verdict (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path).
- `MentorSessionModel.swift` — @MainActor @Observable. Lazy spawn on first `openSession()` (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state). Handshake compares BASE versions (the gate records the derived `0.21.5+build`, the handshake answers the base — raw equality fabricates drift; never blocks). `sendPrompt` returns a `TurnOutcome` (a response missing `stopReason` maps to `.failed` — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed `.thought` row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through `ToolPayloads` (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry `(body, speaker, notice)` — `Speaker` agent|user|system, `NoticeKind` refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored `"Mentor: "`/`"You: "` prefix; the two wire-only classifications are sniffed ONCE at the append seam (`replayedUserContent` — a replayed "Pass Pass N…" kick-off → system/kickoff; `agentSpeakerNotice` — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; `draftCandidateText` is pure over `.agent, .plain` rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; `SessionRoster` persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides `_meta.hermes.sessionProvenance`; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level `notes` array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (`runOneShot`) over their own client into a TRANSIENT unrostered transcript, torn down at the verdict (passes never mint sessions); the turn pipeline is one shared `turnCore`; `restart()`/`requestRestart()` share `respawn()` (deferred to turn end while streaming; resumes the PRE-restart active session). `PassReadiness` per kind: `missingKey` names the provider and `runPass` guards it BEFORE the open-piece guard; `.unknown` never blocks; the nous fallback reads the Portal login (injectable path).
- `MentorPaneView.swift` — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase `ready`), shared transcript + composer (`SessionTranscriptView` — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, `PassBarView` (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; **Apply = ask-before** — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm), and research candidate cards (Keep = ask-before sheet → `writeResearchNote`; Reject = no confirm).
- Wiring: `AppGateState.mentor` is the app-scoped model; quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent — scenePhase `.inactive` would fire on plain focus loss).
+4 -1
View File
@@ -102,7 +102,10 @@ nonisolated enum FixCardStore {
/// The wire shape of one submitted card (ADR-0006 input fields only —
/// the server stamps id/submittedAt/status/anchorStatus). This is the
/// trust boundary: malformed input throws, never becomes a card.
struct Input: Decodable {
/// #177: decoded by ToolPayloads — the one tool-payload decoder; the
/// struct keeps its memberwise init for direct construction (the
/// native lint, tests) but carries no Codable conformance of its own.
struct Input {
var pattern: String
var problem: String
var diagnosticQuestion: String?
+6 -39
View File
@@ -131,10 +131,8 @@ nonisolated enum MCPServer {
]] as [[String: Any]],
])
case "submit_fix_cards":
let args = try FixCardStore.decoder.decode(
SubmitArgs.self, from: JSONSerialization.data(withJSONObject: arguments),
)
let written = try FixCardStore.submit(piecePath: args.piecePath, cards: args.cards)
let (piecePath, cards) = try ToolPayloads.submitFixCards(from: JSONValue(arguments))
let written = try FixCardStore.submit(piecePath: piecePath, cards: cards)
var payload: [String: Any] = [
"cards": written.map {
["file": $0.file, "anchor_status": $0.card.anchorStatus.rawValue]
@@ -142,8 +140,8 @@ nonisolated enum MCPServer {
]
// The ceiling backstop tells the truth on the wire (#25 S3.2):
// cards beyond the kept ranked head were dropped — say how many.
if args.cards.count > written.count {
payload["dropped_over_ceiling"] = args.cards.count - written.count
if cards.count > written.count {
payload["dropped_over_ceiling"] = cards.count - written.count
}
return reply(id: id, result: [
"content": [[
@@ -156,21 +154,11 @@ nonisolated enum MCPServer {
// Findings are engine-owned cargo in their session; the reply
// is a received count, never storage. The ONLY path to disk is
// the writer's keep (PostStore.writeResearchNote).
let args = try FixCardStore.decoder.decode(
ResearchNotesArgs.self, from: JSONSerialization.data(withJSONObject: arguments),
)
for note in args.notes {
guard !note.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw FixCardStore.CardError(message: "note title must not be empty")
}
guard !note.url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw FixCardStore.CardError(message: "note url must not be empty")
}
}
let received = try ToolPayloads.submitResearchNotes(from: JSONValue(arguments))
return reply(id: id, result: [
"content": [[
"type": "text",
"text": jsonString(["received": args.notes.count]) ?? "{}",
"text": jsonString(["received": received]) ?? "{}",
]] as [[String: Any]],
])
default:
@@ -185,27 +173,6 @@ nonisolated enum MCPServer {
var piecePath: String
}
private struct SubmitArgs: Decodable {
var piecePath: String
var cards: [FixCardStore.Input]
}
/// #29 (S8.1): one candidate source-note — quote/note optional on the
/// wire (they arrive as "" at the keep write when absent).
private struct ResearchNoteArgs: Decodable {
var title: String
var url: String
var quote: String?
var note: String?
}
/// #29 (S8.1): the research rail's wire shape — ONE shape, no legacy
/// fallback; a missing field fails decode = the trust boundary.
private struct ResearchNotesArgs: Decodable {
var piecePath: String
var notes: [ResearchNoteArgs]
}
// MARK: - Tools
/// The tools (#23 cards + learnings; #29 the research rail). The submit
+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
}
}
+41 -88
View File
@@ -169,68 +169,18 @@ struct SessionTranscriptView: View {
}
}
/// #155: the editorial-voice classifier — the model's text rows carry
/// speaker prefixes ("Mentor: ", "You: "); the render seam maps them
/// onto the contract's three voices. Everything else (refusals, pass
/// kick-off labels, reveals) is the system's mono voice. Static,
/// nonisolated — pure, testable from any context.
/// Round-1 polish: engine-emitted operational notices (interruptions)
/// and replayed pass kick-offs are STATUS, not conversation — they map
/// to the system voice too (never serif prose, never a user capsule).
nonisolated static func speaker(of text: String) -> Speaker {
if text.hasPrefix("Mentor: ") {
let body = String(text.dropFirst("Mentor: ".count))
return body.hasPrefix("Operation interrupted:") ? .system : .agent
}
if text.hasPrefix("You: ") {
return isPassKickoff(String(text.dropFirst("You: ".count))) ? .system : .user
}
return .system
}
/// Round-1 polish: 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. Static, nonisolated — pure.
nonisolated static func isPassKickoff(_ body: String) -> Bool {
body.hasPrefix("Pass Pass ")
}
/// Round-1 polish: the system row's display text — a replayed pass
/// kick-off shows its FIRST LINE only (the full engine prompt stays out
/// of the UI); every other status row renders verbatim. Static,
/// nonisolated — pure, testable from any context.
///
/// Round-2 polish (r1 regression): PassContext's first line already
/// carries "Pass " + the pass name, so the raw line reads "Pass Pass
/// 2 — …" — collapse the doubled leading "Pass Pass N" to "Pass N".
nonisolated static func statusDisplayText(_ text: String) -> String {
guard text.hasPrefix("You: ") else { return text }
let body = text.dropFirst("You: ".count)
guard isPassKickoff(String(body)) else { return text }
/// #177 (S2): a replayed pass kick-off shows its FIRST LINE only (the
/// full engine prompt stays out of the UI); PassContext's first line
/// already carries "Pass " + the pass name, so the raw line reads
/// "Pass Pass 2 — …" — collapse the doubled leading "Pass Pass N" to
/// "Pass N". The row arrives typed (.system, .kickoff) from the model's
/// append seam, so the prefix is unconditional — no re-sniff here.
/// Static, nonisolated — pure, test-pinnable.
nonisolated static func kickoffDisplayText(_ body: String) -> String {
let line = String(body.prefix(while: { $0 != "\n" }))
guard line.hasPrefix("Pass Pass ") else { return line }
return "Pass " + line.dropFirst("Pass Pass ".count)
}
/// Round-2 polish (argon#24/mercury#60/sol#9): operational warnings —
/// engine-emitted interruptions, connection losses, and the model's
/// failure rows — get the restrained terracotta accent in the status
/// voice. Refusals and cancellations stay neutral (they are outcomes,
/// not failures). Static, nonisolated — pure, test-pinnable.
nonisolated static func isWarningStatus(_ text: String) -> Bool {
let body = text.hasPrefix("Mentor: ") ? String(text.dropFirst("Mentor: ".count)) : text
return body.hasPrefix("Operation interrupted")
|| body.hasPrefix("connection lost")
|| body.contains(" failed — ")
}
/// The three contract voices for a text row.
nonisolated enum Speaker {
case agent
case user
case system
}
/// The composer's Return split: plain Return sends, Shift+Return breaks
/// the line, every other chord passes through to native handling. Caps
/// Lock is masked — an exact `==` turned Shift+Return under Caps Lock
@@ -255,12 +205,15 @@ struct SessionTranscriptView: View {
@ViewBuilder
private func rowView(_ row: SessionRow, previous: SessionRow?) -> some View {
switch row.content {
case let .text(text):
switch Self.speaker(of: text) {
case let .text(body, speaker, notice):
// #177 (S2): the render seam switches on typed data — speaker and
// notice arrive from the model's append sites, never re-derived
// from stored prefixes.
switch speaker {
case .agent:
agentProse(markdownText(String(text.dropFirst("Mentor: ".count))))
agentProse(markdownText(body))
case .user:
userCapsule(String(text.dropFirst("You: ".count)))
userCapsule(body)
case .system:
// Round-7 (mercury#21): the full warning treatment (tinted
// fill + border) renders ONLY while this row is the
@@ -269,13 +222,18 @@ struct SessionTranscriptView: View {
// Round-8 (argon#8): a historical warning keeps the
// terracotta ink + glyph (see `statusBox`) — distinct,
// just not shouting.
let current = Self.isWarningStatus(text) && isLastMeaningfulRow(row)
statusBox(Self.statusDisplayText(text), current: current)
// Round-7 (argon#39): 8pt of air when the warning
// banner directly follows the pass kick-off pill —
// at the stack's uniform 18pt the pair read as one
// fused block.
.padding(.top, current && Self.isKickoffPill(previous) ? 8 : 0)
let warning = notice == .interrupted || notice == .connectionLost || notice == .failed
let current = warning && isLastMeaningfulRow(row)
statusBox(
notice == .kickoff ? Self.kickoffDisplayText(body) : body,
warning: warning,
current: current,
)
// Round-7 (argon#39): 8pt of air when the warning
// banner directly follows the pass kick-off pill —
// at the stack's uniform 18pt the pair read as one
// fused block.
.padding(.top, current && Self.isKickoffPill(previous) ? 8 : 0)
}
case let .thought(text):
// #24 dogfood fix: collapsed — a pass's thought stream runs to
@@ -350,8 +308,8 @@ struct SessionTranscriptView: View {
/// column's full width, leading edge aligned (fit-content pills and
/// full-width banners read as two glued regions).
@ViewBuilder
private func statusBox(_ text: String, current: Bool = false) -> some View {
if Self.isWarningStatus(text) {
private func statusBox(_ text: String, warning: Bool, current: Bool = false) -> some View {
if warning {
let parts = Self.warningParts(text)
WarningStatusRow(
headline: parts.headline,
@@ -615,21 +573,15 @@ private struct WarningStatusRow: View {
// NOT private: ACPClientTests pins both seams via @testable.)
extension SessionTranscriptView {
/// Round-6 (all seats): the warning row's headline/detail split — drop
/// the speaker prefix, then cut at the first ": " ("Operation
/// interrupted: waiting for model response (61.6s elapsed)." → headline
/// "Operation interrupted", detail the rest). No ": " → the whole line
/// is the headline ("connection lost"). Static, nonisolated — pure.
/// Round-6 (all seats): the warning row's headline/detail split — cut
/// at the first ": " ("Operation interrupted: waiting for model
/// response (61.6s elapsed)." → headline "Operation interrupted",
/// detail the rest). Bodies arrive UNPREFIXED (#177 typed rows). No
/// ": " → the whole line is the headline ("connection lost").
/// Static, nonisolated — pure.
nonisolated static func warningParts(_ text: String) -> (headline: String, detail: String?) {
var body = text
if body.hasPrefix("Mentor: ") {
body = String(body.dropFirst("Mentor: ".count))
}
if body.hasPrefix("You: ") {
body = String(body.dropFirst("You: ".count))
}
guard let separator = body.range(of: ": ") else { return (body, nil) }
return (String(body[..<separator.lowerBound]), String(body[separator.upperBound...]))
guard let separator = text.range(of: ": ") else { return (text, nil) }
return (String(text[..<separator.lowerBound]), String(text[separator.upperBound...]))
}
/// Round-8 (argon#8 — calm copy): the engine's own interruption detail,
@@ -666,11 +618,12 @@ private extension SessionTranscriptView {
}
/// Round-7 (argon#39): a replayed pass kick-off row — the status pill
/// a warning banner must not hug (the 8pt-air rule). Static,
/// a warning banner must not hug (the 8pt-air rule). #177 (S2):
/// keyed on the typed notice, not a stored prefix. Static,
/// nonisolated — pure.
nonisolated static func isKickoffPill(_ row: SessionRow?) -> Bool {
guard let row, case let .text(text) = row.content, text.hasPrefix("You: ") else { return false }
return isPassKickoff(String(text.dropFirst("You: ".count)))
guard let row, case .text(_, _, .kickoff) = row.content else { return false }
return true
}
}
+263
View File
@@ -0,0 +1,263 @@
//
// ToolPayloads.swift
// Museion
//
// #177 (slice 1): ONE tool-payload decoder. The submit_fix_cards and
// submit_research_notes wire shapes live here; the museion-tools MCP
// server (strict — named CardErrors at the trust boundary) and the
// session model's transcript rail (lenient — unparseable payloads fall
// through to a raw row) both read through it, so a wire-shape change
// fails in exactly one place.
//
// ## Scenario: one tool-payload decoder
// 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
/// THE tool-payload decoder (#177) — one home for the submit shapes; the
/// MCP server + session model both read through it. Nonisolated: pure
/// shape-reading over wire values, called from the headless MCP mode and
/// the MainActor transcript rail alike.
nonisolated enum ToolPayloads {
// MARK: - Transcript rail (lenient)
/// Fix Card parsing from a tool call's rawInput — the fields per
/// CONTEXT.md. nil = not card-shaped; the transcript renders a raw row.
static func fixCard(from rawInput: JSONValue?) -> FixCard? {
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 }
return FixCard(
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",
)
}
/// 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 "".
static func researchCandidates(from 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, !isBlank(title),
let url = fields["url"]?.stringValue, !isBlank(url)
else { return [] }
candidates.append(ResearchCandidate(
piecePath: piecePath,
title: title,
url: url,
quote: fields["quote"]?.stringValue ?? "",
note: fields["note"]?.stringValue ?? "",
))
}
return candidates
}
// MARK: - MCP trust boundary (strict)
/// submit_fix_cards' arguments at the trust boundary: lenient-shape
/// reading, strict requirements — piece_path required string, cards a
/// NON-empty array, per card pattern + problem + anchor.quote required
/// (occurrence optional, defaulting 1), lane/emitter constrained
/// enums, snake_case spellings per the declared schema (no camelCase
/// alias — that tolerance stays the transcript rail's). Every
/// violation throws a short human CardError — the wire carries the
/// message, never a raw DecodingError dump. Emptiness of the required
/// strings stays the store's submit validation (materialize), as
/// before — this layer is presence and shape only.
static func submitFixCards(from arguments: JSONValue) throws -> (piecePath: String, cards: [FixCardStore.Input]) {
guard let object = arguments.objectValue else {
throw FixCardStore.CardError(message: "arguments must be an object")
}
guard let piecePath = object["piece_path"]?.stringValue else {
throw FixCardStore.CardError(message: "piece_path is required")
}
guard case let .array(items)? = object["cards"] else {
throw FixCardStore.CardError(message: "cards is required")
}
guard !items.isEmpty else {
throw FixCardStore.CardError(message: "cards must not be empty")
}
let cards = try items.map { item -> FixCardStore.Input in
guard let card = item.objectValue else {
throw FixCardStore.CardError(message: "each card must be an object")
}
return try fixCardInput(from: card)
}
return (piecePath: piecePath, cards: cards)
}
/// submit_research_notes' arguments at the trust boundary: piece_path +
/// non-empty notes required; per note title + url required and
/// non-blank AFTER trimming — the EXACT CardErrors the wire has
/// always answered (behavior-pinned). quote/note are validated
/// present-but-wrong-type too (stringField), then discarded — the
/// rail is decode-validate ONLY (#29), the reply is a received count.
static func submitResearchNotes(from arguments: JSONValue) throws -> Int {
guard let object = arguments.objectValue else {
throw FixCardStore.CardError(message: "arguments must be an object")
}
guard object["piece_path"]?.stringValue != nil else {
throw FixCardStore.CardError(message: "piece_path is required")
}
guard case let .array(items)? = object["notes"] else {
throw FixCardStore.CardError(message: "notes is required")
}
guard !items.isEmpty else {
throw FixCardStore.CardError(message: "notes must not be empty")
}
for item in items {
guard let note = item.objectValue else {
throw FixCardStore.CardError(message: "each note must be an object")
}
guard let title = note["title"]?.stringValue, !isBlank(title) else {
throw FixCardStore.CardError(message: "note title must not be empty")
}
guard let url = note["url"]?.stringValue, !isBlank(url) else {
throw FixCardStore.CardError(message: "note url must not be empty")
}
_ = try stringField(note["quote"], name: "note quote")
_ = try stringField(note["note"], name: "note note")
}
return items.count
}
/// The trimmed-emptiness rule both rails enforce on note fields (and
/// the store enforces on card fields — the #6 audit's exact semantics).
private static func isBlank(_ value: String) -> Bool {
value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
/// One card object's fields: scalars + the nested anchor/provenance.
private static func fixCardInput(from card: [String: JSONValue]) throws -> FixCardStore.Input {
guard let pattern = card["pattern"]?.stringValue else {
throw FixCardStore.CardError(message: "card pattern is required")
}
guard let problem = card["problem"]?.stringValue else {
throw FixCardStore.CardError(message: "card problem is required")
}
guard let laneRaw = card["lane"]?.stringValue,
let lane = FixCardStore.StoredFixCard.Lane(rawValue: laneRaw)
else {
throw FixCardStore.CardError(message: "card lane must be mechanical or demonstration")
}
guard let emitterRaw = card["emitter"]?.stringValue,
let emitter = FixCardStore.StoredFixCard.Emitter(rawValue: emitterRaw)
else {
throw FixCardStore.CardError(message: "card emitter must be lint or engine")
}
return try FixCardStore.Input(
pattern: pattern,
problem: problem,
diagnosticQuestion: stringField(card["diagnostic_question"], name: "card diagnostic_question"),
fix: stringField(card["fix"], name: "card fix"),
anchor: cardAnchor(from: card["anchor"]),
lane: lane,
emitter: emitter,
provenance: cardProvenance(from: card["provenance"]),
)
}
/// The anchor object: quote required, occurrence optional (the wire
/// schema's default 1), context optional.
private static func cardAnchor(from value: JSONValue?) throws -> FixCardStore.StoredFixCard.Anchor {
guard let anchor = value?.objectValue else {
throw FixCardStore.CardError(message: "card anchor must be an object")
}
guard let quote = anchor["quote"]?.stringValue else {
throw FixCardStore.CardError(message: "card anchor quote is required")
}
return try FixCardStore.StoredFixCard.Anchor(
quote: quote,
occurrence: intField(anchor["occurrence"], name: "card anchor occurrence") ?? 1,
context: stringField(anchor["context"], name: "card anchor context"),
)
}
/// The optional provenance object: piece required within it, date /
/// engine / pass optional. Absent or explicit null = no provenance
/// (the old decode's decodeIfPresent read).
private static func cardProvenance(from value: JSONValue?) throws -> FixCardStore.StoredFixCard.Provenance? {
switch value {
case nil, .null:
return nil
case let .object(provenance):
guard let piece = provenance["piece"]?.stringValue else {
throw FixCardStore.CardError(message: "card provenance piece is required")
}
return try FixCardStore.StoredFixCard.Provenance(
piece: piece,
date: stringField(provenance["date"], name: "card provenance date"),
engine: stringField(provenance["engine"], name: "card provenance engine"),
pass: intField(provenance["pass"], name: "card provenance pass"),
)
default:
throw FixCardStore.CardError(message: "card provenance must be an object")
}
}
/// An optional wire string; a present-but-non-string value is a tool
/// error, never a silent nil (the old DecodingError's job).
private static func stringField(_ value: JSONValue?, name: String) throws -> String? {
switch value {
case nil, .null:
nil
case let .string(string):
string
default:
throw FixCardStore.CardError(message: "\(name) must be a string")
}
}
/// An optional wire integer; a fractional or non-number value is a
/// tool error, never a silent truncation.
private static func intField(_ value: JSONValue?, name: String) throws -> Int? {
switch value {
case nil, .null:
return nil
case let .number(number):
guard let integer = Int(exactly: number) else {
throw FixCardStore.CardError(message: "\(name) must be an integer")
}
return integer
default:
throw FixCardStore.CardError(message: "\(name) must be an integer")
}
}
}