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

@@ -0,0 +1,78 @@
# #23 museion-tools MCP server — build, live dogfood, hardening
> **Date:** 2026-10-20
> **Type:** issue
> **Reference:** Gitea issue #23 (museion-tools MCP tool server)
## Goal
Ship the museion-tools MCP server (#23): a headless `--serve-mcp` binary role exposing `query_learnings` + `submit_fix_cards` over NDJSON JSON-RPC stdio, a durable per-piece fix-card store, registration into the `museion` profile at provisioning, and the card surface in the app — then fix everything live dogfooding surfaced and harden the whole diff under a three-reviewer audit.
## What Was Done
- **MCP server** (`Museion/MCPServer.swift`): `MuseionLauncher` (@main) branches `--serve-mcp` → `MCPServer.serve()` vs the app. NDJSON JSON-RPC 2.0: initialize echoes the client's `protocolVersion`, silent notifications, typed tool schemas (the submit schema IS the ADR-0006 card schema), `isError` tool failures, fflush per line. `run(lines:write:)` test seam.
- **Fix-card store** (`Museion/FixCardStore.swift`): `StoredFixCard` snake_case/ISO-8601 JSON per `<piece>/cards/<stamp>-<slug>.json`; exact-substring + 1-based occurrence anchor validation (stale lands flagged, never rejected); whole-call validate-then-write with already-written honesty; learnings reader (home 4-up, literal-plural type dirs).
- **Registration** (`ProfileProvisioner.swift`): `hermes mcp add` rail at provisioning — multiple seeded "y" lines (the real profile consumes stdin before the prompt; one "y" silently cancelled the save). Live-verified: `hermes mcp test museion-tools` → connected, 2 tools. #44 invariant amended: config.yaml only ever via the CLI rail.
- **Card surfacing**: `PostsModel.refreshCards` at rescan/open tails (FSEvents covers `cards/` writes); Fix Cards palette — a floating `Window` scene (`FixCardsWindow.swift`, 340×540, warm `DesignTokens.background`), opened from a mono "Fix Cards · N" row in the mentor pane; `provenance.pass` stamps the finding pass (schema → store → "pass N · lane · emitter" meta → persona instruction).
- **Dogfood fixes** (live passes 1+2): `promptTimeout` 1800 s for `session/prompt` (the 15 s client default abandoned live turns — "connection lost", Stop vanished with `isStreaming`); liveness spinner row while streaming; transcript fix-card tool calls collapse to one-line events; pass-persona v1.2/v1.3 (verdict references findings by title only — the card is the finding's single full statement; tools work in silence); Debug checkbox (`@AppStorage("mentorDebugRows")`, off by default) filters the transcript to prose + card events.
- **Profile hygiene**: removed the stray duplicate seed `~/.hermes/profiles/museion/skills/writing skills/` (wrong-path artifact — the source of the engine's live "skills are ambiguous" confusion); persona synced to canonical.
- **Finish-audit (3 reviewers: ponytail/security/general)**: fixed both security MEDIUMs with one `resolvePostURL` guard (file form must BE `post.md` under a `projects/`|`archive/` component — closed the JSON-drop-beside-any-file and substring-oracle holes); nested `submit_fix_cards` rawInput parsing (the flat #14-era parser never matched the live rail — card events were dead against the real engine); missing `stopReason` → `.failed`; `client!` → guard; card scan off MainActor; 1 MB stdin line cap; six ponytail trims (~−30 lines: test-helper dedup, `EditorSession.passPieceURL`/`hasResearch`, `PostsModel.title(of:)`, `jsonString` merge, ceil-div). All four behavioral fixes flip-tested (guards batch-removed → exactly the four pins failed → restored → green).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Cards persist per-piece as one JSON per card | ADR-0006 fields on disk; rides the existing FSEvents watcher; any MCP client's submissions surface |
| Palette = floating window (not popover/inspector) | Cards are consulted WHILE editing — must stay visible; `Window(id:)` scene matches the About-window pattern |
| `provenance.pass` optional Int | Pre-schema cards and foreign clients degrade gracefully (decode nil, render without tag) |
| Transcript detail → palette; verdict → titles only | Dogfood: full card info in chat doubled mental load; cut from both ends (UI + persona) |
| Debug rows off by default, `@AppStorage` toggle in pane header | Writing session ≠ debugging; model keeps every row so the toggle flips with history intact |
| Filter in the view, not the model | Debug history preserved; tests assert model rows unchanged |
| Guard shape check in `resolvePostURL` (not at tool layer) | Root-cause seam: both `submit` and `learnings` route through it; one guard closes both MEDIUMs |
| No dedup, stale-anchors-land | Prior product decisions (the writer skips repeats; the finding survives) |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| "Mentor: connection lost" mid-pass, Stop vanished, engine kept working | `session/prompt`'s response arrives when the TURN ends (minutes); the client's 15 s request default abandoned the wait → `.failed` → `isStreaming = false` | `promptTimeout` 1800 s, test-pinned `>= 600`; liveness spinner |
| Transcript showed full card JSON + verdict restated every finding | Fake-era parser expected flat shape; persona lacked the no-restating rule | Nested `cards[0]` parse + real-shape fake payload; persona v1.2 |
| Engine: "skills are ambiguous — load both" | Duplicate seed: `skills/writing skills/` beside canonical `skills/` (wrong-path artifact, additive-only seeding never cleans) | Deleted stray dir; synced canonical persona |
| Card-event pin silent against the real engine | The ACP fake baked the flat #14-era payload — tests pinned the wrong shape | Fake payload switched to the nested submit-argument shape (flip-verified) |
| 4 posts-tests failed after scan offload | Sync asserts raced the async hop-back (one poll test's FIRST expect was sync too) | `waitForCards` poll helper; tests async |
| `JSONValue` has no `arrayValue`/`.array` accessor | Hand-rolled enum — only objectValue/stringValue exist | `if case let .array(items)? = object["cards"]` pattern match |
| Oversized-line DoS | `readLine()` unbounded into JSONSerialization | 1 MB cap in `dispatch` → `-32600`; readLine buffering noted as ponytail ceiling |
| Foreign file as "piece" (JSON-drop + substring oracle) | `resolvePostURL` accepted any readable FILE | post.md-name + projects/archive-component guard, pinned both forms |
## Files Changed
| File | Change Summary |
|------|----------------|
| `Museion/MCPServer.swift` | NEW — headless MCP server, launcher branch, wire contract, 1 MB line cap, jsonString serializer |
| `Museion/FixCardStore.swift` | NEW — durable card store, anchor validation, learnings reader, provenance.pass, piece-shape guard |
| `Museion/FixCardsWindow.swift` | NEW — Fix Cards palette window scene content (warm bg, pass-stamped meta, empty states) |
| `Museion/Pass.swift` | NEW — pass context stub, token estimate |
| `Museion/MuseionApp.swift` | Launcher split (`@main` moved); `fix-cards` Window scene |
| `Museion/MentorSessionModel.swift` | `promptTimeout` 1800 s; client guard; empty-stopReason → `.failed`; nested rawInput parse; thought lane |
| `Museion/MentorPaneView.swift` | Liveness row; FixCardEventRow; Debug checkbox + `isWritingRow` filter; pass-bar palette opener |
| `Museion/PostsModel.swift` | `refreshCards` (detached scan), `title(of:)`, runPass via session pass facts |
| `Museion/ProfileProvisioner.swift` | MCP registration phase (multi-"y" stdin) |
| `Museion/EngineGate.swift` | `stdin:` param + pipe-buffer ceiling comment |
| `Museion/EditorSession.swift` | `passPieceURL` / `hasResearch` shared facts |
| `Museion/PostsPaneView.swift` | Mentor column wiring (posts+home) |
| `Museion/PostStore.swift` | `snapshotPass` / `advancePassState` / `folder(of:)` support |
| `ref/writing skills/pass-persona/SKILL.md` | v1.3: card-only detail, provenance.pass stamp, tools-work-in-silence |
| `ref/writing skills/AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, root `AGENTS.md` | DOX for all of the above |
| `MuseionTests/*` (7 files) | MCP tools + wire suites, PassRunTests, posts-card tests (poll convention), provenance.pass pin, security pins, noStopReason mode, oversized-line pin |
## Open Items & Next Steps
- [ ] Registration points at the DerivedData Debug binary — after installing the app elsewhere: `hermes -p museion mcp remove museion-tools`, relaunch once (skip-when-present ceiling)
- [ ] Apply/Skip for cards is #25 (palette is show-only by design)
- [ ] runPass refusal-guard/cancel fake-mode tests — next pass-orchestration slice
- [ ] Learnings decay filtering parked until #26 defines frontmatter fields
- [ ] ADR-0006 could carry one line on caller-attested provenance (audit INFO-5)
---
*Log written by write-log skill*
+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-10-20 | issue | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) | #23 museion-tools MCP server + fix-card store, Fix Cards palette, dogfood fixes (prompt timeout, persona, debug filter), 3-reviewer audit round — 296 tests green |
| 2026-10-19 | issue | [20261019-issue123-ptacek-fold-text-landings_log.md](20261019-issue123-ptacek-fold-text-landings_log.md) | #123 card-emitting doctrine, lane/emitter terms, FC-10 mechanical exemplar landed across skills, CONTEXT, ADR-0006; deslop gap fixed at source |
| 2026-10-19 | issue | [20261019-issue115-prose-list-shortcuts_log.md](20261019-issue115-prose-list-shortcuts_log.md) | #115 prose list Tab/⇧Tab/⌥-moves + layer-contents fold chrome (draw(_:) never fires under SwiftUI hosting); 3-reviewer audit round, 239 tests green |
| 2026-10-16 | issue | [20261016-issue114-convert-to-post_log.md](20261016-issue114-convert-to-post_log.md) | #114 Convert to Post: in-place type flip + verbatim/headings-ladder ask, prose re-route via proseOverridePostID — 206 tests green (audit round included) |