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

+4 -1
View File
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (6415 symbols, 28172 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (6596 symbols, 30075 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -180,6 +180,8 @@ This project is indexed by GitNexus as **museion** (6415 symbols, 28172 relation
- Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30)
- Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134)
- Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33)
- A `grep -c` printing 0 exits nonzero and breaks a `&&` chain — the later suite never runs and its stale xcresult reads as the final result; run each verification gate as its own command (#177)
- Under the delegation harness's ~420 s foreground cap a cold full `xcodebuild test` dies mid-build — `build-for-testing` then `test-without-building` splits the cost and the warm suite stays under (#177)
- Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33)
- An app-launch side effect that must never fire under hosted tests splits into the guarded entry + an arm-only seam (`startLaunchCheck`/`wireAutoFire`) — the wiring is pinnable without firing real-root writes, and the model facts stay pinned where the model is directly constructible (#151)
- When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift <file>` check of the pure logic still verify honestly (#134)
@@ -201,6 +203,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-11-09 | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](docs/devlog/20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) |
| 2026-11-09 | [20261109-issue183-shrink-agentsmd_log.md](docs/devlog/20261109-issue183-shrink-agentsmd_log.md) |
| 2026-11-05 | [20261105-issue175-nous-portal-provider_log.md](docs/devlog/20261105-issue175-nous-portal-provider_log.md) |
| 2026-11-05 | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](docs/devlog/20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) |
+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")
}
}
}
+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))
}
}
@@ -0,0 +1,68 @@
# Type the transcript rail — speaker and notice kind as data, one shared tool-payload decoder
> **Date:** 2026-11-09
> **Type:** issue
> **Reference:** git.babylondreams.de/AlexKucera/museion#177
## Goal
Implement issue #177 (mentor line, step 1 of 3 from the 2026-11-09 architecture review): SessionRow's text rows carry speaker (agent/user/system) and notice kind (refused/interrupted/connectionLost/kickoff/failed/plain) as typed data instead of `"Mentor: "`/`"You: "` display prefixes; Fix Card and Research Note tool payloads decode through ONE shared decoder consumed by the museion-tools MCP server and the session model alike; the replayed pass kick-off is sniffed exactly once at the append seam; the transcript view, writing-session filter, and New Post prefill become pure consumers of typed rows; rendering identical; the self-owed debt comment in the session model dies.
## What Was Done
- **Slice 1 — one decoder** (subagent): new `Museion/ToolPayloads.swift` — the lenient transcript-rail decoders moved verbatim from MentorSessionModel's private `FixCard.init?(rawInput:)` + `ResearchCandidate.batch` (both shapes kept: nested card-rail first, flat #14-era fake fallback; both diagnostic spellings; anchor string-or-`{quote}`), plus strict `submitFixCards`/`submitResearchNotes` entries replacing MCPServer's Codable arg structs (`SubmitArgs`/`ResearchNotesArgs`/`ResearchNoteArgs` deleted; every violation throws a short named `CardError`, never a raw `DecodingError` dump). `FixCardStore.Input` dropped `Decodable` (memberwise init stays — DeslopLint + tests construct it); `FixCardStore.decoder` stays (StoredFixCard disk decode, query_learnings). `appendToolCall` rerouted through ToolPayloads (same routing order: notes-array gate → card → raw row).
- **Slice 2 — typed rail** (subagent): `SessionRow.Content.text(String, Speaker, NoticeKind)` with nonisolated nested `Speaker`/`NoticeKind` enums (SessionEntry rule; Content gained Equatable for off-actor pins). All 21 append sites typed per the pinned table (refused ×9, failed ×4 — including "Resume failed" for render parity, plain system rows, user labels unprefixed, pass labels `.system`/`.plain`). The two wire-only classifications sniffed ONCE at the append seam: `agentSpeakerNotice` ("Operation interrupted:" → system/interrupted, shared by live flush + replayed chunk) and `replayedUserContent`/`isPassKickoff` ("Pass Pass " → system/kickoff, moved from the view). `turnCore` takes one typed `labelContent` param. `draftCandidateText` pure over `.text(body, .agent, .plain)`; the ponytail debt comment + prefix-exclusion logic deleted.
- **View seam**: `speaker(of:)`, `Speaker`, `isPassKickoff`, `statusDisplayText`, `isWarningStatus` deleted from SessionTranscriptView; rowView switches on typed data; warning = notice ∈ {interrupted, connectionLost, failed}; kick-off collapse = `kickoffDisplayText` (first line + "Pass Pass "→"Pass "); `warningParts` unprefixed; `isKickoffPill` keys on `.kickoff`; the 8pt-air rule preserved.
- **Tests**: constructors/extractions updated across ACPClientTests, SessionLifecycleTests, PassRunTests, SessionScopeTests, ResearchCandidateTests; new `ToolPayloadsTests` (strict envelope + exact CardError messages + decode facts) and `TranscriptRailTests` (type facts through the fake ACP, prefix-free invariant, append-seam classifiers).
- **Implement-close review** (2 parallel reviewers): four findings fixed — ACPClientTests type-body ceiling (pins split to TranscriptRailTests), strict research-notes envelope refusals pinned, "Pass Pass " literal deduped, decoder shape pins consolidated into ToolPayloadsTests, scenario comment corrected.
- **Finish-audit** (3 parallel reviewers: ponytail/security/general): 5 LOW findings → dead `ResearchNote` struct cut (`submitResearchNotes` returns the validated count), dead kickoff guard cut, strict-boundary type parity restored (`quote`/`note` route through `stringField` — present-but-wrong-type throws), wrong-typed-values pin added, flat-shape lenient pin added. Flip-verified: guard off → pin fails (8 executed, 1 failed); restored → green.
- **DOX pass**: #177 contract facts layered into the (concurrently restructured — see Gotchas) Museion/AGENTS.md (MCPServer, ToolPayloads, MentorSessionModel bullets) and MuseionTests/AGENTS.md (suite map rows). GitNexus re-indexed.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Render-faithful typing: `(refused the prompt)` and `connection lost` rows typed `(.agent, .refused)`/`(.agent, .connectionLost)` — agent serif prose, NOT status pills | The ticket's AC says "The UI renders identically"; the agent-prose render is pinned by the old classifier test. The notices exist so pure consumers (draft extraction) exclude by data. Per-site type flip if the owner ever wants the status voice. |
| Lenient + strict as two entry points in ONE file, shape facts pinned in ONE suite | The strictness split is the trust boundary's requirement (ticket: lenient decoder "consumed by both"). The deeper single-parser merge (shared field readers for a 6-field overlap) rejected — indirection for ~6 saved lines; the drift risk the ticket named is killed by the single home + single pin suite. |
| Strict entry: empty cards/notes arrays throw; camelCase `diagnosticQuestion` alias rejected | Empty arrays were silent no-ops (an empty submit used to mkdir an empty `cards/` dir); the declared schema is snake_case-only. Wire-visible, owner-sanctioned. |
| Kick-off sniff at the replay append seam only (not in sendPrompt) | The live label row knows its provenance (`.system, .plain`); only the REPLAYED user turn needs sniffing. Accepted drift: a user literally typing a "Pass Pass …" prompt renders capsule live, pill on replay — pathological, and the new behavior is more correct. |
| `draftCandidateText` excludes non-`.plain` notices (an interrupted row no longer prefills) | Notices aren't draft prose; falls back to the last real reply. Improvement, reported. |
| Test file splits (ToolPayloadsTests, TranscriptRailTests) | The repo's file-length/type-body ceiling protocol (MCPToolsPromoteTests precedent); helpers stay internal in the founding files. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Both AGENTS.md files (later also root AGENTS.md) showed modified though every child was forbidden from touching them | A CONCURRENT foreign session restructured/compressed the AGENTS.md tree (15:25–15:36, not from this session's agents — verified via delegation transcripts, read-only) | Left the foreign restructure untouched; #177 doc facts layered on top; the three AGENTS.md files stay UNCOMMITTED (not this session's work to commit) |
| Delegation gateway flagged a "failed file edit" on MentorSessionModel | Transient patch retries ("Failed to read file" — read race), superseded by successful retries before the green build | Verified against the live transcript (last patch ok, then build/test green) and the tree state — no gap |
| `grep -cE` printing `0` exits nonzero, breaking a `&&` chain — the "final" suite never ran and a stale flip-run xcresult was read as final | `grep -c` exit semantics in chains (the finish-audit skill's own documented pitfall) | Re-ran the suite as its own command; authoritative 653/653 on the final bytes |
| Slice-1 harness runs died silently mid-build | The child harness's 420 s foreground cap killed long builds under parallel load | Child switched to `build-for-testing` + `test-without-building`; two initial failures (EditorSession debounce, UI automation) were load flakes — verified green on the definitive idle run |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/ToolPayloads.swift` | NEW — THE tool-payload decoder (lenient rail + strict MCP entries) |
| `Museion/MentorSessionModel.swift` | SessionRow typed text case + enums; 21 append sites typed; append-seam sniffs; draftCandidateText pure; debt comment gone; decoders moved out |
| `Museion/SessionTranscriptView.swift` | Render seam switches on typed data; five prefix classifiers deleted; kickoffDisplayText |
| `Museion/MCPServer.swift` | Submit tools route through ToolPayloads; Codable arg structs deleted |
| `Museion/FixCardStore.swift` | Input drops Decodable |
| `MuseionTests/ToolPayloadsTests.swift` | NEW — every wire-shape fact, strict + lenient |
| `MuseionTests/TranscriptRailTests.swift` | NEW — type facts, prefix-free invariant, append-seam classifiers |
| `MuseionTests/ACPClientTests.swift` | Seam pins updated to typed rows; #177 pins moved out |
| `MuseionTests/SessionLifecycleTests.swift` | Draft-candidate + extraction helpers on typed rows |
| `MuseionTests/PassRunTests.swift`, `MuseionTests/SessionScopeTests.swift` | Extraction helper pattern updates |
| `MuseionTests/ResearchCandidateTests.swift` | Pure shape pin moved to ToolPayloadsTests; behavior pins stay |
| `MuseionTests/MCPToolsTests.swift` | Direct-Codable pins rewritten onto ToolPayloads |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | #177 contract facts (layered onto the foreign restructure; uncommitted) |
## Open Items & Next Steps
- [ ] The three AGENTS.md files stay uncommitted (foreign session's compression + this session's layered #177 facts) — commit with that session's work
- [ ] Deferred: `query_learnings` still decodes via `FixCardStore.decoder` + Codable — fold into ToolPayloads when that tool is next touched
- [ ] Deferred: live-vs-replay kickoff consistency for literal "Pass Pass …" user prompts — accepted as designed; one-line `.kickoff` typing in `sendPrompt` if it ever matters
- [ ] #178 (extract the engine host) is blocked by this ticket — ready once #177 lands
---
*Log written by write-log skill. Verification cited: `build-for-testing` SUCCEEDED, 653/653 tests passed (xcresult), swiftformat 0/130, swiftlint zero new vs HEAD, on the exact committed bytes.*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-11-09 | issue | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | SessionRow text rows typed (speaker+notice), kick-off sniffed at append seam, one ToolPayloads decoder both rails read |
| 2026-11-09 | issue | [20261109-issue183-shrink-agentsmd_log.md](20261109-issue183-shrink-agentsmd_log.md) | AGENTS.md rails shrunk 206 KB → 36 KB — contracts and rulings kept, per-issue diaries cut; serif payload untouched (#183) |
| 2026-11-05 | issue | [20261105-issue175-nous-portal-provider_log.md](20261105-issue175-nous-portal-provider_log.md) | Fourth provider `nous`: plain chat-completions probe, session-key fallback gated to the official endpoint, keyless readiness (#175) |
| 2026-11-05 | issue | [20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md](20261105-issue171-default-home-icloud-pin-once-legacy-guard_log.md) | Fresh installs pin `<CloudDocs>/Museion` with a legacy-dir guard; injectable probe seam, 9 tests (#171) |