refactor(session): type the transcript rail
CI / ci (push) Canceled after 0s
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:
1 parent
c2eb9573db
commit
d14cb40e73
18 files changed
+912
-358
No files matched your search
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user