feat(mentor): museion-tools MCP server (#23)
CI / ci (push) Canceled after 0s

Headless --serve-mcp role in the app binary: NDJSON JSON-RPC on stdio
exposing query_learnings and submit_fix_cards (ADR-0006 cards,
anchor-validated; stale lands flagged, never rejected), registered
into the museion profile at provisioning. Cards persist per piece
under <piece>/cards/ and surface in a floating Fix Cards palette
with pass-stamped provenance.

Live dogfood drove the shape: session/prompt waits pass length (the
15 s request default abandoned working turns), a liveness row and a
persisted Debug checkbox (off) split writing sessions from debug
chatter, the verdict references findings by title only while the
cards carry the detail (persona v1.3 — tools work in silence), and
the #24 pass rails (pass bar, TurnOutcome seam, snapshots) ride in.

Three-reviewer audit round: piece-path shape guard closes the
JSON-drop and substring-oracle holes, nested submit rawInput parsing
(the flat parser never matched the live rail), missing stopReason
never advances a pass, 1 MB stdin cap, card scan off MainActor.
296 tests green; every behavioral fix flip-verified.

Closes #23
This commit is contained in:
AlexKucera committed 2026-10-20 12:20:54 +02:00
1 parent c2e94fd825
commit 683ddf8426
29 files changed
+2626 -169

No files matched your search

+117
View File
@@ -137,6 +137,13 @@ final class PostsModel {
/// selects; the sheet is modal in its window, and the convert itself
/// re-derives everything (flush, disk read) at answer time.
private(set) var pendingConversion: PendingConversion?
/// #24 (S3.1): the pass currently streaming over the open piece —
/// one at a time; nil = idle. Drives the pass bar's Run ↔ Cancel swap.
private(set) var runningPass: PassKind?
/// #23 (M2, slice 3): the OPEN piece's stored fix cards
/// (`<piece>/cards/*.json`, newest-first) — what any MCP client
/// submitted; nil session (draft/guest/nothing) shows none.
private(set) var openPieceCards: [FixCardStore.StoredFixCard] = []
/// Last failed-op message surfaced in the editor (nil = clean).
private(set) var lastError: String?
/// Home the watcher is bound to; also the rescan target.
@@ -199,6 +206,9 @@ final class PostsModel {
if openSession === session, let openDiskText {
openSession?.diskDidChange(diskText: openDiskText)
}
// #23: the open piece's stored fix cards ride the same rescan —
// the watcher fires on <piece>/cards/ writes too.
refreshCards(home: home)
}
// MARK: Own ops (route through the same rescan, #61)
@@ -240,6 +250,7 @@ final class PostsModel {
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil
openPieceCards = [] // #23: no open piece, no cards
}
/// #109: New Outline — newPost's draft path with an outline draft instead:
@@ -255,6 +266,7 @@ final class PostsModel {
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil
openPieceCards = [] // #23: no open piece, no cards
}
/// #92: dismiss the external guest slot, flushing pending edits (the
@@ -316,6 +328,7 @@ final class PostsModel {
pendingProject = nil
lastDraftWasOutline = false
selectedPostID = id
refreshCards(home: home) // #23: nil session — the held ask shows no cards
return
}
// The prior session was torn down above; openUnguarded's guards
@@ -556,6 +569,7 @@ final class PostsModel {
lastDraftWasOutline = false // #109: same death, same clearing
proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the guest displaces any held ask
openPieceCards = [] // #23: the guest is not a piece
externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
@@ -689,6 +703,7 @@ extension PostsModel {
outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id
wireSession()
refreshCards(home: home) // #23: the newly opened piece's cards, now
}
}
@@ -762,3 +777,105 @@ extension PostsModel {
}
}
}
// MARK: Pass orchestration (#24, S3.1)
extension PostsModel {
/// #24 (S3.1): run one structured critique pass over the OPEN piece.
/// The pre-pass snapshot lands before the engine sees the text; the
/// minimal stub (PassContext) crosses the bridge and the critique
/// streams into the mentor pane. Pass State advances ONLY when the
/// engine's turn ends normally — never on cancel, refusal, or crash,
/// and never when fix cards resolve. Passes run in any order
/// (advancePassState is monotonic).
func runPass(_ kind: PassKind, home: URL, mentor: MentorSessionModel) async {
guard runningPass == nil else {
lastError = "A pass is already running."
return
}
guard !mentor.isStreaming else {
lastError = "The mentor is mid-reply — stop it or wait."
return
}
guard mentor.phase.isReady else {
lastError = "The mentor engine isn't ready — wait for it or restart it."
return
}
// The pass targets the open Piece: a never-saved draft has no
// folder, and the external guest and a held #111 guard ask are
// not Pieces.
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
lastError = "Open a saved post to run a pass."
return
}
guard flushOrAbort(id) else { return } // the engine reads disk
do {
try PostStore.snapshotPass(id: id, kind: kind, body: session.text, home: home)
} catch {
lastError = error.localizedDescription
return
}
runningPass = kind
defer { runningPass = nil }
let stub = PassContext.stub(kind: kind, pieceURL: session.passPieceURL, hasResearch: session.hasResearch)
let outcome = await mentor.sendPrompt(stub, label: "\(kind.rawValue) · \(title(of: id))")
guard case let .ended(stopReason) = outcome, stopReason != "refusal" else {
return // cancelled / refused / failed — the transcript tells the story
}
do {
_ = try PostStore.advancePassState(id: id, kind: kind, home: home)
lastError = nil
Task { await rescan() } // the library regroups by Pass State
} catch {
lastError = error.localizedDescription
}
}
/// #24 (S3.1): the pass bar's Cancel — the existing session/cancel
/// rail stops the agent; nothing advances (runPass reads .cancelled).
func cancelPass(mentor: MentorSessionModel) {
guard runningPass != nil else { return }
mentor.stopStreaming()
}
}
// MARK: Stored fix cards (#23, M2 slice 3)
extension PostsModel {
/// #23 (M2, slice 3): re-derive `openPieceCards` from the OPEN piece's
/// `<piece>/cards/` (FixCardStore.scan — any MCP client's submissions,
/// newest-first; archive pieces resolve through folder(of:) too). The
/// nil-session rule clears: draft, external guest, held guard ask,
/// nothing open → []. Called at the rescan tail and the open
/// transitions — the piece-roots watcher already fires on cards/ writes.
func refreshCards(home: URL) {
guard let id = session?.postID, let folder = PostStore.folder(of: id, home: home) else {
openPieceCards = []
return
}
// Plain disk reads re-run on every watcher burst (typing retriggers
// rescan) — keep the I/O off MainActor, same posture as rescan's
// Post.scan. The id re-check on hop-back drops a scan that raced a
// piece switch.
Task.detached { [weak self] in
let cards = FixCardStore.scan(pieceURL: folder)
await MainActor.run { [weak self] in
guard let self, session?.postID == id else { return }
openPieceCards = cards
}
}
}
/// The piece's display title (fallback: id) — runPass, the pass bar,
/// and the Fix Cards palette share this one lookup (review: three
/// hand-copies).
func title(of id: String) -> String {
posts.first(where: { $0.id == id })?.title ?? id
}
}