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
+2595 -138

No files matched your search

+4 -3
View File
@@ -102,6 +102,7 @@ When the user requests a durable behavior change, record it here or in the relev
- Never commit, push, or comment on the forge autonomously — explicit authorization each time. - Never commit, push, or comment on the forge autonomously — explicit authorization each time.
- Development targets what the maintainer runs (latest Xcode/Swift, macOS 26.5+); never pin toolchain versions in CI or scripts. - Development targets what the maintainer runs (latest Xcode/Swift, macOS 26.5+); never pin toolchain versions in CI or scripts.
- Before implementing a ticket whose `## Blocked by` list contains an OPEN issue, stop and ask — the `ready-for-agent` label does not override open dependency edges, and noticing the conflict only in the final report is not notification (2026-10-19, #24/#23).
## Child DOX Index ## Child DOX Index
@@ -131,7 +132,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (3477 symbols, 10588 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. This project is indexed by GitNexus as **museion** (3794 symbols, 12054 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -179,6 +180,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start --> <!-- write-log: window-start -->
| Date | Log | | Date | Log |
|------|-----| |------|-----|
| 2026-10-20 | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](docs/devlog/20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) |
| 2026-10-19 | [20261019-issue123-ptacek-fold-text-landings_log.md](docs/devlog/20261019-issue123-ptacek-fold-text-landings_log.md) | | 2026-10-19 | [20261019-issue123-ptacek-fold-text-landings_log.md](docs/devlog/20261019-issue123-ptacek-fold-text-landings_log.md) |
| 2026-10-19 | [20261019-issue115-prose-list-shortcuts_log.md](docs/devlog/20261019-issue115-prose-list-shortcuts_log.md) | | 2026-10-19 | [20261019-issue115-prose-list-shortcuts_log.md](docs/devlog/20261019-issue115-prose-list-shortcuts_log.md) |
| 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) | | 2026-10-16 | [20261016-issue114-convert-to-post_log.md](docs/devlog/20261016-issue114-convert-to-post_log.md) |
@@ -187,5 +189,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-15 | [20261015-issue109-outline-type-outliner_log.md](docs/devlog/20261015-issue109-outline-type-outliner_log.md) | | 2026-10-15 | [20261015-issue109-outline-type-outliner_log.md](docs/devlog/20261015-issue109-outline-type-outliner_log.md) |
| 2026-10-13 | [20261013-issue108-library-ui-archive-audits_log.md](docs/devlog/20261013-issue108-library-ui-archive-audits_log.md) | | 2026-10-13 | [20261013-issue108-library-ui-archive-audits_log.md](docs/devlog/20261013-issue108-library-ui-archive-audits_log.md) |
| 2026-10-13 | [20261013-issue107-storage-substrate-projects-archive_log.md](docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md) | | 2026-10-13 | [20261013-issue107-storage-substrate-projects-archive_log.md](docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md) |
| 2026-10-12 | [20261012-issue22-import-external_log.md](docs/devlog/20261012-issue22-import-external_log.md) | | 2026-10-12 | [20261012-issue22-import-external_log.md](docs/devlog/20261012-issue22-import-external_log.md) |<!-- write-log: window-end -->
| 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) |<!-- write-log: window-end -->
+3
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added ### Added
- **mentor:** museion-tools MCP server + Fix Cards (#23, #24 rails) — the app binary grows a headless `--serve-mcp` role speaking NDJSON JSON-RPC on stdio, exposing `query_learnings` (the piece's visible learnings) and `submit_fix_cards` (ADR-0006 cards, anchor-validated against post.md; stale anchors land flagged, never rejected) registered into the museion profile at provisioning; cards persist per-piece under `<piece>/cards/` and surface live in a floating Fix Cards palette (opened from the mentor pass bar, `pass N · lane · emitter` meta when the engine stamps `provenance.pass`); the transcript renders card tool calls as one-line events, the pass verdict references findings by title only (persona v1.3: tools work in silence, the card is the finding's only full statement), and a Debug checkbox (off by default) gates the session/tool chatter writers never wanted
- **skills:** fix-card lanes + card-emitting doctrine (#123, text landings of #118/#119/#121) — every Fix Card declares a lane (mechanical: the whole fix is table-computable and the only lane Apply executes; demonstration: one annotated example, closed Done/Skip) and an emitter (lint | engine; the engine never re-cards a live lint finding); the pass persona emits one ranked `submit_fix_cards` call at pass end, capped at ten, Learnings-resonant first; the Knife floor gains writer-praise immunity; deslop's tables gain the actually/unfortunately filler cuts and the utilize/utilization→use mapping; CONTEXT.md adds the Emitter and Done terms, ADR-0006 the lane/emitter fields, and the sample pass a mechanical-lane exemplar (FC-10) - **skills:** fix-card lanes + card-emitting doctrine (#123, text landings of #118/#119/#121) — every Fix Card declares a lane (mechanical: the whole fix is table-computable and the only lane Apply executes; demonstration: one annotated example, closed Done/Skip) and an emitter (lint | engine; the engine never re-cards a live lint finding); the pass persona emits one ranked `submit_fix_cards` call at pass end, capped at ten, Learnings-resonant first; the Knife floor gains writer-praise immunity; deslop's tables gain the actually/unfortunately filler cuts and the utilize/utilization→use mapping; CONTEXT.md adds the Emitter and Done terms, ADR-0006 the lane/emitter fields, and the sample pass a mechanical-lane exemplar (FC-10)
- **prose:** list shortcuts (v1.2 S5) — when the caret sits on a markdown list line, Tab/⇧Tab indent/outdent the item (wrapped lines ride along, the caret follows), and ⌥↑/⌥↓ move the item with its subtree among siblings; every structural edit is one undo step over the plain text store. List parents fold visually: a gutter chevron collapses the children to a rust `▸` with a `⋯ N` summary after the parent's line — folding is view state and never edits the buffer (issue #115) - **prose:** list shortcuts (v1.2 S5) — when the caret sits on a markdown list line, Tab/⇧Tab indent/outdent the item (wrapped lines ride along, the caret follows), and ⌥↑/⌥↓ move the item with its subtree among siblings; every structural edit is one undo step over the plain text store. List parents fold visually: a gutter chevron collapses the children to a rust `▸` with a `⋯ N` summary after the parent's line — folding is view state and never edits the buffer (issue #115)
@@ -42,5 +44,6 @@ All notable changes to this project will be documented in this file. The format
### Fixed ### Fixed
- **mentor:** live passes no longer read as crashes — `session/prompt` waits pass-length (1800 s, not the 15 s request default that abandoned working turns with a false "connection lost"), a liveness row shows the engine thinking, Stop stays for the whole turn, and a missing `stopReason` never advances a pass
- **workspace:** doubled View menu — "Toggle Reading Mode" (#68) sat in its own `CommandMenu("View")`, putting a second View menu in the menu bar beside the system one; it now joins the system View menu (`CommandGroup(after: .toolbar)`), ⌘R and behavior unchanged (issue #84) - **workspace:** doubled View menu — "Toggle Reading Mode" (#68) sat in its own `CommandMenu("View")`, putting a second View menu in the menu bar beside the system one; it now joins the system View menu (`CommandGroup(after: .toolbar)`), ⌘R and behavior unchanged (issue #84)
- **acp:** mentor pane against adapter 0.21.5 — `session/new` now sends the newly required `mcpServers` list (empty: Museion ships none); its absence was rejected as invalid params and wrongly surfaced as "the mentor engine stopped" when the engine was fine. The advisory version-drift note now compares base versions, so build metadata (`0.21.5+2177.g735e426` recorded vs `0.21.5` reported) no longer fabricates a mismatch on every launch; real drift still fires. - **acp:** mentor pane against adapter 0.21.5 — `session/new` now sends the newly required `mcpServers` list (empty: Museion ships none); its absence was rejected as invalid params and wrongly surfaced as "the mentor engine stopped" when the engine was fine. The advisory version-drift note now compares base versions, so build metadata (`0.21.5+2177.g735e426` recorded vs `0.21.5` reported) no longer fabricates a mismatch on every launch; real drift still fires.
+15 -8
View File
@@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Local Contracts ## 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). - `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`. - 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. - 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). - `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. - `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). - `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). - `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).
- `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 - `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. - `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. - `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). - `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) ## 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. - `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 writes nothing to the profile config — never an `mcp_servers` entry (#44 negative invariant, test-pinned). - 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. - 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) ## 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. - 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). - 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) ## 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. - `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. - `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), 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). - `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). - 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. - 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 @MainActor
@Observable @Observable
final class EditorSession { 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 let target: SessionTarget
private let debounce: Duration private let debounce: Duration
+24 -3
View File
@@ -86,14 +86,31 @@ nonisolated enum EngineProbe {
return result return result
} }
/// Run a process with stdin closed, capture stdout/stderr, kill after `timeout`. /// Run a process, capture stdout/stderr, kill after `timeout`. `stdin` (when
static func execute(_ arguments: [String], timeout: TimeInterval) -> ProcessOutput { /// 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] let path = arguments[0]
guard FileManager.default.isExecutableFile(atPath: path) else { return ProcessOutput(exitCode: -1) } guard FileManager.default.isExecutableFile(atPath: path) else { return ProcessOutput(exitCode: -1) }
let process = Process() let process = Process()
process.executableURL = URL(fileURLWithPath: path) process.executableURL = URL(fileURLWithPath: path)
process.arguments = Array(arguments.dropFirst()) process.arguments = Array(arguments.dropFirst())
// 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 process.standardInput = FileHandle.nullDevice
}
let stdoutPipe = Pipe(), stderrPipe = Pipe() let stdoutPipe = Pipe(), stderrPipe = Pipe()
process.standardOutput = stdoutPipe process.standardOutput = stdoutPipe
@@ -109,7 +126,11 @@ nonisolated enum EngineProbe {
Thread.sleep(forTimeInterval: 0.01) Thread.sleep(forTimeInterval: 0.01)
} }
if process.isRunning { 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") 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}"#
}
}
+224 -59
View File
@@ -13,12 +13,29 @@ import SwiftUI
struct MentorPaneView: View { struct MentorPaneView: View {
@State private var draft = "" @State private var draft = ""
@State private var model: MentorSessionModel @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). /// Set post-gate by ContentView: the probe's winning binary (no re-probe).
var binaryPath: String? 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) _model = State(initialValue: model)
self.binaryPath = binaryPath self.binaryPath = binaryPath
self.posts = posts
self.home = home
} }
var body: some View { var body: some View {
@@ -30,6 +47,30 @@ struct MentorPaneView: View {
ProgressView("Starting the mentor engine…") ProgressView("Starting the mentor engine…")
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
case .ready: 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 transcript
Divider() Divider()
inputBar 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 // MARK: Header
private var header: some View { private var header: some View {
@@ -75,6 +126,11 @@ struct MentorPaneView: View {
.foregroundStyle(.tertiary) .foregroundStyle(.tertiary)
.textSelection(.enabled) .textSelection(.enabled)
} }
Toggle("Debug", isOn: $debugRows)
.toggleStyle(.checkbox)
.controlSize(.mini)
.foregroundStyle(.tertiary)
.help("Show session updates, tool calls, and engine thinking.")
} }
.padding(.horizontal, 12) .padding(.horizontal, 12)
// #90: pane heads align at the export's 52px — same height as the // #90: pane heads align at the export's 52px — same height as the
@@ -83,35 +139,56 @@ struct MentorPaneView: View {
.frame(minHeight: 52) .frame(minHeight: 52)
} }
// MARK: Pass surface (#24, S3.1)
private var passKind: PassKind? {
switch mode {
case .pass1: .pass1
case .pass2: .pass2
case .chat: nil
}
}
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 // MARK: Transcript
private var transcript: some View { private var transcript: some View {
ScrollViewReader { proxy in
ScrollView { ScrollView {
LazyVStack(alignment: .leading, spacing: 10) { LazyVStack(alignment: .leading, spacing: 10) {
ForEach(model.rows) { row in ForEach(model.rows.filter { debugRows || Self.isWritingRow($0) }) { row in
rowView(row) rowView(row)
.id(row.id) }
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 { if !model.streamingText.isEmpty {
textRow("Mentor: \(model.streamingText)") textRow("Mentor: \(model.streamingText)")
.id("streaming")
} }
} }
.padding(12) .padding(12)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
.onChange(of: model.rows.count) { scrollToBottom(proxy) } // #24 fix: programmatic scrollTo raced the growing lazy rows and
.onChange(of: model.streamingText) { scrollToBottom(proxy) } // mislanded at the TOP; the native bottom anchor needs no scroll code.
} .defaultScrollAnchor(.bottom)
}
private func scrollToBottom(_ proxy: ScrollViewProxy) {
if let last = model.rows.last?.id {
proxy.scrollTo(last, anchor: .bottom)
} else {
proxy.scrollTo("streaming", anchor: .bottom)
}
} }
@ViewBuilder @ViewBuilder
@@ -119,8 +196,12 @@ struct MentorPaneView: View {
switch row.content { switch row.content {
case let .text(text): case let .text(text):
textRow(text) textRow(text)
case let .thought(text):
ThoughtRow(text: text)
case let .fixCard(card): 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): case let .raw(kind, json):
RawUpdateRow(kind: kind, json: json) RawUpdateRow(kind: kind, json: json)
} }
@@ -132,9 +213,80 @@ struct MentorPaneView: View {
.frame(maxWidth: .infinity, alignment: .leading) .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 // MARK: Input
private var inputBar: some View { private var inputBar: some View {
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 {
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
Text("Mentor is working — Stop to interrupt.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
HStack(spacing: 8) { HStack(spacing: 8) {
TextField("Ask the mentor…", text: $draft, axis: .vertical) TextField("Ask the mentor…", text: $draft, axis: .vertical)
.textFieldStyle(.plain) .textFieldStyle(.plain)
@@ -157,6 +309,7 @@ struct MentorPaneView: View {
.controlSize(.regular) .controlSize(.regular)
} }
} }
}
.padding(12) .padding(12)
.disabled(model.phase.isReady == false) .disabled(model.phase.isReady == false)
} }
@@ -207,57 +360,69 @@ struct MentorPaneView: View {
.padding(24) .padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity) .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
private struct FixCardRow: View { /// action. Additive chrome above the mentor pane's shared transcript.
let card: FixCard private struct PassBarView: View {
let kind: PassKind
let posts: PostsModel?
let home: URL?
let model: MentorSessionModel
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 6) { VStack(alignment: .leading, spacing: 8) {
Label(card.pattern, systemImage: "rectangle.and.pencil.and.ellipsis") Text(description)
.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) .font(.callout)
.foregroundStyle(.secondary) .foregroundStyle(DesignTokens.muted)
}
if !card.fix.isEmpty {
Text("Fix: \(card.fix)").font(.callout)
}
Text(card.provenance + " · " + card.status)
.font(.caption2)
.foregroundStyle(.tertiary)
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.background(.quaternary.opacity(0.3), in: RoundedRectangle(cornerRadius: 8)) HStack {
Text(stateLabel)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer()
actions
} }
} }
.padding(.horizontal, 12)
.padding(.bottom, 10)
}
private struct RawUpdateRow: View { /// What the pass does + the predictable cost — or the honest ask when
let kind: String /// no piece is open.
let json: String private var description: String {
guard let posts, let session = posts.session, session.postID != nil else {
var body: some View { return "Open a post to run a pass."
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) let tokens = PassContext.estimateTokens(
kind: kind, body: session.text, pieceURL: session.passPieceURL, hasResearch: session.hasResearch,
)
return "Critiques \(kind.level) · ~\(tokens.formatted()) tokens"
}
/// 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)
}
.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)
} }
} }
} }
+86 -17
View File
@@ -15,6 +15,9 @@ import os
struct SessionRow: Identifiable { struct SessionRow: Identifiable {
enum Content { enum Content {
case text(String) 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 fixCard(FixCard)
case raw(kind: String, json: String) case raw(kind: String, json: String)
} }
@@ -36,6 +39,17 @@ struct FixCard {
var status: String 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 + bridge state machine. Lazy lifecycle: the engine spawns when the
/// pane opens its first session and stays alive for the app's life (map /// pane opens its first session and stays alive for the app's life (map
/// decision: child lifecycle). /// decision: child lifecycle).
@@ -62,6 +76,10 @@ final class MentorSessionModel {
private(set) var rows: [SessionRow] = [] private(set) var rows: [SessionRow] = []
/// Streaming buffer for the in-flight agent message; flushed to a row on completion. /// Streaming buffer for the in-flight agent message; flushed to a row on completion.
private(set) var streamingText = "" 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). /// Advisory engine-version verdict (map decision: advisory, never blocks).
private(set) var versionNote: String? private(set) var versionNote: String?
/// The running engine's version, from the initialize handshake (always visible). /// The running engine's version, from the initialize handshake (always visible).
@@ -126,6 +144,7 @@ final class MentorSessionModel {
clientRef = nil clientRef = nil
sessionId = nil sessionId = nil
streamingText = "" streamingText = ""
streamingThought = ""
phase = .starting phase = .starting
await startEngine() await startEngine()
} }
@@ -216,16 +235,36 @@ final class MentorSessionModel {
phase = .ready(sessionId: sid) 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 — /// stop_reason response ends the turn (refusal maps to a plain note —
/// wire-verified edge semantics). /// wire-verified edge semantics). Returns how the turn ended (#24 seam):
func sendPrompt(_ text: String) async { /// 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) 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 lastPrompt = prompt
rows.append(SessionRow(content: .text("You: \(prompt)"))) rows.append(SessionRow(content: .text(label ?? "You: \(prompt)")))
isStreaming = true isStreaming = true
defer { 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. // Flush any streamed-but-unfinished agent text into a row.
if !streamingText.isEmpty { if !streamingText.isEmpty {
rows.append(SessionRow(content: .text("Mentor: \(streamingText)"))) rows.append(SessionRow(content: .text("Mentor: \(streamingText)")))
@@ -233,22 +272,39 @@ final class MentorSessionModel {
} }
isStreaming = false 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 { do {
let result = try await client!.request("session/prompt", params: .object([ let result = try await client.request(
"session/prompt",
params: .object([
"sessionId": .string(sid), "sessionId": .string(sid),
"prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]), "prompt": .array([.object(["type": .string("text"), "text": .string(prompt)])]),
])) ]),
timeout: Self.promptTimeout,
)
let stopReason = result?.objectValue?["stopReason"]?.stringValue ?? "" 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" { if stopReason == "refusal" {
rows.append(SessionRow(content: .text("Mentor: (refused the prompt)"))) rows.append(SessionRow(content: .text("Mentor: (refused the prompt)")))
} }
if stopReason == "cancelled" {
return .cancelled
}
return .ended(stopReason: stopReason)
} catch { } catch {
// Transport failure mid-turn: the crash path owns the UX; keep the // Transport failure mid-turn: the crash path owns the UX; keep the
// partial transcript (never data loss). // 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)"))) 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 } guard let update = params.objectValue?["update"]?.objectValue else { return }
let kind = update["sessionUpdate"]?.stringValue ?? "unknown" let kind = update["sessionUpdate"]?.stringValue ?? "unknown"
switch kind { switch kind {
case "agent_message_chunk", "agent_thought_chunk": case "agent_message_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? "" let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingText += text streamingText += text
case "agent_thought_chunk":
let text = update["content"]?.objectValue?["text"]?.stringValue ?? ""
streamingThought += text
case "user_message_chunk": case "user_message_chunk":
// The engine echoes the user message; we already rendered it. // The engine echoes the user message; we already rendered it.
break break
@@ -329,15 +388,25 @@ final class MentorSessionModel {
private extension FixCard { private extension FixCard {
init?(rawInput: JSONValue?) { init?(rawInput: JSONValue?) {
guard let object = rawInput?.objectValue else { return nil } 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. // A fix-card-shaped payload carries at least pattern + problem.
guard let patternValue = object["pattern"]?.stringValue, guard let patternValue = card["pattern"]?.stringValue,
let problemValue = object["problem"]?.stringValue else { return nil } let problemValue = card["problem"]?.stringValue else { return nil }
pattern = patternValue pattern = patternValue
problem = problemValue problem = problemValue
diagnosticQuestion = object["diagnosticQuestion"]?.stringValue ?? "" diagnosticQuestion = card["diagnosticQuestion"]?.stringValue
fix = object["fix"]?.stringValue ?? "" ?? card["diagnostic_question"]?.stringValue ?? ""
anchor = object["anchor"]?.stringValue ?? "" fix = card["fix"]?.stringValue ?? ""
provenance = object["provenance"]?.stringValue ?? "engine" anchor = card["anchor"]?.stringValue
status = object["status"]?.stringValue ?? "proposed" ?? 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) .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 { struct MuseionApp: App {
@State private var gate = AppGateState() @State private var gate = AppGateState()
@@ -79,6 +80,15 @@ struct MuseionApp: App {
AboutEngineView() AboutEngineView()
} }
.windowResizability(.contentSize) .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 { .commands {
// SwiftUI has no About scene on macOS; replace the stock panel with our window. // SwiftUI has no About scene on macOS; replace the stock panel with our window.
CommandGroup(replacing: .appInfo) { 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") 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 /// selects; the sheet is modal in its window, and the convert itself
/// re-derives everything (flush, disk read) at answer time. /// re-derives everything (flush, disk read) at answer time.
private(set) var pendingConversion: PendingConversion? 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). /// Last failed-op message surfaced in the editor (nil = clean).
private(set) var lastError: String? private(set) var lastError: String?
/// Home the watcher is bound to; also the rescan target. /// Home the watcher is bound to; also the rescan target.
@@ -199,6 +206,9 @@ final class PostsModel {
if openSession === session, let openDiskText { if openSession === session, let openDiskText {
openSession?.diskDidChange(diskText: 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) // MARK: Own ops (route through the same rescan, #61)
@@ -240,6 +250,7 @@ final class PostsModel {
proseOverridePostID = nil // #111: same death, same clearing proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil selectedPostID = nil
openPieceCards = [] // #23: no open piece, no cards
} }
/// #109: New Outline — newPost's draft path with an outline draft instead: /// #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 proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the draft displaces any held ask outlineGuardPieceID = nil // #111: the draft displaces any held ask
selectedPostID = nil selectedPostID = nil
openPieceCards = [] // #23: no open piece, no cards
} }
/// #92: dismiss the external guest slot, flushing pending edits (the /// #92: dismiss the external guest slot, flushing pending edits (the
@@ -316,6 +328,7 @@ final class PostsModel {
pendingProject = nil pendingProject = nil
lastDraftWasOutline = false lastDraftWasOutline = false
selectedPostID = id selectedPostID = id
refreshCards(home: home) // #23: nil session — the held ask shows no cards
return return
} }
// The prior session was torn down above; openUnguarded's guards // The prior session was torn down above; openUnguarded's guards
@@ -556,6 +569,7 @@ final class PostsModel {
lastDraftWasOutline = false // #109: same death, same clearing lastDraftWasOutline = false // #109: same death, same clearing
proseOverridePostID = nil // #111: same death, same clearing proseOverridePostID = nil // #111: same death, same clearing
outlineGuardPieceID = nil // #111: the guest displaces any held ask outlineGuardPieceID = nil // #111: the guest displaces any held ask
openPieceCards = [] // #23: the guest is not a piece
externalSession = EditorSession(target: .externalFile(target)) externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true { if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed." 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 outlineGuardPieceID = nil // the open displaces any held ask
selectedPostID = id selectedPostID = id
wireSession() 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 { private var mentorColumn: some View {
MentorPaneView(model: mentor, binaryPath: mentorBinaryPath) MentorPaneView(model: mentor, binaryPath: mentorBinaryPath, posts: model, home: home)
.frame(width: DesignTokens.mentorWidth) .frame(width: DesignTokens.mentorWidth)
} }
} }
+56 -3
View File
@@ -3,7 +3,9 @@
// Museion // Museion
// //
// S2.1 provisioning (#47): create the museion profile via the Hermes CLI, // 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 import Foundation
@@ -16,6 +18,7 @@ nonisolated enum ProfileProvisioner {
enum Phase: String, Equatable, Sendable { enum Phase: String, Equatable, Sendable {
case create = "couldn't set up the writing profile" case create = "couldn't set up the writing profile"
case copy = "couldn't copy the writing skills" case copy = "couldn't copy the writing skills"
case register = "couldn't register the writing tools"
} }
enum Outcome: Equatable, Sendable { enum Outcome: Equatable, Sendable {
@@ -23,15 +26,19 @@ nonisolated enum ProfileProvisioner {
case failed(phase: Phase, excerpt: String) 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: /// - Parameters:
/// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes). /// - hermesBinary: absolute path to the engine binary (gate's winner; tests pass fakes).
/// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`). /// - profileRoot: profiles base dir (tests inject; default `~/.hermes/profiles`).
/// - payloadRoot: bundled writing-skills payload dir (tests inject; default in-bundle). /// - 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( static func perform(
hermesBinary: String?, hermesBinary: String?,
profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath, profileRoot: String = ("~/.hermes/profiles" as NSString).expandingTildeInPath,
payloadRoot: String = defaultPayloadRoot(), payloadRoot: String = defaultPayloadRoot(),
serverBinaryPath: String? = Bundle.main.executableURL?.path,
timeout: TimeInterval = 60, timeout: TimeInterval = 60,
) -> Outcome { ) -> Outcome {
let profileDir = (profileRoot as NSString).appendingPathComponent("museion") let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
@@ -56,7 +63,18 @@ nonisolated enum ProfileProvisioner {
} }
// Phase 2 — additive seed per seed-manifest.txt (#46). // 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). /// 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) 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 /// 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. /// pass re-copies the skill, but the orphan would linger forever otherwise.
private static func sweepOrphanedTemps(_ skillsDir: String) { private static func sweepOrphanedTemps(_ skillsDir: String) {
+186 -18
View File
@@ -17,25 +17,17 @@ import Testing
/// Builds a fake engine binary that speaks enough ACP for the M0 client. /// Builds a fake engine binary that speaks enough ACP for the M0 client.
/// `mode`: `full` answers everything; `crashAfterHandshake` exits 1 right /// `mode`: `full` answers everything; `crashAfterHandshake` exits 1 right
/// after answering initialize; `hangOnPrompt` sleeps 30 s inside prompt. /// after answering initialize; `hangOnPrompt` sleeps 30 s inside prompt;
/// `cancelOnPrompt` streams one chunk then answers stopReason "cancelled";
/// `refuseOnPrompt` answers stopReason "refusal" (no chunks).
/// The mode travels in a file next to the fake (self-locating — race-free /// The mode travels in a file next to the fake (self-locating — race-free
/// under parallel suites, same convention as ProfileProvisionerTests). /// under parallel suites, same convention as ProfileProvisionerTests).
/// The fix-card payload travels base64-encoded so shell quoting can't break. /// The fix-card payload travels base64-encoded so shell quoting can't break.
private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "full") -> String { /// Internal (not private) so later test files can reuse the fake (#24).
func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: String = "full") -> String {
let path = (dir as NSString).appendingPathComponent(name) let path = (dir as NSString).appendingPathComponent(name)
let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode") let modeFile = (dir as NSString).appendingPathComponent("\(name)-mode")
// ponytail: built field-by-field so the line stays under the lint cap. let fixCardB64 = fixCardPayloadB64()
let card: [(String, String)] = [
("pattern", "Blame tense"),
("problem", "Never pivots to choice"),
("diagnosticQuestion", "What tense?"),
("fix", "Pivot on the hinge"),
("anchor", "We should stop listening."),
("provenance", "posts/x · pass 1"),
("status", "proposed"),
]
let fixCard = card.map { "\"\($0.0)\":\"\($0.1)\"" }.joined(separator: ",")
let fixCardB64 = Data(("{" + fixCard + "}").utf8).base64EncodedString()
// ponytail: one echo per wire message — long payloads ride shell vars so // ponytail: one echo per wire message — long payloads ride shell vars so
// each line stays under the lint cap and inspectable against the schema. // each line stays under the lint cap and inspectable against the schema.
let script = """ let script = """
@@ -45,18 +37,31 @@ private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: Stri
card=$(print -- '\(fixCardB64)' | base64 -d) card=$(print -- '\(fixCardB64)' | base64 -d)
framing='{"jsonrpc":"2.0","id":' framing='{"jsonrpc":"2.0","id":'
notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-1","update":' notify='{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"sess-1","update":'
while IFS= read -r line; do while IFS= read -r line; do # print -r below, never echo — zsh's echo eats the JSON \n escapes of multi-line prompts
[[ -z "$line" ]] && continue [[ -z "$line" ]] && continue
method=$(echo "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))') method=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; print(json.load(sys.stdin).get("method",""))')
rid=$(echo "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")') rid=$(print -r -- "$line" | /usr/bin/python3 -c 'import json,sys; d=json.load(sys.stdin).get("id"); print(d if d is not None else "x")')
if [[ "$method" == "initialize" ]]; then if [[ "$method" == "initialize" ]]; then
echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}' echo $framing"$rid",'"result":{"protocolVersion":1,"agentInfo":{"name":"hermes-agent","title":"Hermes","version":"9.9.9"}}}'
[[ "$mode" == "crashAfterHandshake" ]] && exit 1 [[ "$mode" == "crashAfterHandshake" ]] && exit 1
elif [[ "$method" == "session/new" ]]; then elif [[ "$method" == "session/new" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}' echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
elif [[ "$method" == "session/prompt" ]]; then elif [[ "$method" == "session/prompt" ]]; then
if [[ "$mode" == "refuseOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"refusal"}}'
continue
fi
echo $notify'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"echo"},"messageId":"u1"}}}' echo $notify'{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"echo"},"messageId":"u1"}}}'
echo $notify'{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"weighing the structure"},"messageId":"t1"}}}'
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello "},"messageId":"m1"}}}' echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Hello "},"messageId":"m1"}}}'
if [[ "$mode" == "cancelOnPrompt" ]]; then
echo $framing"$rid",'"result":{"stopReason":"cancelled"}}'
continue
fi
if [[ "$mode" == "noStopReason" ]]; then
echo $framing"$rid",'"result":{"sessionId":"sess-1"}}'
continue
fi
echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}' echo $notify'{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"mentor."},"messageId":"m1"}}}'
echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}' echo $notify'{"sessionUpdate":"tool_call","toolCallId":"tc1","title":"submit_fix_cards","rawInput":'"$card"'}}}'
if [[ "$mode" == "hangOnPrompt" ]]; then if [[ "$mode" == "hangOnPrompt" ]]; then
@@ -76,7 +81,20 @@ private func makeFakeACP(at dir: String, name: String = "hermes-acp", mode: Stri
return path return path
} }
private func acpTempDir(_ label: String) -> String { /// The fix-card payload for the fake's tool call, base64-encoded so shell
/// quoting can never break the wire JSON. The REAL submit_fix_cards
/// argument shape (snake_case, anchor as object) — pins the nested parse;
/// the flat #14-era shape was a regression the parser never matched the
/// live rail (review).
private func fixCardPayloadB64() -> String {
let card = #"{"pattern":"Blame tense","problem":"Never pivots to choice","# +
#""diagnostic_question":"What tense?","fix":"Pivot on the hinge","# +
#""anchor":{"quote":"We should stop listening.","occurrence":1}}"#
let json = #"{"piece_path":"/tmp/piece","cards":["# + card + #"]}"#
return Data(json.utf8).base64EncodedString()
}
func acpTempDir(_ label: String) -> String {
let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)" let dir = NSTemporaryDirectory() + "museion-acp-\(label)-\(UUID().uuidString)"
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
return dir return dir
@@ -187,6 +205,156 @@ struct ACPClientTests {
} }
#expect(gone) #expect(gone)
} }
// MARK: - Turn outcome seam (#24 S3.1: sendPrompt → TurnOutcome)
// The suite hosts these model tests (not free functions like the model
// tests below) so the suite-name test filter runs them.
@MainActor
@Test func `sendPrompt returns ended end_turn and streams text`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-ended"))
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let streamed = model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("Hello mentor.")
}
return false
}
#expect(streamed)
model.shutdown()
}
@MainActor
@Test func `labeled prompt renders the label not the wire stub`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-label"))
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
// The pass orchestrator sends a long wire stub; only the label may land.
await model.sendPrompt("STUB-WIRE-PROMPT that must never surface", label: "Pass 1 · My Post")
var texts: [String] = []
for row in model.rows {
if case let .text(text) = row.content {
texts.append(text)
}
}
#expect(texts.contains("Pass 1 · My Post"))
#expect(!texts.contains { $0.contains("STUB-WIRE-PROMPT") })
model.shutdown()
}
@MainActor
@Test func `cancelled stopReason maps to TurnOutcome cancelled`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-cancel"), mode: "cancelOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .cancelled)
model.shutdown()
}
/// Review pin: a prompt response without stopReason is NOT a completed
/// turn — .failed, so a pass never advances on a maybe.
@MainActor
@Test func `missing stopReason maps to failed`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-nostop"), mode: "noStopReason")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .failed)
model.shutdown()
}
/// #23 dogfood regression pin: session/prompt's response arrives when the
/// TURN ends — minutes into a pass. The client's 15 s request default
/// abandoned live turns ("connection lost" while the engine kept working,
/// Stop vanished with isStreaming). sendPrompt must wait pass-length.
@Test func `prompt deadline is pass length not the request default`() {
#expect(MentorSessionModel.promptTimeout >= 600)
}
/// #23 dogfood: the writing-session filter — prose + card events stay,
/// raw session/tool rows and thinking are debug-only.
@Test func `writing-session filter keeps prose and cards, hides raw and thought`() {
#expect(MentorPaneView.isWritingRow(SessionRow(content: .text("Pass 1 · The piece"))))
#expect(MentorPaneView.isWritingRow(SessionRow(content: .fixCard(
FixCard(pattern: "p", problem: "q", diagnosticQuestion: "", fix: "", anchor: "", provenance: "", status: ""),
))))
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .thought("thinking…"))))
#expect(!MentorPaneView.isWritingRow(SessionRow(content: .raw(kind: "tool_call_update", json: "{}"))))
}
@MainActor
@Test func `refusal maps to ended refusal and still renders the refusal row`() async {
let fake = makeFakeACP(at: acpTempDir("outcome-refusal"), mode: "refuseOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "refusal"))
let refused = model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("(refused the prompt)")
}
return false
}
#expect(refused)
model.shutdown()
}
@MainActor
@Test func `thought chunks land in a collapsed thought row not the critique`() async {
let fake = makeFakeACP(at: acpTempDir("thought-lane"))
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
// The fake streams a thought chunk BEFORE the message chunks — the
// live shape of a pass turn (long thinking, then the critique).
let outcome = await model.sendPrompt("hello mentor")
#expect(outcome == .ended(stopReason: "end_turn"))
let thought = model.rows.contains { row in
if case let .thought(text) = row.content {
return text == "weighing the structure"
}
return false
}
#expect(thought)
// The critique text stays clean — thinking never bleeds into it.
let critique = model.rows.contains { row in
if case let .text(text) = row.content {
return text == "Mentor: Hello mentor."
}
return false
}
#expect(critique)
#expect(!model.rows.contains { row in
if case let .text(text) = row.content {
return text.contains("weighing")
}
return false
})
model.shutdown()
}
@MainActor
@Test func `transport failure mid-turn maps to TurnOutcome failed`() async throws {
let fake = makeFakeACP(at: acpTempDir("outcome-failed"), mode: "hangOnPrompt")
let model = MentorSessionModel(binaryPath: fake)
await model.openSession()
// Deterministic transport failure through the model: hangOnPrompt keeps
// the turn pending, then shutdown() closes the client — the in-flight
// session/prompt fails with a transport error, the same route a mid-turn
// engine error takes. crashAfterHandshake can't pin this: after the crash
// the phase is .crashed and sendPrompt's guard refuses before any request.
let promptTask = Task { await model.sendPrompt("hello mentor") }
for _ in 0 ..< 100 where !model.isStreaming {
try await Task.sleep(for: .milliseconds(50))
}
model.shutdown()
let outcome = await promptTask.value
#expect(outcome == .failed)
}
} }
// MARK: - Model tests // MARK: - Model tests
+6 -4
View File
@@ -18,11 +18,13 @@ Owned by the root AGENTS.md contract.
- Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked. - Non-trivial logic leaves one runnable check behind: the smallest test that fails if the logic breaks. No fixtures or per-function suites unless asked.
- `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing. - `EngineGateTests.swift` builds fake `hermes` shell scripts in temp dirs and runs them through the real `Process` path — copy that pattern for any future child-process testing.
- `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt`, default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. Only `acpTempDir` remains as a helper; crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. - `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt`, `cancelOnPrompt` — one chunk then stopReason cancelled, `refuseOnPrompt` — refusal, no chunks; default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. `makeFakeACP` + `acpTempDir` are internal (shared-helper convention) for reuse by later test files (#24); `makeStrictFakeACP` stays private. The full mode streams a `agent_thought_chunk` before the message chunks — pinning the #24 dogfood thought lane (thinking lands in a collapsed `.thought` row, never in the critique text). Crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. #24 turn-outcome seam tests live INSIDE the suite — suite-name filters (`-only-testing:MuseionTests/ACPClientTests`) do not run free functions: ended/cancelled/failed mapping, labeled prompt renders the label not the wire stub.
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests. - `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. **#23:** the fake also speaks `-p museion mcp list`/`mcp add` (marker file = already registered, invocation log for the exact add command line, one stdin line read, `mcp-add-fails` reject knob); registration tests pin fresh-add-exact-command, already-registered skip, probe-failure → `.failed(.register)`. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, `registration only via the mcp add cli rail never hand-written yaml` (config.yaml byte-identity through failed + nil-skip + CLI-registering passes — the #44 invariant as amended by #23), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
- `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. - `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects/<name>/<id>/` + `archive/<name>/<id>/` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). - `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects/<name>/<id>/` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects/<project>/<id>/post.md` placement, scan round-trip; default `.post` pinned). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved through the stamp round-trip; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test).
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. - `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `<piece>/cards/`, stale lands flagged, vanished piece + malformed card throw), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700.
- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. **#111 (S7):** the guard lifecycle — mixed outline fires + holds (no session, file untouched), prose answer opens with the routing override + an edit/flush cycle drops nothing, outline answer = consented drop on save, cancel re-guards on next open, clean outline/prose pieces open untouched, reselect of the open guarded piece is a no-op, a draft staged during the ask displaces it and survives the answer, guard fires from the scan-known type too (poll-loop rescan wait); `writeMixedOutline` is one `writeNew` call. **#114 (S4):** convert lifecycle — the open outline piece converts and REOPENS routed prose (`proseOverridePostID` set, disk `type: post`, ladder applied); an unopened piece converts without touching the open session or selection; `verbatim convert flips the posts list after the rescan` (the live-report regression pin). **#114 audit pins:** dirty-session flushes before the transform, staging warns from `session.text` (piece open) vs disk (closed), Headings aborts when the body went lossy behind an unwarned ask (and the warned-consent path proceeds), unanswered #67 conflict aborts (alert stays answerable), failed flush aborts (piece vanished), convert dismisses a held #111 guard ask as a cancel. **#23:** the card-lifecycle pins — cards pre-seeded via a direct `FixCardStore.submit` surface after select, a card landing on disk AFTER open grows the list through the watcher-driven rescan (poll pattern, no reselect), closing the piece (newPost) clears to [], archive-open path covered.
- `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · <title>" renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic).
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. - `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars. - `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit. - `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
+183
View File
@@ -0,0 +1,183 @@
//
// MCPServerWireTests.swift
// MuseionTests
//
// #23 (M2, slice 1): the museion-tools wire contract, in-process through
// MCPServer.run(lines:write:) over real JSON-RPC lines — echoed
// protocolVersion, silent notifications, typed tools/list, the full
// submit round-trip with the card on disk, isError tool failures,
// -32601 unknown method, -32700 garbage. Wire facts verified live
// against the real hermes MCP client.
//
import Foundation
@testable import Museion
import Testing
/// Run lines through the server loop, parsing every reply as JSON objects.
private func runWire(_ lines: [String]) throws -> [[String: Any]] {
var replies: [String] = []
MCPServer.run(lines: AnyIterator(lines.makeIterator())) { replies.append($0) }
return try replies.compactMap {
try JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]
}
}
/// Review pin (DoS): a line over the 1 MB frame cap answers -32600 —
/// never reaches JSONSerialization.
@Test func `oversized line answers line too long`() throws {
let big = String(repeating: "a", count: 1_048_577)
let replies = try runWire([big])
let error = replies[0]["error"] as? [String: Any]
#expect((error?["code"] as? Int) == -32600)
}
private let initializeLine = #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#
private let initializedLine = #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#
private let toolsListLine = #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#
/// The text payload of a tools/call result.
private func toolText(_ result: [String: Any]) throws -> String {
let content = try #require(result["content"] as? [[String: Any]])
return try #require(content.first?["text"] as? String)
}
struct MCPServerWireTests {
@Test func `initialize echoes client protocol version`() throws {
let replies = try runWire([initializeLine])
#expect(replies.count == 1)
#expect(replies[0]["id"] as? Int == 1)
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["protocolVersion"] as? String == "2025-06-18")
let info = try #require(result["serverInfo"] as? [String: Any])
#expect(info["name"] as? String == "museion-tools")
#expect(result["capabilities"] is [String: Any])
}
@Test func `initialize falls back to pinned protocol version`() throws {
let replies = try runWire([#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["protocolVersion"] as? String == "2025-11-25")
}
@Test func `notifications never reply`() throws {
#expect(try runWire([initializedLine]).isEmpty)
}
@Test func `ping answers empty result`() throws {
let replies = try runWire([#"{"jsonrpc":"2.0","id":9,"method":"ping"}"#])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result.isEmpty)
}
@Test func `tools list exposes both tools with schemas`() throws {
let replies = try runWire([toolsListLine])
let result = try #require(replies[0]["result"] as? [String: Any])
let tools = try #require(result["tools"] as? [[String: Any]])
#expect(Set(tools.compactMap { $0["name"] as? String }) == ["query_learnings", "submit_fix_cards"])
let submit = try #require(tools.first { $0["name"] as? String == "submit_fix_cards" })
let schema = try #require(submit["inputSchema"] as? [String: Any])
let required = try #require(schema["required"] as? [String])
#expect(required.contains("piece_path"))
#expect(required.contains("cards"))
let properties = try #require(schema["properties"] as? [String: Any])
let cardsProp = try #require(properties["cards"] as? [String: Any])
let cardItems = try #require(cardsProp["items"] as? [String: Any])
let cardRequired = try #require(cardItems["required"] as? [String])
#expect(cardRequired.contains("pattern"))
#expect(cardRequired.contains("problem"))
#expect(cardRequired.contains("anchor"))
#expect(cardRequired.contains("lane"))
#expect(cardRequired.contains("emitter"))
let cardProps = try #require(cardItems["properties"] as? [String: Any])
let anchor = try #require(cardProps["anchor"] as? [String: Any])
let anchorProps = try #require(anchor["properties"] as? [String: Any])
let occurrence = try #require(anchorProps["occurrence"] as? [String: Any])
#expect(occurrence["type"] as? String == "integer")
#expect(occurrence["default"] as? Int == 1)
let query = try #require(tools.first { $0["name"] as? String == "query_learnings" })
let querySchema = try #require(query["inputSchema"] as? [String: Any])
#expect(try #require(querySchema["required"] as? [String]) == ["piece_path"])
}
@Test func `submit and query round trip through the wire`() throws {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("mcp-wire-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
let piece = home.appendingPathComponent("projects/posts/test-piece", isDirectory: true)
try FileManager.default.createDirectory(at: piece, withIntermediateDirectories: true)
try "---\ntype: post\n---\nThe repeated anchor line.\n"
.write(to: piece.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
try "wire learning".write(to: learnings.appendingPathComponent("l.md"), atomically: true, encoding: .utf8)
// swiftlint:disable line_length
let submit = """
{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"\(piece.path)","cards":[{"pattern":"Hedging","problem":"The hedge weakens the claim.","anchor":{"quote":"repeated anchor line"},"lane":"mechanical","emitter":"lint"}]}}}
"""
// swiftlint:enable line_length
let query = """
{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"query_learnings","arguments":{"piece_path":"\(piece.path)"}}}
"""
let replies = try runWire([initializeLine, initializedLine, submit, query])
// initialize + two tool results; the notification stayed silent.
#expect(replies.count == 3)
let submitResult = try #require(replies[1]["result"] as? [String: Any])
#expect(submitResult["isError"] == nil)
let payload = try #require(
try JSONSerialization.jsonObject(with: Data(toolText(submitResult).utf8)) as? [String: Any],
)
let cards = try #require(payload["cards"] as? [[String: Any]])
#expect(cards.first?["anchor_status"] as? String == "valid")
let file = try #require(cards.first?["file"] as? String)
#expect(file.hasSuffix("-hedging.json"))
#expect(
FileManager.default.fileExists(atPath: piece.appendingPathComponent("cards/\(file)").path),
)
let queryResult = try #require(replies[2]["result"] as? [String: Any])
let learned = try #require(
try JSONSerialization.jsonObject(with: Data(toolText(queryResult).utf8)) as? [String: Any],
)
let learningsPayload = try #require(learned["learnings"] as? [[String: Any]])
#expect(learningsPayload.first?["markdown"] as? String == "wire learning")
}
@Test func `tool failures set is error`() throws {
let lines = [
// Missing piece.
// swiftlint:disable:next line_length
#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"/nonexistent/piece","cards":[{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}]}}}"#,
// Unknown tool name.
#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"wat","arguments":{}}}"#,
// Malformed arguments (piece_path missing).
#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"query_learnings","arguments":{}}}"#,
]
for line in lines {
let replies = try runWire([line])
let result = try #require(replies[0]["result"] as? [String: Any])
#expect(result["isError"] as? Bool == true, "expected isError for: \(line)")
#expect(replies[0]["error"] == nil)
let text = try toolText(result)
#expect(!text.isEmpty)
}
}
@Test func `unknown method errors 32601`() throws {
let replies = try runWire([#"{"jsonrpc":"2.0","id":6,"method":"wat/thing"}"#])
let error = try #require(replies[0]["error"] as? [String: Any])
#expect(error["code"] as? Int == -32601)
#expect(replies[0]["result"] == nil)
}
@Test func `garbage line errors 32700 with null id`() throws {
let replies = try runWire(["not json at all"])
let error = try #require(replies[0]["error"] as? [String: Any])
#expect(error["code"] as? Int == -32700)
#expect(replies[0]["id"] is NSNull)
}
}
+264
View File
@@ -0,0 +1,264 @@
//
// MCPToolsTests.swift
// MuseionTests
//
// #23 (M2, slice 1): the museion-tools tool layer — pure anchor
// validation, the submit round-trip (one snake_case JSON file per card
// under <piece>/cards/), scan ordering, and the learnings reader.
// Temp-home convention (PostStoreTests).
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home in a temp dir (PostStoreTests convention).
private func toolsHome(_ write: (URL) throws -> Void = { _ in }) throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("mcp-tools-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
try write(home)
return home
}
/// One piece under projects/posts/<id>/post.md; returns the piece folder.
/// `type: nil` writes no frontmatter block at all.
@discardableResult
private func writePiece(
_ home: URL,
id: String = "test-piece",
type: String? = "post",
body: String = "# Title\n\nThe repeated anchor line.\nAgain the repeated anchor line.\n",
) throws -> URL {
let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let block = type.map { "---\ntype: \($0)\npass_state: First Draft\norigin: writer\n---\n" } ?? ""
try (block + body).write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
return dir
}
/// One wire-shaped card with test-friendly defaults. Internal — shared
/// with PostsModelTests (review: a hand-copy drifted here).
func card(
pattern: String = "Hedging",
problem: String = "The hedge weakens the claim.",
diagnosticQuestion: String? = nil,
quote: String = "repeated anchor line",
occurrence: Int = 1,
) -> FixCardStore.Input {
FixCardStore.Input(
pattern: pattern,
problem: problem,
diagnosticQuestion: diagnosticQuestion,
fix: nil,
anchor: .init(quote: quote, occurrence: occurrence),
lane: .mechanical,
emitter: .lint,
provenance: nil,
)
}
/// A fully-stamped card for hand-written fixtures (scan tests).
private func storedCard(pattern: String) -> FixCardStore.StoredFixCard {
FixCardStore.StoredFixCard(
id: UUID(),
submittedAt: Date(timeIntervalSince1970: 0),
pattern: pattern,
problem: "p",
diagnosticQuestion: "",
fix: "",
anchor: .init(quote: "q", occurrence: 1),
lane: .mechanical,
emitter: .lint,
provenance: nil,
status: "open",
anchorStatus: .valid,
)
}
struct MCPToolsTests {
@Test func `anchor validation`() {
let text = "alpha anchor beta anchor gamma"
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 1) == .valid)
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 2) == .valid) // 2 of 2
#expect(FixCardStore.anchorStatus(text: text, quote: "anchor", occurrence: 3) == .stale) // 3 of 2
#expect(FixCardStore.anchorStatus(text: text, quote: "vanished", occurrence: 1) == .stale)
#expect(FixCardStore.anchorStatus(text: text, quote: "", occurrence: 1) == .stale)
// Non-overlapping counting: "a a" fits "a a a" only once.
#expect(FixCardStore.anchorStatus(text: "a a a", quote: "a a", occurrence: 2) == .stale)
}
@Test func `input decode defaults occurrence and rejects unknown enums`() throws {
let minimal = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}"#
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(minimal.utf8))
#expect(input.anchor.occurrence == 1)
#expect(input.diagnosticQuestion == nil)
let badLane = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"nope","emitter":"lint"}"#
#expect(throws: DecodingError.self) {
_ = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(badLane.utf8))
}
}
/// #23 follow-up: pass differentiation — `provenance.pass` rides the
/// wire; pre-schema cards (no pass key) decode to nil, never error.
@Test func `provenance pass rides the wire and old cards decode without it`() throws {
let wire = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a","pass":2}}"#
let input = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(wire.utf8))
#expect(input.provenance?.pass == 2)
let old = #"{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"engine","provenance":{"piece":"posts/a"}}"#
let oldInput = try FixCardStore.decoder.decode(FixCardStore.Input.self, from: Data(old.utf8))
#expect(oldInput.provenance?.pass == nil)
}
@Test func `submit writes snake case card file`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(
piecePath: piece.path,
cards: [card(diagnosticQuestion: "Is the hedge load-bearing?")],
)
#expect(written.count == 1)
#expect(written[0].card.anchorStatus == .valid)
#expect(written[0].card.status == "open")
#expect(written[0].file.hasSuffix("-hedging.json"))
let cardsDir = piece.appendingPathComponent("cards", isDirectory: true)
let files = try FileManager.default.contentsOfDirectory(atPath: cardsDir.path)
.filter { $0.hasSuffix(".json") }
#expect(files == [written[0].file])
let json = try #require(
try JSONSerialization.jsonObject(
with: Data(contentsOf: cardsDir.appendingPathComponent(written[0].file)),
) as? [String: Any],
)
#expect(json["pattern"] as? String == "Hedging")
#expect(json["diagnostic_question"] as? String == "Is the hedge load-bearing?")
#expect(json["anchor_status"] as? String == "valid")
#expect(json["status"] as? String == "open")
#expect(json["submitted_at"] is String)
#expect(json["id"] is String)
}
@Test func `submit flags stale anchors but still lands`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
// A post.md path is accepted directly, not just the piece folder.
let written = try FixCardStore.submit(
piecePath: piece.appendingPathComponent("post.md").path,
cards: [card(quote: "this quote is nowhere")],
)
#expect(written[0].card.anchorStatus == .stale)
#expect(
FileManager.default.fileExists(
atPath: piece.appendingPathComponent("cards/\(written[0].file)").path,
),
)
}
@Test func `submit throws on missing piece`() throws {
let home = try toolsHome()
// A lazy piece folder without post.md is not a piece.
let noPost = home.appendingPathComponent("projects/posts/ghost", isDirectory: true)
try FileManager.default.createDirectory(at: noPost, withIntermediateDirectories: true)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: noPost.path, cards: [card()]) }
#expect(throws: Error.self) {
try FixCardStore.submit(piecePath: home.appendingPathComponent("nowhere").path, cards: [card()])
}
}
/// Security pins (review MEDIUM-1/-2): a readable foreign file must not
/// pass as a "piece" — submit beside it = JSON-drop, anchor check =
/// substring oracle. One resolvePostURL guard closes both.
@Test func `submit refuses foreign files and loose post md`() throws {
let home = try toolsHome()
let foreign = home.appendingPathComponent("notes.md")
try "not a piece".write(to: foreign, atomically: true, encoding: .utf8)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: foreign.path, cards: [card()]) }
let loose = home.appendingPathComponent("loose", isDirectory: true)
try FileManager.default.createDirectory(at: loose, withIntermediateDirectories: true)
try "x".write(to: loose.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: loose.path, cards: [card()]) }
}
@Test func `submit throws on malformed cards and writes nothing`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(pattern: " ")]) }
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(problem: "")]) }
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(quote: "")]) }
#expect(throws: Error.self) { try FixCardStore.submit(piecePath: piece.path, cards: [card(occurrence: 0)]) }
#expect(!FileManager.default.fileExists(atPath: piece.appendingPathComponent("cards").path))
}
@Test func `submit suffixes same second collisions`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let written = try FixCardStore.submit(piecePath: piece.path, cards: [card(), card()])
#expect(written[0].file.hasSuffix("-hedging.json"))
#expect(written[1].file.hasSuffix("-hedging-2.json"))
#expect(written[0].file != written[1].file)
}
@Test func `scan returns newest first and skips undecodable`() throws {
let home = try toolsHome()
let piece = try writePiece(home)
let dir = piece.appendingPathComponent("cards", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try FixCardStore.encoder.encode(storedCard(pattern: "New"))
.write(to: dir.appendingPathComponent("20260102-000000-new.json"))
try FixCardStore.encoder.encode(storedCard(pattern: "Old"))
.write(to: dir.appendingPathComponent("20260101-000000-old.json"))
try "{ not json".write(to: dir.appendingPathComponent("junk.json"), atomically: true, encoding: .utf8)
try "note".write(to: dir.appendingPathComponent("note.txt"), atomically: true, encoding: .utf8)
#expect(FixCardStore.scan(pieceURL: piece).map(\.pattern) == ["New", "Old"])
// A post.md URL is tolerated (the app-side call sites hold the file URL).
#expect(FixCardStore.scan(pieceURL: piece.appendingPathComponent("post.md")).count == 2)
}
@Test func `learnings read raw markdown name sorted`() throws {
let home = try toolsHome { home in
let dir = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "beta body".write(to: dir.appendingPathComponent("b.md"), atomically: true, encoding: .utf8)
try "# Alpha\n\nraw *markdown*".write(to: dir.appendingPathComponent("a.md"), atomically: true, encoding: .utf8)
}
let piece = try writePiece(home)
let learned = try FixCardStore.learnings(piecePath: piece.path)
#expect(learned.map(\.file) == ["a.md", "b.md"])
#expect(learned[0].markdown == "# Alpha\n\nraw *markdown*")
}
@Test func `learnings follow content type`() throws {
let home = try toolsHome { home in
let outlines = home.appendingPathComponent("learnings/outlines", isDirectory: true)
try FileManager.default.createDirectory(at: outlines, withIntermediateDirectories: true)
try "- outline learning".write(to: outlines.appendingPathComponent("o.md"), atomically: true, encoding: .utf8)
let posts = home.appendingPathComponent("learnings/posts", isDirectory: true)
try FileManager.default.createDirectory(at: posts, withIntermediateDirectories: true)
try "post learning".write(to: posts.appendingPathComponent("p.md"), atomically: true, encoding: .utf8)
}
let piece = try writePiece(home, id: "outline-piece", type: "outline")
#expect(try FixCardStore.learnings(piecePath: piece.path).map(\.markdown) == ["- outline learning"])
}
@Test func `learnings missing dir is empty and type defaults to post`() throws {
let home = try toolsHome { home in
let outlines = home.appendingPathComponent("learnings/outlines", isDirectory: true)
try FileManager.default.createDirectory(at: outlines, withIntermediateDirectories: true)
try "outline learning".write(to: outlines.appendingPathComponent("o.md"), atomically: true, encoding: .utf8)
}
// No type key → post → looks in learnings/posts/, which doesn't exist.
let piece = try writePiece(home, type: nil)
#expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty)
// A missing piece is still an error, not an empty answer.
#expect(throws: Error.self) {
try FixCardStore.learnings(piecePath: home.appendingPathComponent("gone").path)
}
}
}
+147
View File
@@ -0,0 +1,147 @@
//
// PassRunTests.swift
// MuseionTests
//
// #24 (S3.1): the pass orchestration — PostsModel.runPass over the real
// client + fake ACP server (ACPClientTests' fake, PostsModelTests' temp-home
// model). Pre-pass snapshot before the engine sees the text, Pass State
// advancing only on a completed turn, order-free.
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home + model + mentor over the fake engine (makeModelHome +
/// makeFakeACP, one rig).
@MainActor
// swiftlint:disable:next large_tuple
func makePassRig(mode: String = "full") throws -> (PostsModel, URL, MentorSessionModel) {
let (model, home) = try makeModelHome()
let fake = makeFakeACP(at: acpTempDir("passrun"), mode: mode)
let mentor = MentorSessionModel(binaryPath: fake)
return (model, home, mentor)
}
@MainActor
private func textRows(of model: MentorSessionModel) -> [String] {
model.rows.compactMap {
if case let .text(text) = $0.content {
text
} else {
nil
}
}
}
@Test @MainActor func `runPass snapshots streams and advances pass state`() async throws {
let (model, home, mentor) = try makePassRig()
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Pass Piece\n\nThe body under pass.", home: home)
model.select(post.id, home: home)
// Wait for the bind rescan to surface the piece — the pass label reads
// the library's title for it (the PostsModelTests poll pattern).
for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) {
try await Task.sleep(nanoseconds: 20_000_000)
}
await model.runPass(.pass1, home: home, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("The body under pass."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: Pass-1 Done"))
// The label renders as the user row; the wire stub never lands.
#expect(textRows(of: mentor).contains("Pass 1 · \(post.title)"))
#expect(!textRows(of: mentor).contains { $0.contains("Critique the piece") })
#expect(model.runningPass == nil)
#expect(model.lastError == nil)
// The library regroups after the (async) rescan.
for _ in 0 ..< 250 where model.posts.first(where: { $0.id == post.id })?.passState != .pass1Done {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.posts.first(where: { $0.id == post.id })?.passState == .pass1Done)
mentor.shutdown()
}
@Test @MainActor func `cancelled pass does not advance`() async throws {
let (model, home, mentor) = try makePassRig(mode: "cancelOnPrompt")
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Cancel Me\n\nStill first draft.", home: home)
model.select(post.id, home: home)
await model.runPass(.pass1, home: home, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
// Pre-pass is unconditional — the snapshot landed anyway.
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("Still first draft."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(model.runningPass == nil)
mentor.shutdown()
}
@Test @MainActor func `refused pass does not advance`() async throws {
let (model, home, mentor) = try makePassRig(mode: "refuseOnPrompt")
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Refused\n\nAlso first draft.", home: home)
model.select(post.id, home: home)
await model.runPass(.pass1, home: home, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(model.runningPass == nil)
mentor.shutdown()
}
@Test @MainActor func `runPass requires an open saved post`() async throws {
let (model, home, mentor) = try makePassRig()
await mentor.openSession()
model.newPost() // draft staged — no folder exists
await model.runPass(.pass1, home: home, mentor: mentor)
#expect(model.lastError?.contains("post") == true)
// Nothing landed on disk — no passes/ anywhere under the Home.
let paths = (FileManager.default.enumerator(atPath: home.path)?.allObjects ?? [])
.compactMap { $0 as? String }
#expect(!paths.contains { $0.contains("passes") })
mentor.shutdown()
}
@Test @MainActor func `dirty session flushes before the snapshot`() async throws {
let (model, home, mentor) = try makePassRig()
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Flush First\n\nOriginal.", home: home)
model.select(post.id, home: home)
model.session?.edit("# Flush First\n\nEdited on the way.") // inside the debounce window
await model.runPass(.pass1, home: home, mentor: mentor)
let piece = home.appendingPathComponent("projects/posts/\(post.id)")
let snapshot = try String(contentsOf: piece.appendingPathComponent("passes/pass-1.md"), encoding: .utf8)
#expect(snapshot.contains("Edited on the way."))
let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8)
#expect(onDisk.contains("Edited on the way."))
mentor.shutdown()
}
@Test @MainActor func `pass runs in any order from first draft`() async throws {
let (model, home, mentor) = try makePassRig()
await mentor.openSession()
let post = try PostStore.writeNew(body: "# Free Order\n\nStraight to two.", home: home)
model.select(post.id, home: home)
await model.runPass(.pass2, home: home, mentor: mentor)
let onDisk = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8,
)
#expect(onDisk.contains("pass_state: Pass-2 Done"))
mentor.shutdown()
}
+146
View File
@@ -557,3 +557,149 @@ private func readPiece(_ home: URL, root: String, project: String, _ id: String)
#expect(onDisk.contains("## one")) #expect(onDisk.contains("## one"))
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path)) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/\(post.id)").path))
} }
// MARK: Pass substrate (#24)
@Test func `snapshotPass writes the pre-pass body verbatim under passes`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Snapshot\n\nPre-pass body.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snapshot\n\nPre-pass body.", home: home)
let snapshot = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot == "# Snapshot\n\nPre-pass body.") // body only, no frontmatter
}
@Test func `snapshotPass re-run overwrites keeping latest per pass type`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Snap\n\nBefore.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nBefore.", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "# Snap\n\nAfter the first pass.", home: home)
let snapshot = try String(
contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/passes/pass-1.md"),
encoding: .utf8,
)
#expect(snapshot == "# Snap\n\nAfter the first pass.")
}
@Test func `pass snapshots coexist per pass type`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Both\n\nBody.", home: home)
let passes = home.appendingPathComponent("projects/posts/\(post.id)/passes", isDirectory: true)
try PostStore.snapshotPass(id: post.id, kind: .pass1, body: "before pass one", home: home)
try PostStore.snapshotPass(id: post.id, kind: .pass2, body: "before pass two", home: home)
#expect(try String(contentsOf: passes.appendingPathComponent("pass-1.md"), encoding: .utf8) == "before pass one")
#expect(try String(contentsOf: passes.appendingPathComponent("pass-2.md"), encoding: .utf8) == "before pass two")
}
@Test func `snapshotPass on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
try PostStore.snapshotPass(id: "ghost", kind: .pass1, body: "x", home: home)
}
#expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/posts/ghost").path))
}
@Test func `advancePassState stamps Pass-1 Done preserving origin type and body`() throws {
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/essays/essay", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "---\ntype: outline\npass_state: First Draft\norigin: ai\n---\n# Essay\n\nArgued body."
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
let newState = try PostStore.advancePassState(id: "essay", kind: .pass1, home: home)
#expect(newState == .pass1Done)
// Stamp round-trip: pass_state advanced, origin/type/body byte-preserved.
#expect(try readPiece(home, root: "projects", project: "essays", "essay")
== "---\ntype: outline\npass_state: Pass-1 Done\norigin: ai\n---\n# Essay\n\nArgued body.")
#expect(PostStore.readBody(id: "essay", home: home) == "# Essay\n\nArgued body.")
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.passState == .pass1Done)
#expect(scanned.origin == .ai)
#expect(scanned.type == .outline)
}
@Test func `advancePassState reaches Pass-2 Done straight from First Draft`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Direct\n\nBody.", home: home)
// Passes run in any order — Pass 2 first is legal.
#expect(try PostStore.advancePassState(id: post.id, kind: .pass2, home: home) == .pass2Done)
#expect(Post.scan(home: home).first?.passState == .pass2Done)
}
@Test func `advancePassState never regresses a higher state`() throws {
let home = try storeHome { home in
let dir = home.appendingPathComponent("projects/posts/done-both", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try "---\ntype: post\npass_state: Pass-2 Done\norigin: writer\n---\n# Done\n\nBody."
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
// A Pass 1 completing on a Pass-2 Done piece keeps the higher state.
let newState = try PostStore.advancePassState(id: "done-both", kind: .pass1, home: home)
#expect(newState == .pass2Done)
#expect(Post.scan(home: home).first?.passState == .pass2Done)
#expect(try readPost(home, "done-both").contains("pass_state: Pass-2 Done"))
}
@Test func `advancePassState is idempotent on re-run`() throws {
let home = try storeHome()
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
_ = try PostStore.advancePassState(id: post.id, kind: .pass1, home: home)
let first = try readPost(home, post.id)
#expect(try PostStore.advancePassState(id: post.id, kind: .pass1, home: home) == .pass1Done)
#expect(try readPost(home, post.id) == first)
}
@Test func `advancePassState on vanished piece throws`() throws {
let home = try storeHome()
#expect(throws: CocoaError(.fileReadNoSuchFile)) {
_ = try PostStore.advancePassState(id: "ghost", kind: .pass1, home: home)
}
}
@Test func `stub carries pass name piece path and fix-card reminder`() {
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
let stub = PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false)
#expect(stub.contains("Pass 1 — paragraph level and up."))
#expect(stub.contains("Piece: /vault/projects/essays/essay/post.md"))
#expect(!stub.contains("Research notes:"))
let closing = "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."
#expect(stub.contains(closing))
#expect(PassContext.stub(kind: .pass2, pieceURL: pieceURL, hasResearch: false)
.contains("Pass 2 — sentence level and below."))
}
@Test func `stub adds the research line only when research exists`() {
let pieceURL = URL(fileURLWithPath: "/vault/projects/essays/essay/post.md")
let research = "/vault/projects/essays/essay/research"
#expect(PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: true)
.contains("Research notes: \(research)"))
#expect(!PassContext.stub(kind: .pass1, pieceURL: pieceURL, hasResearch: false).contains(research))
}
@Test func `estimateTokens is stub plus body chars over four rounded up`() {
let pieceURL = URL(fileURLWithPath: "/vault/essay/post.md")
let body = "# Title\n\nTwo paragraphs of argued prose."
for kind in PassKind.allCases {
for hasResearch in [true, false] {
let total = PassContext.stub(kind: kind, pieceURL: pieceURL, hasResearch: hasResearch).count + body.count
let expected = total % 4 == 0 ? total / 4 : total / 4 + 1 // ceil — derived independently of the impl
#expect(PassContext.estimateTokens(kind: kind, body: body, pieceURL: pieceURL, hasResearch: hasResearch)
== expected)
}
}
}
+75 -2
View File
@@ -12,9 +12,10 @@ import Foundation
import Testing import Testing
/// Throwaway Home + model (EditorSessionTests convention: direct @MainActor /// Throwaway Home + model (EditorSessionTests convention: direct @MainActor
/// instantiation, no app gate). /// instantiation, no app gate). Internal — PassRunTests builds its rig on
/// it (review: a hand-copy drifted).
@MainActor @MainActor
private func makeModelHome() throws -> (PostsModel, URL) { func makeModelHome() throws -> (PostsModel, URL) {
let home = FileManager.default.temporaryDirectory let home = FileManager.default.temporaryDirectory
.appendingPathComponent("postsmodel-\(UUID().uuidString)", isDirectory: true) .appendingPathComponent("postsmodel-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
@@ -468,3 +469,75 @@ private func writeMixedOutline(home: URL) throws -> Post {
#expect(onDisk.contains("type: post")) #expect(onDisk.contains("type: post"))
#expect(onDisk.contains("A paragraph between bullets.")) // verbatim kept everything #expect(onDisk.contains("A paragraph between bullets.")) // verbatim kept everything
} }
// #23 (M2, slice 3): the open piece's stored fix cards surface live.
// The card Input helper is MCPToolsTests' internal card() — one shape,
// no hand-copy (review).
/// refreshCards hops off MainActor (scan runs in Task.detached) — poll for
/// the hop-back instead of asserting synchronously.
@MainActor
private func waitForCards(_ model: PostsModel, _ count: Int) async throws {
for _ in 0 ..< 250 where model.openPieceCards.count < count {
try await Task.sleep(nanoseconds: 20_000_000)
}
}
@Test @MainActor func `opening a piece surfaces its stored fix cards`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home)
try await waitForCards(model, 1)
#expect(model.openPieceCards.map(\.pattern) == ["Hedging"])
#expect(model.openPieceCards.first?.anchorStatus == .valid)
}
@Test @MainActor func `a card landing after open joins the list without reselect`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home)
try await waitForCards(model, 1)
// An MCP client submits another card while the piece stays open —
// the piece-roots watcher fires on <piece>/cards/ and the rescan
// tail refreshes (poll-loop convention).
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Telling", quote: "The anchor sentence.")])
for _ in 0 ..< 250 where model.openPieceCards.count < 2 {
try await Task.sleep(nanoseconds: 20_000_000)
}
#expect(model.openPieceCards.count == 2) // grew live, no reselect
}
@Test @MainActor func `closing the piece clears the card list`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Carded\n\nThe anchor sentence.\n", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home)
try await waitForCards(model, 1)
model.newPost()
#expect(model.openPieceCards == []) // the nil-session rule
}
@Test @MainActor func `an archived piece opened shows its cards too`() async throws {
let (model, home) = try makeModelHome()
let post = try PostStore.writeNew(body: "# Filed\n\nThe anchor sentence.\n", home: home)
try PostStore.archive(post, home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
#expect(folder.path.contains("/archive/"))
try FixCardStore.submit(piecePath: folder.path, cards: [card(pattern: "Hedging", quote: "The anchor sentence.")])
model.select(post.id, home: home) // opened from the Archive pane
try await waitForCards(model, 1)
#expect(model.openPieceCards.count == 1)
}
@@ -32,10 +32,14 @@ struct ProfileProvisionerFailureTests {
#expect(model.hasFailure) #expect(model.hasFailure)
} }
@Test func `provisioning never writes mcp_servers into the profile config`() { @Test func `registration only via the mcp add cli rail never hand-written yaml`() {
// #44 negative invariant: a pre-existing engine-owned config.yaml stays // #44 invariant, slice-2 form: museion-tools registration happens ONLY
// byte-identical through a failed AND a successful pass — no museion-tools entry. // through the `hermes -p museion mcp add` CLI rail — the provisioner
// never writes mcp_servers YAML itself. A pre-existing engine-owned
// config.yaml stays byte-identical through a failed pass, a skipped
// (nil server) pass, AND a pass that registers via the CLI.
let binDir = provTempDir("mcp") let binDir = provTempDir("mcp")
let binary = makeFakeHermes(at: binDir, mode: "ok")
let profileRoot = (binDir as NSString).appendingPathComponent("profiles") let profileRoot = (binDir as NSString).appendingPathComponent("profiles")
let profileDir = (profileRoot as NSString).appendingPathComponent("museion") let profileDir = (profileRoot as NSString).appendingPathComponent("museion")
let configPath = (profileDir as NSString).appendingPathComponent("config.yaml") let configPath = (profileDir as NSString).appendingPathComponent("config.yaml")
@@ -50,27 +54,61 @@ struct ProfileProvisionerFailureTests {
) )
try? FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true) try? FileManager.default.createDirectory(atPath: profileDir, withIntermediateDirectories: true)
try? config.write(toFile: configPath, atomically: true, encoding: .utf8) try? config.write(toFile: configPath, atomically: true, encoding: .utf8)
let binary = makeFakeHermes(at: binDir, mode: "ok") func configUntouched() -> Bool {
(try? String(contentsOfFile: configPath, encoding: .utf8)) == config
}
// Failed pass: registration never reached, config untouched.
let failed = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: badPayload) let failed = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: badPayload)
guard case .failed = failed else { guard case .failed = failed else {
Issue.record("expected copy failure, got \(failed)") Issue.record("expected copy failure, got \(failed)")
return return
} }
#expect((try? String(contentsOfFile: configPath, encoding: .utf8)) == config) #expect(configUntouched())
// The failed pass copied both real skills before hitting the missing entry // Skipped pass: nil serverBinaryPath is the test seam — nothing
// (partial progress is the point — retry resumes additively), so the clean // registers, config untouched.
// re-run finds them present. let skipped = ProfileProvisioner.perform(
let seeded = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: profileRoot, payloadRoot: goodPayload) hermesBinary: binary,
#expect(seeded == .seeded(copied: 0, present: 2)) profileRoot: profileRoot,
#expect((try? String(contentsOfFile: configPath, encoding: .utf8)) == config) payloadRoot: goodPayload,
serverBinaryPath: nil,
)
#expect(skipped == .seeded(copied: 0, present: 2))
#expect(configUntouched())
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation")))
// #44, fresh-profile case: a profile the fake hermes just created carries // Registering pass: the CLI rail ran (marker + invocation recorded) and
// no config.yaml at all — provisioning never writes one. // still not one byte of config.yaml is written by the provisioner — the
let freshRoot = (provTempDir("fresh-mcp") as NSString).appendingPathComponent("profiles") // entry lands through the CLI, or not at all.
_ = ProfileProvisioner.perform(hermesBinary: binary, profileRoot: freshRoot, payloadRoot: goodPayload) let registered = ProfileProvisioner.perform(
let freshConfig = ((freshRoot as NSString).appendingPathComponent("museion") as NSString).appendingPathComponent("config.yaml") hermesBinary: binary,
profileRoot: profileRoot,
payloadRoot: goodPayload,
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
)
#expect(registered == .seeded(copied: 0, present: 2))
#expect(configUntouched())
#expect(FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-registered")))
let invocation = (try? String(
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation"),
encoding: .utf8,
)) ?? ""
#expect(invocation.contains("mcp add museion-tools"))
// #44, fresh-profile case (own binary dir so the add truly runs): a
// registering pass still writes no config.yaml — the CLI owns that
// file, not us.
let freshBinDir = provTempDir("fresh-mcp")
let freshRoot = (freshBinDir as NSString).appendingPathComponent("profiles")
_ = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: freshBinDir, mode: "ok"),
profileRoot: freshRoot,
payloadRoot: goodPayload,
serverBinaryPath: "/fake/Museion.app/Contents/MacOS/Museion",
)
let freshConfig = ((freshRoot as NSString).appendingPathComponent("museion") as NSString)
.appendingPathComponent("config.yaml")
#expect(!FileManager.default.fileExists(atPath: freshConfig)) #expect(!FileManager.default.fileExists(atPath: freshConfig))
} }
@@ -25,6 +25,14 @@ struct SeedSkill {
/// - ok: creates the dir, exit 0. exists: creates the dir, "already exists" on /// - ok: creates the dir, exit 0. exists: creates the dir, "already exists" on
/// stdout, exit 1 (the create race). fail: "Error: create exploded", exit 1. /// stdout, exit 1 (the create race). fail: "Error: create exploded", exit 1.
/// stderr-only: error on stderr with empty stdout (#48 fallback). /// stderr-only: error on stderr with empty stdout (#48 fallback).
///
/// Also speaks `mcp` behind the `-p museion` global flag (#23): `mcp list`
/// prints "museion-tools" iff `<binaryDir>/mcp-registered` exists, else
/// "No MCP servers configured."; `mcp add` verifies its argv, reads ONE "y"
/// line from stdin (mismatch/EOF → "Cancelled.", exit 1 — nothing saved),
/// records the exact invocation in `<binaryDir>/mcp-add-invocation`, drops the
/// marker, prints "Saved 'museion-tools' to …" (verified wire strings).
/// `<binaryDir>/mcp-add-fails` forces "Error: mcp add exploded", exit 1.
func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String { func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> String {
let path = (dir as NSString).appendingPathComponent(name) let path = (dir as NSString).appendingPathComponent(name)
let createBlock = switch mode { let createBlock = switch mode {
@@ -57,6 +65,35 @@ func makeFakeHermes(at dir: String, name: String = "hermes", mode: String) -> St
NAME="$3" NAME="$3"
\(createBlock) \(createBlock)
fi fi
if [[ "$1" == "-p" && "$2" == "museion" && "$3" == "mcp" ]]; then
if [[ "$4" == "list" ]]; then
if [[ -f "${0:h}/mcp-registered" ]]; then
print "museion-tools enabled"
exit 0
fi
print "No MCP servers configured."
exit 0
fi
if [[ "$4" == "add" ]]; then
if [[ "$5" != "museion-tools" || "$6" != "--command" || -z "$7" || "$8" != "--args" || "$9" != "--serve-mcp" ]]; then
print "Error: mcp add unexpected argv: $5 $6 $7 $8 $9"
exit 1
fi
if [[ -f "${0:h}/mcp-add-fails" ]]; then
print "Error: mcp add exploded"
exit 1
fi
read -r ANSWER
if [[ "$ANSWER" != "y" ]]; then
print "Cancelled."
exit 1
fi
print -r -- "$*" > "${0:h}/mcp-add-invocation"
touch "${0:h}/mcp-registered"
print "Saved 'museion-tools' to ${0:h}/profiles/museion/config.yaml"
exit 0
fi
fi
exit 97 exit 97
""" """
try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true) try? FileManager.default.createDirectory(atPath: dir, withIntermediateDirectories: true)
@@ -277,6 +314,58 @@ struct ProfileProvisionerTests {
#expect(!FileManager.default.fileExists(atPath: orphan)) #expect(!FileManager.default.fileExists(atPath: orphan))
} }
@Test func `fresh pass registers museion-tools via the cli with the exact command line`() {
let binDir = provTempDir("mcp-add")
let serverPath = (provTempDir("server") as NSString).appendingPathComponent("Museion")
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
serverBinaryPath: serverPath,
)
#expect(outcome == .seeded(copied: 2, present: 0))
let invocation = ((try? String(
contentsOfFile: (binDir as NSString).appendingPathComponent("mcp-add-invocation"),
encoding: .utf8,
)) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
#expect(invocation == "-p museion mcp add museion-tools --command \(serverPath) --args --serve-mcp")
}
@Test func `already-registered profile skips the add`() {
let binDir = provTempDir("mcp-skip")
// Pre-existing registration → `mcp list` reports it → no add: a re-add
// would prompt "Overwrite? [y/N]" — the skip avoids that branch.
try? "".write(
toFile: (binDir as NSString).appendingPathComponent("mcp-registered"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
serverBinaryPath: "/fake/Museon",
)
#expect(outcome == .seeded(copied: 2, present: 0))
#expect(!FileManager.default.fileExists(atPath: (binDir as NSString).appendingPathComponent("mcp-add-invocation")))
}
@Test func `rejected add fails the register phase with the cli excerpt`() {
let binDir = provTempDir("mcp-reject")
try? "".write(
toFile: (binDir as NSString).appendingPathComponent("mcp-add-fails"),
atomically: true,
encoding: .utf8,
)
let outcome = ProfileProvisioner.perform(
hermesBinary: makeFakeHermes(at: binDir, mode: "ok"),
profileRoot: (binDir as NSString).appendingPathComponent("profiles"),
payloadRoot: makePayload(at: provTempDir("payload"), skills: skills),
serverBinaryPath: "/fake/Museion",
)
#expect(outcome == .failed(phase: .register, excerpt: "Error: mcp add exploded"))
}
@Test func `bundled manifest matches bundled payload`() { @Test func `bundled manifest matches bundled payload`() {
// url(forResource:) doesn't resolve folder references — use the same path // url(forResource:) doesn't resolve folder references — use the same path
// the provisioner itself builds. // the provisioner itself builds.
@@ -0,0 +1,78 @@
# #23 museion-tools MCP server — build, live dogfood, hardening
> **Date:** 2026-10-20
> **Type:** issue
> **Reference:** Gitea issue #23 (museion-tools MCP tool server)
## Goal
Ship the museion-tools MCP server (#23): a headless `--serve-mcp` binary role exposing `query_learnings` + `submit_fix_cards` over NDJSON JSON-RPC stdio, a durable per-piece fix-card store, registration into the `museion` profile at provisioning, and the card surface in the app — then fix everything live dogfooding surfaced and harden the whole diff under a three-reviewer audit.
## What Was Done
- **MCP server** (`Museion/MCPServer.swift`): `MuseionLauncher` (@main) branches `--serve-mcp` → `MCPServer.serve()` vs the app. NDJSON JSON-RPC 2.0: initialize echoes the client's `protocolVersion`, silent notifications, typed tool schemas (the submit schema IS the ADR-0006 card schema), `isError` tool failures, fflush per line. `run(lines:write:)` test seam.
- **Fix-card store** (`Museion/FixCardStore.swift`): `StoredFixCard` snake_case/ISO-8601 JSON per `<piece>/cards/<stamp>-<slug>.json`; exact-substring + 1-based occurrence anchor validation (stale lands flagged, never rejected); whole-call validate-then-write with already-written honesty; learnings reader (home 4-up, literal-plural type dirs).
- **Registration** (`ProfileProvisioner.swift`): `hermes mcp add` rail at provisioning — multiple seeded "y" lines (the real profile consumes stdin before the prompt; one "y" silently cancelled the save). Live-verified: `hermes mcp test museion-tools` → connected, 2 tools. #44 invariant amended: config.yaml only ever via the CLI rail.
- **Card surfacing**: `PostsModel.refreshCards` at rescan/open tails (FSEvents covers `cards/` writes); Fix Cards palette — a floating `Window` scene (`FixCardsWindow.swift`, 340×540, warm `DesignTokens.background`), opened from a mono "Fix Cards · N" row in the mentor pane; `provenance.pass` stamps the finding pass (schema → store → "pass N · lane · emitter" meta → persona instruction).
- **Dogfood fixes** (live passes 1+2): `promptTimeout` 1800 s for `session/prompt` (the 15 s client default abandoned live turns — "connection lost", Stop vanished with `isStreaming`); liveness spinner row while streaming; transcript fix-card tool calls collapse to one-line events; pass-persona v1.2/v1.3 (verdict references findings by title only — the card is the finding's single full statement; tools work in silence); Debug checkbox (`@AppStorage("mentorDebugRows")`, off by default) filters the transcript to prose + card events.
- **Profile hygiene**: removed the stray duplicate seed `~/.hermes/profiles/museion/skills/writing skills/` (wrong-path artifact — the source of the engine's live "skills are ambiguous" confusion); persona synced to canonical.
- **Finish-audit (3 reviewers: ponytail/security/general)**: fixed both security MEDIUMs with one `resolvePostURL` guard (file form must BE `post.md` under a `projects/`|`archive/` component — closed the JSON-drop-beside-any-file and substring-oracle holes); nested `submit_fix_cards` rawInput parsing (the flat #14-era parser never matched the live rail — card events were dead against the real engine); missing `stopReason` → `.failed`; `client!` → guard; card scan off MainActor; 1 MB stdin line cap; six ponytail trims (~−30 lines: test-helper dedup, `EditorSession.passPieceURL`/`hasResearch`, `PostsModel.title(of:)`, `jsonString` merge, ceil-div). All four behavioral fixes flip-tested (guards batch-removed → exactly the four pins failed → restored → green).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Cards persist per-piece as one JSON per card | ADR-0006 fields on disk; rides the existing FSEvents watcher; any MCP client's submissions surface |
| Palette = floating window (not popover/inspector) | Cards are consulted WHILE editing — must stay visible; `Window(id:)` scene matches the About-window pattern |
| `provenance.pass` optional Int | Pre-schema cards and foreign clients degrade gracefully (decode nil, render without tag) |
| Transcript detail → palette; verdict → titles only | Dogfood: full card info in chat doubled mental load; cut from both ends (UI + persona) |
| Debug rows off by default, `@AppStorage` toggle in pane header | Writing session ≠ debugging; model keeps every row so the toggle flips with history intact |
| Filter in the view, not the model | Debug history preserved; tests assert model rows unchanged |
| Guard shape check in `resolvePostURL` (not at tool layer) | Root-cause seam: both `submit` and `learnings` route through it; one guard closes both MEDIUMs |
| No dedup, stale-anchors-land | Prior product decisions (the writer skips repeats; the finding survives) |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| "Mentor: connection lost" mid-pass, Stop vanished, engine kept working | `session/prompt`'s response arrives when the TURN ends (minutes); the client's 15 s request default abandoned the wait → `.failed` → `isStreaming = false` | `promptTimeout` 1800 s, test-pinned `>= 600`; liveness spinner |
| Transcript showed full card JSON + verdict restated every finding | Fake-era parser expected flat shape; persona lacked the no-restating rule | Nested `cards[0]` parse + real-shape fake payload; persona v1.2 |
| Engine: "skills are ambiguous — load both" | Duplicate seed: `skills/writing skills/` beside canonical `skills/` (wrong-path artifact, additive-only seeding never cleans) | Deleted stray dir; synced canonical persona |
| Card-event pin silent against the real engine | The ACP fake baked the flat #14-era payload — tests pinned the wrong shape | Fake payload switched to the nested submit-argument shape (flip-verified) |
| 4 posts-tests failed after scan offload | Sync asserts raced the async hop-back (one poll test's FIRST expect was sync too) | `waitForCards` poll helper; tests async |
| `JSONValue` has no `arrayValue`/`.array` accessor | Hand-rolled enum — only objectValue/stringValue exist | `if case let .array(items)? = object["cards"]` pattern match |
| Oversized-line DoS | `readLine()` unbounded into JSONSerialization | 1 MB cap in `dispatch` → `-32600`; readLine buffering noted as ponytail ceiling |
| Foreign file as "piece" (JSON-drop + substring oracle) | `resolvePostURL` accepted any readable FILE | post.md-name + projects/archive-component guard, pinned both forms |
## Files Changed
| File | Change Summary |
|------|----------------|
| `Museion/MCPServer.swift` | NEW — headless MCP server, launcher branch, wire contract, 1 MB line cap, jsonString serializer |
| `Museion/FixCardStore.swift` | NEW — durable card store, anchor validation, learnings reader, provenance.pass, piece-shape guard |
| `Museion/FixCardsWindow.swift` | NEW — Fix Cards palette window scene content (warm bg, pass-stamped meta, empty states) |
| `Museion/Pass.swift` | NEW — pass context stub, token estimate |
| `Museion/MuseionApp.swift` | Launcher split (`@main` moved); `fix-cards` Window scene |
| `Museion/MentorSessionModel.swift` | `promptTimeout` 1800 s; client guard; empty-stopReason → `.failed`; nested rawInput parse; thought lane |
| `Museion/MentorPaneView.swift` | Liveness row; FixCardEventRow; Debug checkbox + `isWritingRow` filter; pass-bar palette opener |
| `Museion/PostsModel.swift` | `refreshCards` (detached scan), `title(of:)`, runPass via session pass facts |
| `Museion/ProfileProvisioner.swift` | MCP registration phase (multi-"y" stdin) |
| `Museion/EngineGate.swift` | `stdin:` param + pipe-buffer ceiling comment |
| `Museion/EditorSession.swift` | `passPieceURL` / `hasResearch` shared facts |
| `Museion/PostsPaneView.swift` | Mentor column wiring (posts+home) |
| `Museion/PostStore.swift` | `snapshotPass` / `advancePassState` / `folder(of:)` support |
| `ref/writing skills/pass-persona/SKILL.md` | v1.3: card-only detail, provenance.pass stamp, tools-work-in-silence |
| `ref/writing skills/AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, root `AGENTS.md` | DOX for all of the above |
| `MuseionTests/*` (7 files) | MCP tools + wire suites, PassRunTests, posts-card tests (poll convention), provenance.pass pin, security pins, noStopReason mode, oversized-line pin |
## Open Items & Next Steps
- [ ] Registration points at the DerivedData Debug binary — after installing the app elsewhere: `hermes -p museion mcp remove museion-tools`, relaunch once (skip-when-present ceiling)
- [ ] Apply/Skip for cards is #25 (palette is show-only by design)
- [ ] runPass refusal-guard/cancel fake-mode tests — next pass-orchestration slice
- [ ] Learnings decay filtering parked until #26 defines frontmatter fields
- [ ] ADR-0006 could carry one line on caller-attested provenance (audit INFO-5)
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index --> <!-- write-log: full-index -->
| Date | Type | File | Summary | | Date | Type | File | Summary |
|------|------|------|---------| |------|------|------|---------|
| 2026-10-20 | issue | [20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md](20261020-issue23-museion-tools-mcp-server-dogfood-hardening_log.md) | #23 museion-tools MCP server + fix-card store, Fix Cards palette, dogfood fixes (prompt timeout, persona, debug filter), 3-reviewer audit round — 296 tests green |
| 2026-10-19 | issue | [20261019-issue123-ptacek-fold-text-landings_log.md](20261019-issue123-ptacek-fold-text-landings_log.md) | #123 card-emitting doctrine, lane/emitter terms, FC-10 mechanical exemplar landed across skills, CONTEXT, ADR-0006; deslop gap fixed at source | | 2026-10-19 | issue | [20261019-issue123-ptacek-fold-text-landings_log.md](20261019-issue123-ptacek-fold-text-landings_log.md) | #123 card-emitting doctrine, lane/emitter terms, FC-10 mechanical exemplar landed across skills, CONTEXT, ADR-0006; deslop gap fixed at source |
| 2026-10-19 | issue | [20261019-issue115-prose-list-shortcuts_log.md](20261019-issue115-prose-list-shortcuts_log.md) | #115 prose list Tab/⇧Tab/⌥-moves + layer-contents fold chrome (draw(_:) never fires under SwiftUI hosting); 3-reviewer audit round, 239 tests green | | 2026-10-19 | issue | [20261019-issue115-prose-list-shortcuts_log.md](20261019-issue115-prose-list-shortcuts_log.md) | #115 prose list Tab/⇧Tab/⌥-moves + layer-contents fold chrome (draw(_:) never fires under SwiftUI hosting); 3-reviewer audit round, 239 tests green |
| 2026-10-16 | issue | [20261016-issue114-convert-to-post_log.md](20261016-issue114-convert-to-post_log.md) | #114 Convert to Post: in-place type flip + verbatim/headings-ladder ask, prose re-route via proseOverridePostID — 206 tests green (audit round included) | | 2026-10-16 | issue | [20261016-issue114-convert-to-post_log.md](20261016-issue114-convert-to-post_log.md) | #114 Convert to Post: in-place type flip + verbatim/headings-ladder ask, prose re-route via proseOverridePostID — 206 tests green (audit round included) |
+1 -1
View File
@@ -20,7 +20,7 @@ Owned by the root AGENTS.md contract. Vocabulary is bound by CONTEXT.md (Mentor,
## Work Guidance ## Work Guidance
- Authoring follows the writing-for-agents craft: front-loaded context pointers, leading words, positive phrasing, single source of truth, pruned no-ops. - Authoring follows the writing-for-agents craft: front-loaded context pointers, leading words, positive phrasing, single source of truth, pruned no-ops.
- Persona skills carry blend arithmetic plus pass-operational mechanics (Fix Card emission) — no mood adjectives. - Persona skills carry blend arithmetic plus pass-operational mechanics (Fix Card emission) — no mood adjectives. The pass verdict references findings by pattern title only, never restating problem/fix/anchor — the card is the finding's single full statement (pass-persona v1.2).
## Verification ## Verification
+8 -2
View File
@@ -5,7 +5,7 @@ license: GNU GPLv3
metadata: metadata:
author: Alexander Kucera author: Alexander Kucera
email: a.kucera@babylondreams.de email: a.kucera@babylondreams.de
version: "1.1" version: "1.3"
--- ---
# Pass Persona # Pass Persona
@@ -43,7 +43,13 @@ The Chief works before the Knife: verdict on structure, argument, and flow befor
## Fix Cards leave as one ranked submit ## Fix Cards leave as one ranked submit
The verdict lands in prose; the findings leave as Fix Cards. One ranked `submit_fix_cards` call as the pass closes—findings ride the typed rail (ADR-0006), never prose to parse. Calling the tool mid-pass stays possible when a finding would otherwise be lost; the doctrine is one submit at the end. The verdict lands in prose; the findings leave as Fix Cards. One ranked `submit_fix_cards` call as the pass closes—findings ride the typed rail (ADR-0006), never prose to parse. Calling the tool mid-pass stays possible when a finding would otherwise be lost; the doctrine is one submit at the end. Every card carries `provenance.pass`—the number of the pass that found it.
## Tools work in silence
Skill loads, learnings consultations, card reads, dedup checks, retries—none of it is prose. The pass speaks once: the verdict is the message's entirety, first line to last. A tool failure that survives its retry gets one line at the verdict's end, never running commentary.
The card is the finding's only full statement. The prose verdict names each finding by its pattern title—one numbered line, nothing more—never restating the problem, fix, or anchor. The detail lives on the card rail; the verdict points at it.
Rank the submit before sending it. Learnings-resonant findings rise first—a pattern the writer has heard before outranks a novel one, so Learnings inform silently here too. Then Chief-verdict weight: what the Piece loses if the finding goes unfixed. Cap the submit at ten cards; the app's hard ceiling is a backstop, never the primary filter. Rank the submit before sending it. Learnings-resonant findings rise first—a pattern the writer has heard before outranks a novel one, so Learnings inform silently here too. Then Chief-verdict weight: what the Piece loses if the finding goes unfixed. Cap the submit at ten cards; the app's hard ceiling is a backstop, never the primary filter.