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

+15 -8
View File
@@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Local Contracts
- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires).
- Entry point: `MuseionApp.swift` (`WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state). **#23:** no `@main` here — `MuseionLauncher` (MCPServer.swift) is the `@main` entry: `--serve-mcp` in argv runs the headless `museion-tools` MCP server (never touches AppKit), anything else runs `MuseionApp.main()`. One binary, two roles (ADR-0008). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires).
- `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project).
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (bumped from 26.5 with the Xcode 27 settings pass — all six project configs, tests included, stay aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
@@ -24,8 +24,9 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `<project>` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip).
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse.
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws).
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing line "Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the sessionLine truncated
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
@@ -48,10 +49,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Profile provisioning (S2.1, tickets #43–#48)
- `ProfileProvisioner.swift` — `ProfileProvisioner` (nonisolated): one idempotent pass per gate pass. Create phase: dir-check first, spawn `hermes profile create museion --no-alias --no-skills` only when missing; exit 1 + "already exists" on stdout = success (#43); errors read from stdout; a nil binary path fails the create phase cleanly (no probe fallback — the gate's winner is always handed in). Seed phase: `seed-manifest.txt` in the payload root is the inclusion list (blank/`#` lines ignored; entries validated kebab-case at the trust boundary — a traversal-shaped entry fails the copy phase instead of escaping `skills/`); per-skill dir-check, copy to temp name + rename (atomic), never open or overwrite present skills; orphaned `.`-prefixed temp dirs from an interrupted copy are swept at pass start; `.DS_Store` purged from copies. One os_log line per pass (`seeded writing skills: <name> <version>, … (N copied, M present)`) reading shipped versions from the bundled payload only; at most one os_log line per failure (phase + excerpt, #48). `ProvisioningModel` (@MainActor @Observable): runs the pass off-main, guards stacking, records `lastFailure` (phase-named copy + excerpt); failure never re-raises the gate.
- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented` = `hasFailure && gateDismissed`, where `gateDismissed` is set in the gate sheet's `onDismiss` — keying on dismissal completion avoids macOS dropping a sheet presented during another's dismissal animation); phase rawValue is the title, excerpt behind Technical details; the card snapshots the failure into `@State` so a successful Retry doesn't blank it mid-dismiss. Retry re-runs the whole pass (idempotent), Not Now (`deferFailure`) defers to the next launch's silent retry; sheet is interactiveDismissDisabled. Provisioning writes nothing to the profile config — never an `mcp_servers` entry (#44 negative invariant, test-pinned).
- `ProfileProvisioner.swift` — `ProfileProvisioner` (nonisolated): one idempotent pass per gate pass. Create phase: dir-check first, spawn `hermes profile create museion --no-alias --no-skills` only when missing; exit 1 + "already exists" on stdout = success (#43); errors read from stdout; a nil binary path fails the create phase cleanly (no probe fallback — the gate's winner is always handed in). Seed phase: `seed-manifest.txt` in the payload root is the inclusion list (blank/`#` lines ignored; entries validated kebab-case at the trust boundary — a traversal-shaped entry fails the copy phase instead of escaping `skills/`); per-skill dir-check, copy to temp name + rename (atomic), never open or overwrite present skills; orphaned `.`-prefixed temp dirs from an interrupted copy are swept at pass start; `.DS_Store` purged from copies. One os_log line per pass (`seeded writing skills: <name> <version>, … (N copied, M present)`) reading shipped versions from the bundled payload only; at most one os_log line per failure (phase + excerpt, #48). `ProvisioningModel` (@MainActor @Observable): runs the pass off-main, guards stacking, records `lastFailure` (phase-named copy + excerpt); failure never re-raises the gate. **#23 register phase:** after a seeded pass (and only when BOTH `hermesBinary` and `serverBinaryPath` are non-nil — production always has both after a gate pass; nil = the test-injection seam, skipped with one os_log line), `registerTools` runs `hermes -p museion mcp list` — "museion-tools" present → idempotent skip (a stale binary path after an app move is refreshed manually via `hermes -p museion mcp remove museion-tools` — ponytail ceiling) — else `hermes -p museion mcp add museion-tools --command <serverBinaryPath> --args --serve-mcp` with stdin fed repeated "y" lines (the CLI's final "Enable all tools? [Y/n]" prompt cancels on EOF, and profile-startup stdin consumers can burn a line — observed live; one y cancelled the save). Success = exit 0 + stdout "Saved 'museion-tools'"; anything else → `.failed(phase: .register)` through the #48 rail. The add LIVE-PROBES the server (spawns the app binary `--serve-mcp` — the headless launcher branch).
- Provisioning failure UX (#48): `ProvisioningFailureCard` (in `EngineGateView.swift`) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (`ContentView.failurePresented` = `hasFailure && gateDismissed`, where `gateDismissed` is set in the gate sheet's `onDismiss` — keying on dismissal completion avoids macOS dropping a sheet presented during another's dismissal animation); phase rawValue is the title, excerpt behind Technical details; the card snapshots the failure into `@State` so a successful Retry doesn't blank it mid-dismiss. Retry re-runs the whole pass (idempotent), Not Now (`deferFailure`) defers to the next launch's silent retry; sheet is interactiveDismissDisabled. Provisioning never hand-writes the profile config — the ONLY writer of an `mcp_servers` entry is the `hermes mcp add` CLI rail (#44 invariant as amended by #23/ADR-0008: config.yaml stays byte-identical through provisioning passes; registration itself goes through the engine's own command, test-pinned).
- Payload: `ref/writing skills/` ships as a folder reference → plain `Resources/writing skills/` directory (no zip, no compiled manifest). 11 mentor skills seeded; `ste-writing`/`writing-for-agents` ship but never seed.
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profile at `<binaryDir>/profiles/<name>`), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload.
- Tests: `MuseionTests/ProfileProvisionerTests.swift` — fake-binary Process harness (fake creates profile at `<binaryDir>/profiles/<name>`; **#23:** the fake also speaks `-p museion mcp list`/`mcp add` — marker file for "already registered", invocation log asserting the exact add command line, one stdin line read, `mcp-add-fails` reject knob), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload; registration tests: fresh pass adds via the CLI with the exact command line, already-registered skips, probe failure → `.failed(.register)`.
## Profile backup (S2.6, #15 map / #50)
@@ -60,11 +61,17 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- UI: Help → **Open Backup Folder** (`OpenBackupFolderButton` in `MuseionApp.swift`) reveals the Backups root in Finder; restore docs live in `RESTORE.md` beside the snapshots.
- Tests: `MuseionTests/ProfileBackupTests.swift` — injected roots/clock/psScan: liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → `.failed`, temp swept).
## museion-tools MCP server (S2.4, #23)
- `MCPServer.swift` — `MCPServer` (nonisolated): the binary's second role. `MuseionLauncher` (`@main`, this file) branches on `--serve-mcp` → `MCPServer.serve()` (headless — never touches AppKit; blocks on stdin lines, exits 0 on EOF) vs `MuseionApp.main()`. NDJSON JSON-RPC 2.0 on stdio (wire facts live-verified against hermes' MCP client): `initialize` → echo the client's `protocolVersion` (client sends `2025-11-25`) + `capabilities {tools}` + serverInfo; `notifications/*` never answered; `tools/list` → the two tools with typed JSON Schemas (the submit schema IS the fix-card schema, ADR-0006 — one schema serves card UI, apply-write, learning promotion); `tools/call` results carry `content[{type:"text"}]` + `isError:true` on tool failure; `ping` → `{}`; unknown method `-32601`, unparseable line `-32700` id null; **audit: lines over 1 MB answer `-32600` "Line too long" (frame cap mirroring the ACP reader side; readLine's own buffering is a commented ceiling), and one `jsonString` serializer serves replies and tool payloads**; **fflush after every stdout line** (piped stdout is block-buffered). `run(lines:write:)` is the testable seam behind `serve()`. Registration into the `museion` profile happens at provisioning (see above) — ACP sessions then expose the tools as `mcp_museion_tools_query_learnings` / `mcp_museion_tools_submit_fix_cards`.
- `FixCardStore.swift` — `FixCardStore` (nonisolated): the durable card store + tool bodies. `StoredFixCard` (Codable, snake_case, ISO-8601 dates): pattern/problem/diagnosticQuestion/fix, anchor {quote, occurrence (1-based), context?}, lane mechanical|demonstration, emitter lint|engine, provenance {piece, date?, engine?, pass?} (`pass` = the finding pass number — optional, pre-schema cards decode to nil; the palette renders "pass N" in the card meta; #23 follow-up), status "open", anchorStatus valid|stale — the ADR-0006 fields verbatim. `submit(piecePath:cards:)` — piece resolves to post.md (dir or file path; **audit guard: the file form must BE `post.md` under a `projects/`|`archive/` component — any readable file passing as a "piece" made submit a JSON-drop beside it and the anchor check a substring oracle over it; one resolvePostURL guard closed both security MEDIUMs**), raw text loaded once; anchor validation = exact substring, non-overlapping occurrence count vs 1-based occurrence, **stale → the card still lands flagged** (never rejected — the finding survives for the writer; malformed input/vanished piece → thrown error = tool error, the trust boundary); writes `<piece>/cards/<yyyyMMdd-HHmmss>-<PostStore.slug(pattern)>.json` (collision `-2`/`-3`), no dedup (v1 decision — the writer skips repeats). `scan(pieceURL:)` newest-first, skips junk. `learnings(piecePath:)` — home = 4 components up (ADR-0012), content type from frontmatter (`Post.frontmatter(of:)`), reads `<home>/learnings/<type>s/` (literal plural, PRD S4.3) returning raw markdown per file; decay filtering is pass-through until #26 defines the fields (ponytail note in code).
- Tests: `MuseionTests/MCPToolsTests.swift` (anchor matrix incl. occurrence 3-of-2 → stale, empty quote → stale; submit round-trip + snake_case keys; scan ordering + junk skip; learnings per type + missing dir → empty) and `MuseionTests/MCPServerWireTests.swift` (in-process `run(lines:write:)`: initialize echo, silent notifications, both tools listed with required arrays, full submit round-trip through the wire, isError path, -32601/-32700).
## ACP bridge (S2.2, #14 map)
- `ACPEngineClient.swift` — `ACPEngineClient` (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for `hermes acp -p museion` (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per `\n` line, stdout = wire, stderr = logs (never parsed for state); `session/new` **requires `mcpServers`** (list; Museion sends `[]` — the #44 no-MCP-servers invariant on the wire); `session/cancel` is a *notification* (no response); responses camelCase; updates discriminate on `update.sessionUpdate`. `JSONValue` (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto `-32601` (M0 handles none — the deny option); crash/EOF fail pending requests and fire `onCrash` exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit `close()`); `close()` = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks) → `session/new` cwd `~` + `mcpServers: []`. `sendPrompt` streams `agent_message_chunk`/`thought` into a buffer flushed on turn end; tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields); every other update type a collapsible raw-JSON row. Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note), transcript (text rows, FixCardRow cards, RawUpdateRow disclosure), freeform input 1…4 lines + send + Stop while streaming, crash card (Restart, last prompt, stderr tail behind Technical details).
- `MentorSessionModel.swift` — `MentorSessionModel` (@MainActor @Observable): pane state machine (idle/starting/ready/crashed; `isStreaming` Bool). Lazy lifecycle: spawns on first `openSession()` (skipped under hosted tests via `XCTestConfigurationFilePath`), handshake `initialize` → advisory version compare vs state.json (`recordedVersionProvider` injectable; **compares base versions** — the gate records the derived version (`acp --version` → `0.21.5+2177.g735e426`) while the handshake answers the base (`agentInfo.version` → `0.21.5`), so raw string equality fabricates drift on every dev install; `baseVersion(of:)` strips `+`-build metadata; one os_log line + both versions in the pane, never blocks) → `session/new` cwd `~` + `mcpServers: []`. `sendPrompt` (#24 seam: `@discardableResult`, returns `TurnOutcome` — `.ended(stopReason:)` for any completion stopReason incl. `refusal`, `.cancelled` for `cancelled`, `.failed` on a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streams `agent_message_chunk` into a buffer flushed on turn end; **thought lane (#24 dogfood fix): `agent_thought_chunk` streams into its own `streamingThought` buffer** — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed `.thought` row FIRST (it preceded the message), and `restart()` clears both buffers; an optional `label:` renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); **#23 dogfood fix: `sendPrompt` sends session/prompt with `promptTimeout` (nonisolated, 1800 s), NOT the client's 15 s request default** — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished with `isStreaming`; test-pinned `promptTimeout >= 600`); tool calls with fix-card-shaped `rawInput` (pattern+problem minimum) render as `FixCard` (ADR-0006 fields; **audit: the parser takes the nested `submit_fix_cards` argument shape first — `{piece_path, cards:[…]}`, snake_case, anchor as `{quote,occurrence}` object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool**); every other update type a collapsible raw-JSON row. **Audit hardening: a prompt response missing `stopReason` maps to `.failed` (a turn without stopReason never advances a pass), and `sendPrompt` guards the client instead of force-unwrapping.** Cancel = `session/cancel` notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. `clientRef` mirror exists solely so nonisolated deinit can close the child.
- `MentorPaneView.swift` — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note, trailing mini **Debug** checkbox — `@AppStorage("mentorDebugRows")`, off by default: the writing-session transcript filters to prose + card events via `isWritingRow` (static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript (text rows, fix-card tool calls as one-line `FixCardEventRow`s — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; **#24 dogfood fix:** `defaultScrollAnchor(.bottom)` — programmatic `scrollTo` raced the growing lazy rows and mislanded at the TOP; `.thought` rows render collapsed (`ThoughtRow`, the engine's thinking — kept out of the critique text), live thinking shows muted + `lineLimit(3)`), freeform input 1…4 lines + send + Stop while streaming (**#23 dogfood fix:** a liveness row above the input — indeterminate `ProgressView` + "Mentor is working — Stop to interrupt." caption while `isStreaming`; minutes of silent tool work read as dead without it), crash card (Restart, last prompt, stderr tail behind Technical details; input + crash card live in a file-scope `private extension MentorPaneView` — type_body_length posture). **#24 (S3.1):** below the header a segmented **Pass 1 | Pass 2 | Chat** picker (the design contract's `.mentor-tabs`) — pass modes carry the pass bar (`PassBarView`, private): what the pass critiques + `PassContext.estimateTokens` cost line ("· ~N tokens") or "Open a post to run a pass.", the open piece's Pass State chip (library's post-meta voice), and the actions — Cancel (bordered, only while `posts.runningPass` streams) ↔ Run Pass N (borderedProminent; disabled with no open piece, engine not ready, or mid-turn). Chat hides the bar; transcript + input stay shared (the pass's streamed critique renders in the same transcript). `posts: PostsModel?` + `home: URL?` params (nil = previews); PostsPaneView's mentor column passes both. **#23 follow-up (dogfood):** card detail lives in the **Fix Cards palette** — a floating `Window` scene (id `fix-cards`, `FixCardsPalette` in `FixCardsWindow.swift`, `defaultSize` 340×540) beside About, opened via `openWindow` from a mono "Fix Cards · N" row below the pass bar (shown only when cards exist). The palette shows the open piece's title + `posts.openPieceCards` (mono-11 "FIX CARDS · N" header, pattern/problem/fix rows, `lane · emitter` mono meta; stale anchors orange + "· stale anchor" — show-only, never acts; Apply is #25; card meta leads with "pass N" when `provenance.pass` is stamped) and re-contextualizes via `@Observable` as the open piece changes (**audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.`title(of:)` + EditorSession.`passPieceURL`/`hasResearch` are the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped**); painted `DesignTokens.background` — app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering is `FixCardEventRow` — the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement).
- Wiring: `AppGateState.mentor` is the app-scoped model ( ContentView renders `MentorPaneView(model:binaryPath:)` once `gateModel.currentBinaryPath` exists, handing the gate's winner to `mentor.binaryPath` — no re-probe); quit teardown on `NSApplication.willTerminateNotification` → `mentor.shutdown()` (idempotent; scenePhase `.inactive` would fire on plain focus loss).
- Tests: `MuseionTests/ACPClientTests.swift` — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.
+11
View File
@@ -33,6 +33,17 @@ enum SessionTarget {
@MainActor
@Observable
final class EditorSession {
/// #24: the pass rails' shared piece facts — runPass and PassBarView
/// must agree on the stub path and the research probe (review: two
/// hand-copies drifting).
var passPieceURL: URL {
folderURL.appendingPathComponent("post.md")
}
var hasResearch: Bool {
FileManager.default.fileExists(atPath: folderURL.appendingPathComponent("research").path)
}
let target: SessionTarget
private let debounce: Duration
+25 -4
View File
@@ -86,14 +86,31 @@ nonisolated enum EngineProbe {
return result
}
/// Run a process with stdin closed, capture stdout/stderr, kill after `timeout`.
static func execute(_ arguments: [String], timeout: TimeInterval) -> ProcessOutput {
/// Run a process, capture stdout/stderr, kill after `timeout`. `stdin` (when
/// set) is written to the child then closed — for interactive prompts like
/// the mcp add's "Enable all tools? [Y/n]"; otherwise stdin is /dev/null.
static func execute(_ arguments: [String], timeout: TimeInterval, stdin: String? = nil) -> ProcessOutput {
let path = arguments[0]
guard FileManager.default.isExecutableFile(atPath: path) else { return ProcessOutput(exitCode: -1) }
let process = Process()
process.executableURL = URL(fileURLWithPath: path)
process.arguments = Array(arguments.dropFirst())
process.standardInput = FileHandle.nullDevice
// The parent holds the pipe's read end until dealloc, so this small
// pre-spawn write can't hit EPIPE; closing our write end gives the
// child one line + EOF. Ceiling (audit INFO-6): a pre-spawn write
// must stay well under the 64 KB pipe buffer or it deadlocks before
// the watchdog exists — chunked write or spawn-then-write if a
// caller ever needs more.
var stdinPipe: Pipe?
if let stdin {
let pipe = Pipe()
process.standardInput = pipe
try? pipe.fileHandleForWriting.write(contentsOf: Data(stdin.utf8))
try? pipe.fileHandleForWriting.close()
stdinPipe = pipe
} else {
process.standardInput = FileHandle.nullDevice
}
let stdoutPipe = Pipe(), stderrPipe = Pipe()
process.standardOutput = stdoutPipe
@@ -109,7 +126,11 @@ nonisolated enum EngineProbe {
Thread.sleep(forTimeInterval: 0.01)
}
if process.isRunning {
terminateAndReap(process, pipes: [stdoutPipe.fileHandleForReading, stderrPipe.fileHandleForReading])
var pipes = [stdoutPipe.fileHandleForReading, stderrPipe.fileHandleForReading]
if let stdinPipe {
pipes.append(stdinPipe.fileHandleForReading)
}
terminateAndReap(process, pipes: pipes)
return ProcessOutput(exitCode: -1, stderr: "timed out after \(Int(timeout)) s")
}
+308
View File
@@ -0,0 +1,308 @@
//
// FixCardStore.swift
// Museion
//
// #23 (M2, slice 1): the durable fix-card side of ADR-0006 — the stored
// card (one snake_case JSON file under <piece>/cards/), pure anchor
// validation against post.md, and the learnings reader the museion-tools
// MCP server exposes. Plain disk work, no UI; the transcript-side
// FixCard in MentorSessionModel is the ephemeral sibling.
//
import Foundation
/// #23: Fix Card persistence. nonisolated like PostStore — the headless
/// MCP mode calls this before any app machinery exists.
nonisolated enum FixCardStore {
// MARK: - Model
/// One durable Fix Card as written to `<piece>/cards/*.json`.
struct StoredFixCard: Codable, Equatable {
/// Where the card anchors in the piece: an exact-substring quote,
/// its 1-based occurrence, optional human context note.
struct Anchor: Codable, Equatable {
var quote: String
var occurrence: Int
var context: String?
init(quote: String, occurrence: Int = 1, context: String? = nil) {
self.quote = quote
self.occurrence = occurrence
self.context = context
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
quote = try container.decode(String.self, forKey: .quote)
// The wire schema declares default 1 — an omitted occurrence
// means "the first one".
occurrence = try container.decodeIfPresent(Int.self, forKey: .occurrence) ?? 1
context = try container.decodeIfPresent(String.self, forKey: .context)
}
}
/// ADR-0006 lanes: the mechanical fix vs the demonstration rewrite.
enum Lane: String, Codable {
case mechanical, demonstration
}
/// Who emitted the card.
enum Emitter: String, Codable {
case lint, engine
}
/// Anchor validation outcome: a stale card still lands (the writer
/// decides), it just never auto-applies.
enum AnchorStatus: String, Codable {
case valid, stale
}
struct Provenance: Codable, Equatable {
var piece: String
var date: String?
var engine: String?
/// Which pass found it (1, 2…) — optional: pre-schema cards and
/// foreign MCP clients may omit it; the palette renders it when
/// present. #23 follow-up: pass differentiation.
var pass: Int?
}
var id: UUID
var submittedAt: Date
var pattern: String
var problem: String
var diagnosticQuestion: String
var fix: String
var anchor: Anchor
var lane: Lane
var emitter: Emitter
var provenance: Provenance?
/// Always "open" on submit; later states belong to the app slice.
var status: String
var anchorStatus: AnchorStatus
}
/// 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 {
var pattern: String
var problem: String
var diagnosticQuestion: String?
var fix: String?
var anchor: StoredFixCard.Anchor
var lane: StoredFixCard.Lane
var emitter: StoredFixCard.Emitter
var provenance: StoredFixCard.Provenance?
}
// MARK: - Codec
/// Shared codec: snake_case keys + ISO-8601 dates — the wire and the
/// disk format agree. Created per access; no non-Sendable statics
/// (repo convention, ProfileBackup.stamp).
static var encoder: JSONEncoder {
let instance = JSONEncoder()
instance.keyEncodingStrategy = .convertToSnakeCase
instance.dateEncodingStrategy = .iso8601
return instance
}
static var decoder: JSONDecoder {
let instance = JSONDecoder()
instance.keyDecodingStrategy = .convertFromSnakeCase
instance.dateDecodingStrategy = .iso8601
return instance
}
/// Descriptive failures surfaced verbatim as tool error text.
struct CardError: LocalizedError, Equatable {
let message: String
var errorDescription: String? {
message
}
}
// MARK: - Anchor validation (pure)
/// `quote` must appear in `text` at least `occurrence` times
/// (non-overlapping, 1-based). Empty quote or a vanished quote →
/// stale — never a crash, never a rejection.
static func anchorStatus(text: String, quote: String, occurrence: Int) -> StoredFixCard.AnchorStatus {
guard !quote.isEmpty, occurrence >= 1 else { return .stale }
return text.ranges(of: quote).count >= occurrence ? .valid : .stale
}
// MARK: - Submit
/// Validate every card first, then write one JSON file per card into
/// `<piece>/cards/` named `<yyyyMMdd-HHmmss>-<slug>.json` (collision →
/// -2, -3…). Stale anchors still land, flagged. No dedup — every
/// submission lands (explicit product decision).
static func submit(piecePath: String, cards: [Input]) throws -> [(card: StoredFixCard, file: String)] {
let postURL = try resolvePostURL(piecePath)
let text = try String(contentsOf: postURL, encoding: .utf8)
// Whole-call semantics: a malformed card errors the call before
// anything is written.
let materialized = try cards.map { try materialize($0, postText: text) }
let dir = postURL.deletingLastPathComponent().appendingPathComponent("cards", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let stamp = Self.stamp(Date())
var written: [(card: StoredFixCard, file: String)] = []
for card in materialized {
let file = uniqueFile(dir, base: "\(stamp)-\(PostStore.slug(from: card.pattern))")
do {
try encoder.encode(card).write(to: dir.appendingPathComponent(file), options: .atomic)
} catch {
// Honesty at the trust boundary: a mid-loop write failure leaves
// earlier cards landed — say which, so a client retry doesn't
// blindly duplicate them (there is no dedup, by decision).
let landed = written.map(\.file).joined(separator: ", ")
throw CardError(message: "card write failed: \(error.localizedDescription)"
+ (landed.isEmpty ? "" : " — already written: \(landed)"))
}
written.append((card, file))
}
return written
}
/// Trust-boundary validation + server stamping.
private static func materialize(_ input: Input, postText: String) throws -> StoredFixCard {
guard !input.pattern.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw CardError(message: "card pattern must not be empty")
}
guard !input.problem.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw CardError(message: "card problem must not be empty")
}
guard !input.anchor.quote.isEmpty else {
throw CardError(message: "card anchor quote must not be empty")
}
guard input.anchor.occurrence >= 1 else {
throw CardError(message: "card anchor occurrence must be ≥ 1")
}
return StoredFixCard(
id: UUID(),
submittedAt: Date(),
pattern: input.pattern,
problem: input.problem,
diagnosticQuestion: input.diagnosticQuestion ?? "",
fix: input.fix ?? "",
anchor: input.anchor,
lane: input.lane,
emitter: input.emitter,
provenance: input.provenance,
status: "open",
anchorStatus: anchorStatus(
text: postText,
quote: input.anchor.quote,
occurrence: input.anchor.occurrence,
),
)
}
/// A piece path is the piece folder or its post.md; it must exist and
/// be readable — a missing piece is a tool error, never an empty
/// submit. No tilde expansion: the pass stub pins absolute paths, and
/// expanding a foreign string needlessly widens what a client can
/// address (trust boundary — standards review). The file form must be
/// named post.md AND sit under a `projects/` or `archive/` component
/// (ADR-0012) — otherwise any readable file becomes a "piece", submit
/// becomes a JSON-drop beside it, and anchor validation a substring
/// oracle over it (security review: both MEDIUMs, one guard).
private static func resolvePostURL(_ piecePath: String) throws -> URL {
let url = URL(fileURLWithPath: piecePath)
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) else {
throw CardError(message: "piece not found: \(piecePath)")
}
var postURL = url
if isDir.boolValue {
postURL.appendPathComponent("post.md")
}
guard postURL.lastPathComponent == "post.md",
postURL.pathComponents.contains(where: { $0 == "projects" || $0 == "archive" }),
FileManager.default.isReadableFile(atPath: postURL.path)
else {
throw CardError(message: "not a piece (expected <projects|archive>/…/post.md): \(piecePath)")
}
return postURL
}
/// Timestamped card filename prefix, lexicographically sortable
/// (ProfileBackup convention).
private static func stamp(_ date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd-HHmmss"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.string(from: date)
}
/// First free filename for `base` (no extension): base, base-2, base-3…
// ponytail: exists-then-write race needs two concurrent same-second
// same-pattern submits to matter (atomic rename = replace, not corrupt);
// O_EXCL retry if a second writer ever appears.
private static func uniqueFile(_ dir: URL, base: String) -> String {
var name = "\(base).json"
var suffix = 2
while FileManager.default.fileExists(atPath: dir.appendingPathComponent(name).path) {
name = "\(base)-\(suffix).json"
suffix += 1
}
return name
}
// MARK: - Scan
/// Every stored card under `<piece>/cards/`, newest-first (the stamp
/// prefix sorts lexicographically). Undecodable files are skipped
/// silently — a stranger's hand-edit never crashes the reader. A
/// post.md URL is tolerated (app-side call sites hold the file URL).
static func scan(pieceURL: URL) -> [StoredFixCard] {
var dir = pieceURL
if ["md", "markdown"].contains(dir.pathExtension.lowercased()) {
dir.deleteLastPathComponent()
}
let cards = dir.appendingPathComponent("cards", isDirectory: true)
let files = (try? FileManager.default.contentsOfDirectory(atPath: cards.path)) ?? []
return files
.filter { $0.hasSuffix(".json") }
.sorted(by: >)
.compactMap { name in
guard let data = try? Data(contentsOf: cards.appendingPathComponent(name)) else { return nil }
return try? decoder.decode(StoredFixCard.self, from: data)
}
}
// MARK: - Learnings
/// The piece's visible learnings: raw markdown per file under
/// `<home>/learnings/<type>s/` (LITERAL plural — "posts", "outlines"),
/// name-sorted. Raw contents, no parsing — promotion stays a later
/// decision (#26). Missing dir → empty (fresh start is the correct
/// v1 answer); a missing piece still throws.
// ponytail: decay filtering is pass-through until issue #26 defines
// the frontmatter fields.
static func learnings(piecePath: String) throws -> [(file: String, markdown: String)] {
let postURL = try resolvePostURL(piecePath)
let text = try String(contentsOf: postURL, encoding: .utf8)
// ADR-0012 layout: <home>/<projects|archive>/<project>/<id>/post.md —
// the Home is four components up from the file.
var home = postURL
for _ in 0 ..< 4 {
home.deleteLastPathComponent()
}
let type = Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
let dir = home.appendingPathComponent("learnings/\(type.rawValue)s", isDirectory: true)
let files = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? [])
.filter { $0.hasSuffix(".md") }
.sorted()
return files.compactMap { name in
guard let markdown = try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8) else {
return nil
}
return (file: name, markdown: markdown)
}
}
}
+109
View File
@@ -0,0 +1,109 @@
//
// FixCardsWindow.swift
// Museion
//
// #23 follow-up (dogfood): the Fix Cards palette — the durable card
// store's own surface, a floating window (scene id "fix-cards") opened
// from the mentor pass bar. The transcript renders card tool calls as
// one-line events; the card DETAIL lives here while the verdict gets
// worked through. Show-only, never acts (Apply is #25).
//
import SwiftUI
/// Palette body: the open piece's stored fix cards (`<piece>/cards/`, any
/// MCP client's submissions — PostsModel re-derives on open/rescan, so this
/// stays current via @Observable). Re-contextualizes as the piece changes.
struct FixCardsPalette: View {
@Environment(AppGateState.self) private var gate
var body: some View {
let posts = gate.posts
VStack(alignment: .leading, spacing: 0) {
if let title = openPieceTitle {
Text(title)
.font(.headline)
.padding(.horizontal, 12)
.padding(.top, 12)
.padding(.bottom, 4)
}
if posts.openPieceCards.isEmpty {
emptyState(hasPiece: posts.session?.postID != nil)
} else {
cardList(posts.openPieceCards)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
// The window reads as app chrome, not a document — the same warm
// cream the workspace root/rail paints (DesignTokens.background).
.background(DesignTokens.background)
}
/// The pass label's title source — PostsModel's shared lookup.
private var openPieceTitle: String? {
guard let id = gate.posts.session?.postID else { return nil }
return gate.posts.title(of: id)
}
private func emptyState(hasPiece: Bool) -> some View {
VStack(alignment: .leading, spacing: 6) {
Text(hasPiece ? "No fix cards yet." : "No piece open.")
.font(.headline)
Text(hasPiece
? "Run a pass — cards land here as the mentor files them."
: "Open a post — its fix cards collect here.")
.font(.callout)
.foregroundStyle(.secondary)
}
.padding(12)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
/// The open piece's STORED fix cards (moved from MentorPaneView #23 S2.4
/// — uncapped here, the window owns its scroll).
private func cardList(_ cards: [FixCardStore.StoredFixCard]) -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 8) {
Text("FIX CARDS · \(cards.count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
ForEach(cards, id: \.id) { card in
row(card)
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
/// One card: pattern title, problem + fix body, lane · emitter mono meta
/// (ADR-0006). A stale anchor reads distinct — orange + caption — and is
/// never appliable: v1 shows, never acts.
private func row(_ card: FixCardStore.StoredFixCard) -> some View {
let stale = card.anchorStatus == .stale
var meta = "\(card.lane.rawValue) · \(card.emitter.rawValue)"
if let pass = card.provenance?.pass {
meta = "pass \(pass) · " + meta
}
if stale {
meta += " · stale anchor"
}
return VStack(alignment: .leading, spacing: 6) {
Label(card.pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
.font(.callout.weight(.semibold))
.foregroundStyle(stale ? .orange : DesignTokens.foreground)
if !card.problem.isEmpty {
Text(card.problem).font(.callout)
}
if !card.fix.isEmpty {
Text("Fix: \(card.fix)").font(.callout)
}
Text(meta)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(stale ? .orange : DesignTokens.muted)
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 8))
}
}
+267
View File
@@ -0,0 +1,267 @@
//
// MCPServer.swift
// Museion
//
// #23 (M2, slice 1): the museion-tools MCP server over stdio — NDJSON
// JSON-RPC 2.0 (one message per line, stdout is the wire, stderr logs),
// launched headless via --serve-mcp before any AppKit machinery. Wire
// facts baked in from a live verified session against the real hermes
// MCP client.
//
import Foundation
import SwiftUI
/// The launch branch (#23): `--serve-mcp` runs the headless tool server,
/// anything else is the normal app. Lives here — MuseionApp stays the
/// pure SwiftUI scene.
@main
enum MuseionLauncher {
static func main() {
if CommandLine.arguments.contains("--serve-mcp") {
MCPServer.serve()
} else {
MuseionApp.main()
}
}
}
/// #23: the stdio MCP server. nonisolated — this mode runs before any app
/// machinery and never touches NSApplication/AppKit.
nonisolated enum MCPServer {
/// Production entry: blocking loop over stdin lines, replies on
/// stdout. EOF on stdin → clean exit 0.
static func serve() {
run(
lines: AnyIterator { readLine() },
write: { line in
fputs(line + "\n", stdout)
fflush(stdout) // piped stdout is block-buffered; unflushed lines never reach the client
},
)
}
/// The dispatch loop, in-process testable: feed lines, collect
/// replies.
static func run(lines: AnyIterator<String>, write: (String) -> Void) {
while let line = lines.next() {
dispatch(line, write: write)
}
}
// MARK: - Dispatch
private static func dispatch(_ line: String, write: (String) -> Void) {
// 1 MB frame cap — mirrors ACPEngineClient's reader cap so a
// hostile or buggy client can't push an unbounded line into
// JSONSerialization. ponytail: readLine() still buffers the line
// itself in memory; byte-chunked stdin reader if a same-user OOM
// ever matters.
guard line.utf8.count <= 1_048_576 else {
write(reply(error: ["code": -32600, "message": "Line too long"], id: NSNull()))
return
}
guard let data = line.data(using: .utf8),
let message = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
let method = message["method"] as? String
else {
write(reply(error: ["code": -32700, "message": "Parse error"], id: NSNull()))
return
}
let id = message["id"]
let params = message["params"] as? [String: Any] ?? [:]
// Notifications (notifications/initialized & friends) never reply.
if method.hasPrefix("notifications/") {
return
}
switch method {
case "initialize":
// Echo the client's protocolVersion; never invent one.
let version = params["protocolVersion"] as? String ?? "2025-11-25"
write(reply(id: id, result: [
"protocolVersion": version,
"capabilities": ["tools": [:]] as [String: Any],
"serverInfo": ["name": "museion-tools", "version": "1.0"],
]))
case "ping":
write(reply(id: id, result: [:]))
case "tools/list":
write(reply(id: id, result: ["tools": tools]))
case "tools/call":
write(toolCall(id: id, params: params))
default:
write(reply(error: ["code": -32601, "message": "Method not found"], id: id ?? NSNull()))
}
}
private static func toolCall(id: Any?, params: [String: Any]) -> String {
let name = params["name"] as? String ?? ""
let arguments = params["arguments"] as? [String: Any] ?? [:]
func failure(_ error: Error) -> String {
// CardError carries the human message; other errors (decode)
// read better verbatim. Tool failures are results with
// isError inside — never JSON-RPC errors.
let text = error is FixCardStore.CardError ? error.localizedDescription : "\(error)"
return reply(id: id, result: [
"content": [["type": "text", "text": text]] as [[String: Any]],
"isError": true,
])
}
do {
switch name {
case "query_learnings":
let args = try FixCardStore.decoder.decode(
LearningsArgs.self, from: JSONSerialization.data(withJSONObject: arguments),
)
let learned = try FixCardStore.learnings(piecePath: args.piecePath)
return reply(id: id, result: [
"content": [[
"type": "text",
"text": jsonString([
"learnings": learned.map { ["file": $0.file, "markdown": $0.markdown] } as [[String: Any]],
]) ?? "{}",
]] 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)
return reply(id: id, result: [
"content": [[
"type": "text",
"text": jsonString([
"cards": written.map {
["file": $0.file, "anchor_status": $0.card.anchorStatus.rawValue]
} as [[String: Any]],
]) ?? "{}",
]] as [[String: Any]],
])
default:
return failure(FixCardStore.CardError(message: "Unknown tool: \(name)"))
}
} catch {
return failure(error)
}
}
private struct LearningsArgs: Decodable {
var piecePath: String
}
private struct SubmitArgs: Decodable {
var piecePath: String
var cards: [FixCardStore.Input]
}
// MARK: - Tools
/// The two tools (#23). The submit schema IS the fix-card schema
/// (ADR-0006): it serves the card UI, the apply-write, and learning
/// promotion.
private static var tools: [[String: Any]] {
[
[
"name": "query_learnings",
"description": "The piece's visible learnings — raw markdown per file, from <home>/learnings/<type>s/.",
"inputSchema": [
"type": "object",
"properties": [
"piece_path": [
"type": "string",
"description": "Path to the piece folder or its post.md.",
] as [String: Any],
] as [String: Any],
"required": ["piece_path"],
] as [String: Any],
],
[
"name": "submit_fix_cards",
"description": "Persist fix cards for a piece. Anchor-validated against post.md; stale anchors land flagged.",
"inputSchema": [
"type": "object",
"properties": [
"piece_path": [
"type": "string",
"description": "Path to the piece folder or its post.md.",
],
"cards": [
"type": "array",
"items": [
"type": "object",
"properties": [
"pattern": ["type": "string"],
"problem": ["type": "string"],
"diagnostic_question": ["type": "string"],
"fix": ["type": "string"],
"anchor": [
"type": "object",
"properties": [
"quote": [
"type": "string",
"description": "Exact substring quoted from the piece.",
],
"occurrence": [
"type": "integer",
"default": 1,
"description": "1-based occurrence of the quote in the piece.",
],
"context": ["type": "string"],
] as [String: Any],
"required": ["quote"],
],
"lane": ["type": "string", "enum": ["mechanical", "demonstration"]],
"emitter": ["type": "string", "enum": ["lint", "engine"]],
"provenance": [
"type": "object",
"properties": [
"piece": ["type": "string"],
"date": ["type": "string"],
"engine": ["type": "string"],
"pass": [
"type": "integer",
"description": "Pass number that found the card (1 = structural, 2 = line-level).",
] as [String: Any],
] as [String: Any],
],
] as [String: Any],
"required": ["pattern", "problem", "anchor", "lane", "emitter"],
] as [String: Any],
] as [String: Any],
] as [String: Any],
"required": ["piece_path", "cards"],
] as [String: Any],
],
]
}
// MARK: - Wire plumbing
/// One JSON serializer for every wire path (review: textJSON/serialize
/// were the same body twice).
private static func jsonString(_ object: [String: Any]) -> String? {
(try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]))
.flatMap { String(data: $0, encoding: .utf8) }
}
private static func reply(id: Any?, result: [String: Any]) -> String {
serialize(["jsonrpc": "2.0", "id": id ?? NSNull(), "result": result] as [String: Any])
}
private static func reply(error: [String: Any], id: Any) -> String {
serialize(["jsonrpc": "2.0", "error": error, "id": id] as [String: Any])
}
private static func serialize(_ object: [String: Any]) -> String {
if let string = jsonString(object) {
return string
}
// The wire must always answer, but stay debuggable: stderr is logs.
fputs("museion-tools: reply serialization failed\n", stderr)
return #"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":null}"#
}
}
+252 -87
View File
@@ -13,12 +13,29 @@ import SwiftUI
struct MentorPaneView: View {
@State private var draft = ""
@State private var model: MentorSessionModel
/// #23 follow-up: opens the Fix Cards palette window (scene "fix-cards").
@Environment(\.openWindow) private var openWindow
/// Set post-gate by ContentView: the probe's winning binary (no re-probe).
var binaryPath: String?
/// #24 (S3.1): app-scoped Posts state for the pass bar (nil = no pass
/// surface, previews).
var posts: PostsModel?
/// #24 (S3.1): the Home passes run against.
var home: URL?
/// #24 (S3.1): the segmented surface — Pass 1 | Pass 2 | Chat. Pass
/// modes carry the pass bar; Chat is the freeform surface alone.
private enum Mode: Hashable { case pass1, pass2, chat }
@State private var mode: Mode = .pass1
/// Writing-session filter (#23 dogfood): session/tool/debug rows render
/// only when on — off by default, persisted. The model keeps every row
/// either way (debug history intact; the toggle flips instantly).
@AppStorage("mentorDebugRows") private var debugRows = false
init(model: MentorSessionModel, binaryPath: String?) {
init(model: MentorSessionModel, binaryPath: String?, posts: PostsModel? = nil, home: URL? = nil) {
_model = State(initialValue: model)
self.binaryPath = binaryPath
self.posts = posts
self.home = home
}
var body: some View {
@@ -30,6 +47,30 @@ struct MentorPaneView: View {
ProgressView("Starting the mentor engine…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
case .ready:
modePicker
if let kind = passKind {
PassBarView(kind: kind, posts: posts, home: home, model: model)
Divider()
}
if let posts, !posts.openPieceCards.isEmpty {
// #23 follow-up: the detail moved to the palette window —
// this row just names it and opens it.
Button {
openWindow(id: "fix-cards")
} label: {
Label(
"Fix Cards · \(posts.openPieceCards.count)",
systemImage: "rectangle.and.pencil.and.ellipsis",
)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
.buttonStyle(.borderless)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 12)
.padding(.vertical, 6)
Divider()
}
transcript
Divider()
inputBar
@@ -49,6 +90,16 @@ struct MentorPaneView: View {
}
}
/// The writing-session transcript: prose (verdicts, labels, notes) and
/// card events stay; raw session/tool rows and collapsed thinking are
/// debug-only. Static — pure, testable.
static func isWritingRow(_ row: SessionRow) -> Bool {
switch row.content {
case .text, .fixCard: true
case .thought, .raw: false
}
}
// MARK: Header
private var header: some View {
@@ -75,6 +126,11 @@ struct MentorPaneView: View {
.foregroundStyle(.tertiary)
.textSelection(.enabled)
}
Toggle("Debug", isOn: $debugRows)
.toggleStyle(.checkbox)
.controlSize(.mini)
.foregroundStyle(.tertiary)
.help("Show session updates, tool calls, and engine thinking.")
}
.padding(.horizontal, 12)
// #90: pane heads align at the export's 52px — same height as the
@@ -83,35 +139,56 @@ struct MentorPaneView: View {
.frame(minHeight: 52)
}
// MARK: Transcript
// MARK: Pass surface (#24, S3.1)
private var transcript: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
ForEach(model.rows) { row in
rowView(row)
.id(row.id)
}
if !model.streamingText.isEmpty {
textRow("Mentor: \(model.streamingText)")
.id("streaming")
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
}
.onChange(of: model.rows.count) { scrollToBottom(proxy) }
.onChange(of: model.streamingText) { scrollToBottom(proxy) }
private var passKind: PassKind? {
switch mode {
case .pass1: .pass1
case .pass2: .pass2
case .chat: nil
}
}
private func scrollToBottom(_ proxy: ScrollViewProxy) {
if let last = model.rows.last?.id {
proxy.scrollTo(last, anchor: .bottom)
} else {
proxy.scrollTo("streaming", anchor: .bottom)
private var modePicker: some View {
Picker("Mentor surface", selection: $mode) {
Text("Pass 1").tag(Mode.pass1)
Text("Pass 2").tag(Mode.pass2)
Text("Chat").tag(Mode.chat)
}
.pickerStyle(.segmented)
.padding(.horizontal, 12)
.padding(.top, 10)
.padding(.bottom, 8)
}
// MARK: Transcript
private var transcript: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 10) {
ForEach(model.rows.filter { debugRows || Self.isWritingRow($0) }) { row in
rowView(row)
}
if debugRows, !model.streamingThought.isEmpty {
// Live thinking: quiet, capped — it's transient (the full
// text lands in a collapsed row when the turn ends).
Text(model.streamingThought)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.lineLimit(3)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
if !model.streamingText.isEmpty {
textRow("Mentor: \(model.streamingText)")
}
}
.padding(12)
.frame(maxWidth: .infinity, alignment: .leading)
}
// #24 fix: programmatic scrollTo raced the growing lazy rows and
// mislanded at the TOP; the native bottom anchor needs no scroll code.
.defaultScrollAnchor(.bottom)
}
@ViewBuilder
@@ -119,8 +196,12 @@ struct MentorPaneView: View {
switch row.content {
case let .text(text):
textRow(text)
case let .thought(text):
ThoughtRow(text: text)
case let .fixCard(card):
FixCardRow(card: card)
// #23 follow-up: detail lives in the palette window — the
// transcript keeps a one-line event, not the card.
FixCardEventRow(pattern: card.pattern)
case let .raw(kind, json):
RawUpdateRow(kind: kind, json: json)
}
@@ -132,29 +213,101 @@ struct MentorPaneView: View {
.frame(maxWidth: .infinity, alignment: .leading)
}
// MARK: Rows
/// The tool-call EVENT, not the card: the pattern title alone. The
/// card's full statement lives in the Fix Cards palette window.
private struct FixCardEventRow: View {
let pattern: String
var body: some View {
Label(pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
/// #24 fix: the engine's thinking, collapsed — a pass's thought stream runs
/// to hundreds of lines and is not the critique (only `agent_message_chunk`
/// is). Same shape as RawUpdateRow: quiet mono, expandable, never in the way.
private struct ThoughtRow: View {
let text: String
var body: some View {
DisclosureGroup {
Text(text)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
} label: {
Text("thinking")
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(DesignTokens.muted)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
private struct RawUpdateRow: View {
let kind: String
let json: String
var body: some View {
DisclosureGroup {
Text(json)
.font(.system(size: 10, design: .monospaced))
.textSelection(.enabled)
} label: {
Text(kind)
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
// MARK: Input + crash card (file-scope extension — type_body_length posture)
private extension MentorPaneView {
// MARK: Input
private var inputBar: some View {
HStack(spacing: 8) {
TextField("Ask the mentor…", text: $draft, axis: .vertical)
.textFieldStyle(.plain)
.lineLimit(1 ... 4)
.onSubmit { send() }
Button {
send()
} label: {
Image(systemName: "arrow.up.circle.fill")
.font(.title2)
}
.buttonStyle(.plain)
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isStreaming)
VStack(alignment: .leading, spacing: 8) {
// Liveness: a pass legitimately runs minutes of silent tool work
// (skill loads, learnings) — without this the pane reads as dead
// (dogfood #23: "hard to tell if it is still thinking").
if model.isStreaming {
Button {
model.stopStreaming()
} label: {
Text("Stop")
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
Text("Mentor is working — Stop to interrupt.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
HStack(spacing: 8) {
TextField("Ask the mentor…", text: $draft, axis: .vertical)
.textFieldStyle(.plain)
.lineLimit(1 ... 4)
.onSubmit { send() }
Button {
send()
} label: {
Image(systemName: "arrow.up.circle.fill")
.font(.title2)
}
.buttonStyle(.plain)
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isStreaming)
if model.isStreaming {
Button {
model.stopStreaming()
} label: {
Text("Stop")
}
.controlSize(.regular)
}
.controlSize(.regular)
}
}
.padding(12)
@@ -207,57 +360,69 @@ struct MentorPaneView: View {
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
// MARK: Rows
/// #24 (S3.1): the pass bar — what the pass critiques + the honest cost
/// estimate (PassContext), the open piece's Pass State, and the Run/Cancel
/// action. Additive chrome above the mentor pane's shared transcript.
private struct PassBarView: View {
let kind: PassKind
let posts: PostsModel?
let home: URL?
let model: MentorSessionModel
private struct FixCardRow: View {
let card: FixCard
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Label(card.pattern, systemImage: "rectangle.and.pencil.and.ellipsis")
.font(.callout.weight(.semibold))
if !card.anchor.isEmpty {
Text("“\(card.anchor)”")
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(.secondary)
}
if !card.problem.isEmpty {
Text(card.problem).font(.callout)
}
if !card.diagnosticQuestion.isEmpty {
Text("Diagnostic: \(card.diagnosticQuestion)")
.font(.callout)
.foregroundStyle(.secondary)
}
if !card.fix.isEmpty {
Text("Fix: \(card.fix)").font(.callout)
}
Text(card.provenance + " · " + card.status)
.font(.caption2)
.foregroundStyle(.tertiary)
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(description)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
HStack {
Text(stateLabel)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer()
actions
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 8))
}
.padding(.horizontal, 12)
.padding(.bottom, 10)
}
private struct RawUpdateRow: View {
let kind: String
let json: String
/// What the pass does + the predictable cost — or the honest ask when
/// no piece is open.
private var description: String {
guard let posts, let session = posts.session, session.postID != nil else {
return "Open a post to run a pass."
}
let tokens = PassContext.estimateTokens(
kind: kind, body: session.text, pieceURL: session.passPieceURL, hasResearch: session.hasResearch,
)
return "Critiques \(kind.level) · ~\(tokens.formatted()) tokens"
}
var body: some View {
DisclosureGroup {
Text(json)
.font(.system(size: 10, design: .monospaced))
.textSelection(.enabled)
} label: {
Text(kind)
.font(.system(size: 11, design: .monospaced))
.foregroundStyle(.secondary)
/// The open piece's current Pass State (the library's post-meta voice).
private var stateLabel: String {
guard let posts else { return "—" }
return posts.posts.first(where: { $0.id == posts.selectedPostID })?.passState.rawValue ?? "—"
}
/// Cancel while a pass runs; Run otherwise — disabled with no open
/// piece or while the engine can't take the turn.
@ViewBuilder
private var actions: some View {
if posts?.runningPass != nil {
Button("Cancel") {
posts?.cancelPass(mentor: model)
}
.frame(maxWidth: .infinity, alignment: .leading)
.buttonStyle(.bordered)
} else {
Button("Run \(kind.rawValue)") {
guard let posts, let home else { return }
Task { await posts.runPass(kind, home: home, mentor: model) }
}
.buttonStyle(.borderedProminent)
.disabled(posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming)
}
}
}
+88 -19
View File
@@ -15,6 +15,9 @@ import os
struct SessionRow: Identifiable {
enum Content {
case text(String)
/// #24 fix: the engine's thinking for one turn — rendered collapsed,
/// never mixed into the critique text.
case thought(String)
case fixCard(FixCard)
case raw(kind: String, json: String)
}
@@ -36,6 +39,17 @@ struct FixCard {
var status: String
}
/// How a turn ended — the pass orchestrator's seam (#24): a pass advances
/// Pass State only when the engine's turn completed, never on cancel/crash.
enum TurnOutcome: Equatable {
/// Turn ended; stopReason as answered on the wire (e.g. "end_turn", "refusal").
case ended(stopReason: String)
/// The engine acknowledged a session/cancel (stopReason "cancelled").
case cancelled
/// Transport error / crash mid-turn (the failure row is already appended).
case failed
}
/// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the
/// pane opens its first session and stays alive for the app's life (map
/// decision: child lifecycle).
@@ -62,6 +76,10 @@ final class MentorSessionModel {
private(set) var rows: [SessionRow] = []
/// Streaming buffer for the in-flight agent message; flushed to a row on completion.
private(set) var streamingText = ""
/// #24 fix: streaming buffer for the engine's THINKING — kept out of the
/// critique stream. A pass runs to hundreds of thought lines; conflating
/// them with `agent_message_chunk` made the transcript one giant blob.
private(set) var streamingThought = ""
/// Advisory engine-version verdict (map decision: advisory, never blocks).
private(set) var versionNote: String?
/// The running engine's version, from the initialize handshake (always visible).
@@ -126,6 +144,7 @@ final class MentorSessionModel {
clientRef = nil
sessionId = nil
streamingText = ""
streamingThought = ""
phase = .starting
await startEngine()
}
@@ -216,16 +235,36 @@ final class MentorSessionModel {
phase = .ready(sessionId: sid)
}
/// Send a prompt and stream the reply. Appends the user row first; the
/// Send a prompt and stream the reply. Appends the user row first — a
/// non-nil `label` renders verbatim INSTEAD of the raw prompt (pass prompts
/// are long wire stubs that must not land in the transcript); the
/// stop_reason response ends the turn (refusal maps to a plain note —
/// wire-verified edge semantics).
func sendPrompt(_ text: String) async {
/// wire-verified edge semantics). Returns how the turn ended (#24 seam):
/// a pass advances only on a completed turn, never on cancel/crash.
/// session/prompt's response arrives only when the TURN ends — a pass
/// legitimately runs minutes of tool work between prompt and stop reason.
/// The client's 15 s request default would abandon the wait mid-stream
/// (observed live, #23 dogfood: "connection lost" while the engine kept
/// working, Stop vanished with isStreaming). Long-but-finite so a truly
/// stuck engine still surfaces; Stop is the live-turn exit.
nonisolated static let promptTimeout: TimeInterval = 1800
@discardableResult
func sendPrompt(_ text: String, label: String? = nil) async -> TurnOutcome {
let prompt = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return }
// Guard refusal: the turn never ran — .failed is the closest of the
// three buckets (the seam has no "never started" case; callers that
// check phase before prompting never land here).
guard !prompt.isEmpty, case let .ready(sid) = phase, !isStreaming else { return .failed }
lastPrompt = prompt
rows.append(SessionRow(content: .text("You: \(prompt)")))
rows.append(SessionRow(content: .text(label ?? "You: \(prompt)")))
isStreaming = true
defer {
// Flush the thinking first (it preceded the message), collapsed.
if !streamingThought.isEmpty {
rows.append(SessionRow(content: .thought(streamingThought)))
streamingThought = ""
}
// Flush any streamed-but-unfinished agent text into a row.
if !streamingText.isEmpty {
rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
@@ -233,22 +272,39 @@ final class MentorSessionModel {
}
isStreaming = false
}
// Parity with the phase guard above: never lean on two invariants
// (.ready ⇒ client) where one guard suffices.
guard let client else { return .failed }
do {
let result = try await client!.request("session/prompt", params: .object([
"sessionId": .string(sid),
"prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]),
]))
let result = try await client.request(
"session/prompt",
params: .object([
"sessionId": .string(sid),
"prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]),
]),
timeout: Self.promptTimeout,
)
let stopReason = result?.objectValue?["stopReason"]?.stringValue ?? ""
// A completed turn always carries stopReason (ACP spec). An
// engine that omits it did not complete the turn — the pass
// must not advance on a maybe (review: empty-stopReason bug).
guard !stopReason.isEmpty else { return .failed }
if stopReason == "refusal" {
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
}
if stopReason == "cancelled" {
return .cancelled
}
return .ended(stopReason: stopReason)
} catch {
// Transport failure mid-turn: the crash path owns the UX; keep the
// partial transcript (never data loss).
guard case .crashed = phase else {
if case .crashed = phase {
// Crash card already owns the failure surface.
} else {
rows.append(SessionRow(content: .text("Mentor: connection lost — \(error.localizedDescription)")))
return
}
return .failed
}
}
@@ -294,9 +350,12 @@ final class MentorSessionModel {
guard let update = params.objectValue?["update"]?.objectValue else { return }
let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
switch kind {
case "agent_message_chunk", "agent_thought_chunk":
case "agent_message_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingText += text
case "agent_thought_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingThought += text
case "user_message_chunk":
// The engine echoes the user message; we already rendered it.
break
@@ -329,15 +388,25 @@ final class MentorSessionModel {
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 = object["pattern"]?.stringValue,
let problemValue = object["problem"]?.stringValue else { return nil }
guard let patternValue = card["pattern"]?.stringValue,
let problemValue = card["problem"]?.stringValue else { return nil }
pattern = patternValue
problem = problemValue
diagnosticQuestion = object["diagnosticQuestion"]?.stringValue ?? ""
fix = object["fix"]?.stringValue ?? ""
anchor = object["anchor"]?.stringValue ?? ""
provenance = object["provenance"]?.stringValue ?? "engine"
status = object["status"]?.stringValue ?? "proposed"
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"
}
}
+11 -1
View File
@@ -58,7 +58,8 @@ final class AppGateState {
.appendingPathComponent("Documents/Museion", isDirectory: true)
}
@main
/// #23: no `@main` here — MuseionLauncher (MCPServer.swift) branches
/// between the app and the headless `--serve-mcp` tool server.
struct MuseionApp: App {
@State private var gate = AppGateState()
@@ -79,6 +80,15 @@ struct MuseionApp: App {
AboutEngineView()
}
.windowResizability(.contentSize)
// #23 follow-up (dogfood): the Fix Cards palette — a floating
// window for the open piece's stored cards, opened from the
// mentor pass bar. Stays visible while the verdict is worked
// through in the editor.
Window("Fix Cards", id: "fix-cards") {
FixCardsPalette()
.environment(gate)
}
.defaultSize(width: 340, height: 540)
.commands {
// SwiftUI has no About scene on macOS; replace the stock panel with our window.
CommandGroup(replacing: .appInfo) {
+70
View File
@@ -0,0 +1,70 @@
//
// Pass.swift
// Museion
//
// #24 (S3.1): the pass substrate's shared vocabulary — PassKind (the app's
// own Pass 1 / Pass 2 names; the skill stack's vocabulary stays engine-side,
// CONTEXT.md) and PassContext, the minimal engine-facing prompt shape.
//
import Foundation
/// One structured critique pass over a Piece (#24). Pass 1 = paragraph
/// level and up; Pass 2 = sentence level and below. App vocabulary only —
/// strictly 'Pass 1'/'Pass 2' (CONTEXT.md).
nonisolated enum PassKind: String, CaseIterable {
case pass1 = "Pass 1"
case pass2 = "Pass 2"
/// What the pass critiques (CONTEXT.md).
var level: String {
switch self {
case .pass1: "paragraph level and up"
case .pass2: "sentence level and below"
}
}
/// The fixed pre-pass snapshot filename in `<piece>/passes/` — latest
/// per pass type kept (a re-run overwrites in place).
var snapshotFileName: String {
switch self {
case .pass1: "pass-1.md"
case .pass2: "pass-2.md"
}
}
/// The Pass State a completed pass advances to.
var doneState: Post.PassState {
switch self {
case .pass1: .pass1Done
case .pass2: .pass2Done
}
}
}
/// The engine-facing pass context (#24, PRD G6): pass name, piece path,
/// tool reminders — the methodology itself lives engine-side and never
/// travels through the app.
nonisolated enum PassContext {
/// The minimal engine-facing prompt for one pass over one piece.
/// Pinned shape — keep it a small constant, not a template system.
/// Restored contract (#23, museion-tools rail): findings travel as
/// fix-card tool calls (submit_fix_cards) — the reply carries the
/// verdict, never the findings.
static func stub(kind: PassKind, pieceURL: URL, hasResearch: Bool) -> String {
"Pass \(kind.rawValue) — \(kind.level).\nPiece: \(pieceURL.path)\n"
+ (hasResearch
? "Research notes: \(pieceURL.deletingLastPathComponent().appendingPathComponent("research").path)\n"
: "")
+ "Critique the piece for this pass. Deliver the verdict in your reply — "
+ "findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder."
}
/// Honest app-side token estimate BEFORE a pass runs (PRD: predictable,
/// shown before, never a deterrent).
static func estimateTokens(kind: PassKind, body: String, pieceURL: URL, hasResearch: Bool) -> Int {
// chars/4 — the standard ~4-characters-per-token approximation, rounded up.
let total = (stub(kind: kind, pieceURL: pieceURL, hasResearch: hasResearch) + body).count
return (total + 3) / 4
}
}
+51
View File
@@ -567,3 +567,54 @@ nonisolated enum PostStore {
return lines.joined(separator: "\n")
}
}
// MARK: Pass substrate (#24)
/// #24 (S3.1): the pass write side — pre-pass snapshots and monotonic
/// Pass State advancement. Same file as the enum: `private` members
/// (folder/existingStamp/stamped) stay reachable at file scope.
nonisolated extension PostStore {
/// #24 (S3.1): pre-pass snapshot — the body exactly as it stood when
/// the pass was invoked, written verbatim to
/// `<piece>/passes/<kind.snapshotFileName>`. Fixed filename per pass
/// type: a re-run overwrites, so the LATEST pre-pass body per type
/// survives (running a pass never destroys text). Body only, no
/// frontmatter — it is the writer's diff anchor against post.md. A
/// vanished piece throws (a snapshot never resurrects, #18).
static func snapshotPass(id: String, kind: PassKind, body: String, home: URL) throws {
guard let dir = folder(of: id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
let passes = dir.appendingPathComponent("passes", isDirectory: true)
try FileManager.default.createDirectory(at: passes, withIntermediateDirectories: true)
try body.write(to: passes.appendingPathComponent(kind.snapshotFileName), atomically: true, encoding: .utf8)
}
/// #24 (S3.1): advance `pass_state` when a pass completes. Monotonic:
/// the new state is the higher of the file's current state and the
/// pass's doneState — passes run in ANY order, so a Pass 1 completing
/// on a Pass-2 Done piece never regresses it. Body/origin/type ride the
/// existingStamp→stamped round-trip unchanged (same preservation as
/// `overwrite`). Returns the state now stamped. A vanished piece throws.
static func advancePassState(id: String, kind: PassKind, home: URL) throws -> Post.PassState {
let piece = try existingStamp(id: id, home: home)
let advanced = higherState(piece.passState, kind.doneState)
try stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
return advanced
}
/// #24: Pass State maturity order — First Draft < Pass-1 Done <
/// Pass-2 Done. Private: state advancement is the only consumer (making
/// `Post.PassState` Comparable would widen the public surface for it).
private static func higherState(_ current: Post.PassState, _ completed: Post.PassState) -> Post.PassState {
func rank(_ state: Post.PassState) -> Int {
switch state {
case .firstDraft: 0
case .pass1Done: 1
case .pass2Done: 2
}
}
return rank(current) >= rank(completed) ? current : completed
}
}
+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
}
}
+1 -1
View File
@@ -147,7 +147,7 @@ struct PostsPaneView: View {
}
private var mentorColumn: some View {
MentorPaneView(model: mentor, binaryPath: mentorBinaryPath)
MentorPaneView(model: mentor, binaryPath: mentorBinaryPath, posts: model, home: home)
.frame(width: DesignTokens.mentorWidth)
}
}
+56 -3
View File
@@ -3,7 +3,9 @@
// Museion
//
// S2.1 provisioning (#47): create the museion profile via the Hermes CLI,
// then seed the bundled writing skills additively (#43/#45/#46).
// then seed the bundled writing skills additively (#43/#45/#46), then
// register museion-tools via `hermes -p museion mcp add` (#23 slice 2 —
// the CLI rail only, never hand-written mcp_servers YAML, #44).
//
import Foundation
@@ -16,6 +18,7 @@ nonisolated enum ProfileProvisioner {
enum Phase: String, Equatable, Sendable {
case create = "couldn't set up the writing profile"
case copy = "couldn't copy the writing skills"
case register = "couldn't register the writing tools"
}
enum Outcome: Equatable, Sendable {
@@ -23,15 +26,19 @@ nonisolated enum ProfileProvisioner {
case failed(phase: Phase, excerpt: String)
}
/// One idempotent pass: create the profile if missing, seed missing skills (#45).
/// One idempotent pass: create the profile if missing, seed missing skills
/// (#45), register museion-tools when missing (#23).
/// - Parameters:
/// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes).
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
/// - payloadRoot: bundled writing-skills payload dir (tests inject; default in-bundle).
/// - serverBinaryPath: MCP server the engine spawns — this app's binary with
/// `--serve-mcp` (tests inject; nil skips registration).
static func perform(
hermesBinary: String?,
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
payloadRoot: String = defaultPayloadRoot(),
serverBinaryPath: String? = Bundle.main.executableURL?.path,
timeout: TimeInterval = 60,
) -> Outcome {
let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
@@ -56,7 +63,18 @@ nonisolated enum ProfileProvisioner {
}
// Phase 2 — additive seed per seed-manifest.txt (#46).
return seedSkills(payloadRoot: payloadRoot, profileDir: profileDir)
let seeded = seedSkills(payloadRoot: payloadRoot, profileDir: profileDir)
guard case .seeded = seeded else { return seeded }
// Phase 3 — museion-tools registration (#23 slice 2). nil on either
// binary is the test-injection seam; production always has both after a
// gate pass (the server IS this app's binary).
guard let hermesBinary, let serverBinaryPath else {
Logger(subsystem: subsystem, category: "provisioning")
.info("museion-tools registration skipped: engine or server binary missing")
return seeded
}
return registerTools(seeded, hermesBinary: hermesBinary, serverBinaryPath: serverBinaryPath, timeout: timeout)
}
/// The bundled payload ships as a plain Resources directory (#46 map decision).
@@ -129,6 +147,41 @@ nonisolated enum ProfileProvisioner {
return .seeded(copied: copied, present: present)
}
/// #23 slice 2: register museion-tools into the profile exactly once, via
/// the hermes CLI only — the provisioner never writes mcp_servers YAML
/// itself (#44). `mcp list` first: a re-add would prompt "Overwrite? [y/N]"
/// interactively; the skip avoids that branch. ponytail: a stale command
/// path after the app moves is refreshed manually via
/// `hermes -p museion mcp remove museion-tools`.
private static func registerTools(
_ seeded: Outcome,
hermesBinary: String,
serverBinaryPath: String,
timeout: TimeInterval,
) -> Outcome {
let list = EngineProbe.execute([hermesBinary, "-p", "museion", "mcp", "list"], timeout: timeout)
if list.stdout.contains("museion-tools") {
return seeded
}
let add = EngineProbe.execute(
[
hermesBinary, "-p", "museion", "mcp", "add", "museion-tools",
"--command", serverBinaryPath, "--args", "--serve-mcp",
],
timeout: timeout,
stdin: String(repeating: "y\n", count: 4), // answers "Enable all tools? [Y/n]" — and survives
// profile-startup stdin consumers (observed live: a seeded profile burned
// one line before the prompt; a single y cancelled the save)
)
// Verified wire contract: exit 0 + "Saved 'museion-tools'" on stdout.
guard add.exitCode == 0, add.stdout.contains("Saved 'museion-tools'") else {
return logFailure(.failed(phase: .register, excerpt: excerpt(add)))
}
Logger(subsystem: subsystem, category: "provisioning")
.info("registered museion-tools via hermes CLI (command: \(serverBinaryPath, privacy: .public))")
return seeded
}
/// Sweep `.name-UUID` temp dirs left by an interrupted copy+rename; the next
/// pass re-copies the skill, but the orphan would linger forever otherwise.
private static func sweepOrphanedTemps(_ skillsDir: String) {