CI / ci (push) Canceled after 0s
Fix Cards become actionable. Mechanical cards offer Apply behind a blocking ask-before sheet showing the exact edit (anchored quote -> replacement, occurrence + context; empty fix cuts); the sheet is the only path to a write, one card at a time, no apply-all. The edit lands through the editing session (pending edits flush first, the editor re-seeds via adoptText, the card closes applied); Skip and Done close the card in place, recording nothing; demonstration cards close Done/Skip only (ADR-0006). Cards arrive ranked (store-stamped, scan-ordered, open-first palette) and capped at ten per submit — the app keeps the ranked head and the wire reply discloses the drop. Stale anchors re-validate at apply: no text selected or changed, the card flags itself. Includes the finish-audit round (11 fixes, 2 flip-verified pins); 316 tests green. Closes #25
66 KiB
66 KiB
Museion (app target)
Purpose
The Museion application target: the native SwiftUI macOS app shell of the Agentic Writing Environment. Everything user-visible lives here.
Ownership
Owned by the root AGENTS.md contract. The .xcodeproj uses filesystem-synchronized groups — files on disk are the truth; add/move/delete sources here and Xcode follows. Never hand-edit project.pbxproj beyond plain build-setting values and the one sanctioned exception: the ref/writing skills folder reference into the Resources phase (#46 map decision — a folder reference can't be expressed through fs-sync groups).
Local Contracts
- Entry point:
MuseionApp.swift(WindowGroupscene +aboutwindow;AppGateStateholds app-scoped gate state). #23: no@mainhere —MuseionLauncher(MCPServer.swift) is the@mainentry:--serve-mcpin argv runs the headlessmuseion-toolsMCP server (never touches AppKit), anything else runsMuseionApp.main(). One binary, two roles (ADR-0008). #22: File ▸ Open… (⌘O) + Import… (⇧⌘O) viaCommandGroup(after: .newItem)—OpenExternalButton/ImportFilesButtonover one sharedpickMarkdownNSOpenPanel helper (.md/.markdown viaPostStore.openableTypes); neverCommandMenu("File")(#84 trap).FocusModeTogglearms 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 theNewProjectSheet— commands can't present sheets, the pendingImportURLs pattern: create succeeds →newProjectPendingsets 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). AppMetadatais the single source for the displayed app name and tagline; members arenonisolated(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 idcom.babylondreams.Museion. - App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed
hermesbinary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No.entitlementsfile. - No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exception: the engine gate's
state.json(see below). - Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
- App icon:
Assets.xcassets/AppIcon.appiconset— single-size 1024×1024 PNG (Museion-Logo_1024.png); Xcode derives all sizes. The built icns tops out at 256 px entries — that matches Apple's own apps on this macOS; larger sizes come from the catalog.
Workspace shell (M1, #17 + #18 / S1.1)
DesignTokens.swift— palette/geometry from the design contract (ref/Web-Prototype/museion-workspace.html:root+ grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. #89 (2026-10-09): two-color world, calibrated live —background#FAF9F3 (chrome + focus ground),surface#FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.WorkspaceView.swift— post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane.RailButtonper 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 viaPostStore.isMarkdown, first match — same guest slot as ⌘O), theOriginAskSheet(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 reuseLibraryPostRowwith Move Back to<project>+ Rename…, row-click selects + hops to Posts (onOpenPiececlosure — 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 whenlossy; 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;PaneHeadercarries 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):PostsLibraryColumnregroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11· Ncount, 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;UnevenRoundedRectangle0/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;RenamePostSheetinternal for the Archive pane's reuse.PostLibrary.swift—Post(nonisolated: id/title/passState/origin + #107 type/project/isArchived;ContentTypepost|outline) +Post.scan(home:) -> [Post]: #107/ADR-0012 two-level scan — enumeratesprojects/<name>/<id>/post.mdANDarchive/<name>/<id>/post.md(archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs),typeread leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (untitledon blank, marker-only, or unterminated-frontmatter bodies);pass_state/originfrontmatter 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,untitledfallback),availableSlug(for:home:)collision suffixes-2/-3… over the GLOBAL slug space (all entries underprojects/*/ANDarchive/*/— an archived slug is never reused, restore can't collide; all comparisons through privatefolded(_:)= 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, sofoldedis 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 underprojects/<project>/— defaultposts, the selected project flows in from PostsModel; #109:typeparam default.post, stamped first in the block — New Outline passes.outline; the returned Post carries it),overwrite(resolves viafolder(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 stayspost.md; a title slugging to the current id only retitles),trash(resolves viafolder(of:)+FileManager.trashItem— recoverable),readBody(frontmatter stripped for editing). #114 (S4):convert(id:headingsLadder:home:)— the one-time in-place Convert to Post:typeflips to post, body transforms once (verbatim = unchanged; ladder =OutlineTree.headingsLadderBody), id/folder never move, vanished piece throws. One-way in v1.overwrite+convertshareexistingStamp(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; sharedmarkdownExtensionslist),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\nsplit sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim withtype/pass_state/originset-overwritten viamergedFrontmatter—type: postwins even over an externaltype: outline; absent keys inserted before the closing---; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; privatematerializeis the one lazy-folder pathwriteNewshares). #108:move(_:to:home:)(projects→projects folder move; refuses archived pieces via the resolved disk path — never the scan snapshot'sisArchivedflag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name viavalidatedProject, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers),archive(_:home:)/restore(_:home:)(folder moves into/out ofarchive/<project>/, project disk-derived the same way),unarchiveProject(_:home:)(moves every child ofarchive/<name>/intoprojects/<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 materializesprojects/<name>/), privaterelocatebehind 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-fileextension PostStorecarries 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) andadvancePassState(id:kind:home:)(monotonic: the new state is the higher of the file's pass_state and the pass's doneState via privatehigherState— passes run in any order, never regress; body/origin/type preserved through the existingStamp→stamped round-trip; vanished piece throws).Pass.swift— #24 (S3.1) the pass substrate's shared vocabulary (nonisolated):PassKind(pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md;level= paragraph-level-and-up / sentence-level-and-below,snapshotFileName= pass-1.md/pass-2.md,doneState= .pass1Done/.pass2Done) andPassContext(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 viaAppGateState.posts): posts list + selection + New Post draft (PostDraft, in-memory, no folder until first save; #107: carriesproject— captured atnewPost()from the selected non-archived post's project, else the defaultposts; #109: carriestypetoo, default.post—saveDraftthreads it intowriteNew;mountID(UUID per staging) keys the editor's.idso 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"- "/.outlinedraft instead;importFileslands in the same target project); the open post'sEditorSession(#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 nestedpost.mdedits fire) on BOTHprojects/andarchive/(#107 —PostsWatcher.start(urls:)takes an array), rescan reusingPost.scanoff-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)createsprojects/+archive/if missing + rebinds on repoint; lifecycle ops (saveDraft/rename/trash) setlastErroron failure, never alert; the session'sonErrorroutes save failures into the same strip. #111 (S7) mixed-content outline guard:selecton atype: outlinepiece whose bodyOutlineTree.parsesWithLossflags ends the old session, nils the new one, and holds the open (outlineGuardPieceID) — theOutlineGuardSheetask (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); answersopenGuardedOutlineInProse(home:)(setsproseOverridePostID— a routing override withlastDraftWasOutline's exact lifecycle, cleared in newPost/newOutline/select/openExternal) /openGuardedOutlineAsOutline(home:)(consented drop on save) /cancelOutlineGuard()(no session, selection cleared; still guarded next open);outlineGuardPieceIDalso dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes throughopenUnguarded(the one open body; it clears the hold too);isGuardedOutlinedoes ONE disk read deriving type (scan-known, else frontmatter) + body viasplitFrontmatter; guard members live in a file-scopeextension PostsModel(type_body_length posture). Routing: PostsPaneView suppresses outline forproseOverridePostIDand renders an inert notice while a guard hold is up. #22:externalSessionguest 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 viadismissExternal;select/newPostboth route through the dismissal), a secondPostsWatcheron the external file's folder (#93 — its events re-read the file and feed the session'sdiskDidChange, the #67 conflict check reused verbatim),shutdown()also flushes the guest (#96.3), and the import path:stageImport/cancelImportholdpendingImportURLsfor the ONE Origin ask,importFiles(origin:home:)copies each viaPostStore.importFile, continues past per-file failures intolastError, opens the last success,wireSession()routes both sessions'onErrorinto 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, onselect, and onopenExternal— 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 unansweredconflictAlertaborts 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 viafolder(of:), captured before the move, not the posts snapshot),restorePost(reopens the session off the archive path —selectalone would keep the init-timefolderURL; a cold restore still selects),moveTargets(home:)(audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects),createProject(named:) -> String?(nil = success; the failure reason shows inline in the sheet, never double-messaged intolastError),stageNewProject/cancelNewProject/askNewProject(the New Project ask, pendingImportURLs pattern),newProjectPending(no re-validation — the sheet trimmed,createProjectvalidated). #114 (S4) Convert to Post:pendingConversion(PendingConversion {id, lossy}— id-scoped, survives background selects; lossy =parsesWithLoss, drives the sheet's ladder warning) staged bystageConversion(_:home:)(outline pieces only; lossy fromsession.textwhen the piece is open — disk lags the debounce, else disk),cancelConversion();convertToPost(headingsLadder:home:)=flushOrAbort(failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) →PostStore.convert→ when the piece was the open session: teardown-no-flush + reopen viaopenUnguardedwithproseOverridePostIDset (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scopeextension PostsModel. rescan's #67 echo check is gated by session IDENTITY (openSession === session— a same-id reopen must not receive the old session's stale disk text as a conflict). #24 (S3.1) pass orchestration:runningPass(stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) +runPass(_:home:mentor:)in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse withlastError) →flushOrAbort(the engine reads disk) →PostStore.snapshotPass(pre-pass, unconditional — even a cancelled pass snapshots) → stub over the bridge viamentor.sendPrompt(stub, label: "Pass N · <title>")(the label renders, the wire stub never lands) → advance ONLY on.ended(stopReason)with stopReason ≠ "refusal":PostStore.advancePassState+ rescan (the library regroups).cancelPass(mentor:)= the existing session/cancel rail (stopStreaming); cancel/refusal/crash advance nothing — the transcript tells the story. #23 (S2.4) fix-card surfacing:openPieceCards([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed byrefreshCards(home:)(session's piece id →PostStore.folder(of:)→FixCardStore.scan; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires oncards/writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. #25 (S3.2/S3.3) card lifecycle:applyCard(_:home:)→FixCardApplyOutcome(.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session),flushOrAbort(dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor →close(status: .open, anchorStatus: .stale)+ NO text selected or changed, the edit lands throughEditorSession.adoptText(buffer and disk agree, both surfaces re-seed), the card closes .applied,refreshCardsre-derives;skipCard/doneCard→ one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md).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) +OutlineTreeparse/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 (# Titlefrom 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; sharesparseItemso 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") withEnterResultfor focus routing. #112 drag primitives:extract(_:path:)(remove + return a whole subtree) andinsertRun(_:parentPath:index:in:)(splice consecutive siblings at any parent, index clamps to append) over privatewithChildren— 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; sharesscanso 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 visibleRows (preorder, fold-skipping, per-row childCount + foldedDescendantCount; #112:zoomRootIDroots 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;rangeIDsis zoom-aware), resolves id↔path/node +setTextby identity,rangeIDs(block-selection span, ⇧↑/⇧↓ anchor↔focus) andapplyBatch(block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY viaOutlineTree.siblingMovewith 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 promotedOutlineRowTextViewon 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 thekeyDownhead in OutlineRowTextView.swift: function-key scalars"\u{F700}"/"\u{F701}"—String(NSUpArrowFunctionKey)is its decimal description;.function/.numericPadbits stripped before modifier compare; ⇧⇥ = backtab\u{19}with aninsertBacktaboverride; Esc via a localNSEventkeyDown 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 carryProseTypography.outlineRowAttributes(body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's.padding(.vertical, 3), andsizeThatFitsfloors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-fileextension 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)oronDraftEditfor drafts; focus follows node IDs; folds are session-scoped view state. Routing:PostEditorView.outlineflag swapseditingSurfaceto the outliner;PostsPaneViewpassesdraft.type == .outlinefor drafts andlastDraftWasOutline || posts-lookupfor sessions.OutlineDrag.swift— #112 (S6) the drag plumbing + drop math:OutlineDragCatcher/CatcherView(one transparent NSView per row —.gripowns the left margin, click focuses / drag always runs;.bodyoverlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past itDragTrackerowns 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 inarmDrag— 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); astatic currentguard 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.windowcoordinate 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 anonisolated 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). PlusDragInfo,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).OutlineRowTextView.swift— #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (RowTextView), native undo/IME, rust caret, wraps at the column width;keyDownintercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission);sizeThatFitsfloors at 21 so the row never grows on focus.- Editor core (#19 / S1.2, ADR-0010 mode B):
ProsePresenter.swift(nonisolated) — #77 reading-parity rework: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS--lh 1.8via font metrics (lineHeightMultiple(font:cssLineHeight:)— copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits:**bold**/_italic_/`code`/ link labels (ink + underline; brackets+URL dim; CommonMark intraword-_never emphasizes), list markers + heading hashes + quote markers dim; full-docattributeon load, per-paragraphreattributeon edit; plain store stays the source of truth (ADR-0010: presentation-only attributes).EditorSession.swift— @MainActor @Observable session per open document: #22SessionTarget(.post(id, home)|.externalFile(url)— postID/fileURL computed per target; #107:folderURLis a stored property, resolved once at init for posts viaPostStore.folder(of:)(fallbackprojects/posts/<id>for a vanished piece); the convenienceinit(postID:home:)keeps #19 call sites unchanged);editre-arms a ~1 s debounce (#64) →flush(⌘S / selection change / window close / app quit also flush);flushroutes through target-awarewriteDocument— posts writePostStore.overwrite+ the cursor sidecar, externals write the whole text in place with NO sidecar (#93);loadFailed(audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session;openExternalrefuses it intolastErrorandflushis a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on\n; a CRLF pair is one Swift grapheme); trackssaveStateChanged→Saved (+ Save failed in accent, #65/#83, routed tolastErrortoo — dirty = local text ≠ last flushed, shown honestly while the debounce holds);diskDidChange(diskText:)raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher);reloadFromDisk(alert Yes) bumpsloadGeneration+ re-reads (posts restore the sidecar cursor, externals reset it — #93);keepLocal(No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then);teardown(flushFirst:)is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); #25:adoptText(_:)— Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (loadGenerationbump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict);folderURLexposes the document's folder for reading image resolution (#71).PostEditorView.swift— toolbar (mono crumb +SaveStateDot: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; #92: the external guest's crumb is the file name) +ProseTextView(NSViewRepresentable: plainisRichText = falseNSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by sessionloadGeneration— never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; #22: message names the file, post.md or the external's). #77 spellcheck posture:AppGateState.spellChecking(default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (EditSpellingTogglein MuseionApp.swift — commands views takegateas a plain property, they don't inherit the window environment) and applied to the live NSTextView inmakeNSView/updateNSView.PostStorecursor sidecar (#66):CursorState{selectionLocation,selectionLength,scrollOffset}Codable in the resolved piece folder's.museion-state.json(#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - Prose list machinery (#115 / S5, map #110):
ProseList.swift(nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer:Item(marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared withProsePresenter.listMarkerPattern(marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item.ProseListTextView.swift— NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (Foldkeyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height viaProseTypography.foldedAttributes(buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. Chrome rendering (#115 field findings): SwiftUI-hosted TextKit2 never callsNSTextView.draw(_:)and everyNSTextLayoutManagerfragment query (location bridge,textLayoutFragment(for:), enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay'slayer.contents(ProseChromeView, deferred one main-queue tick past textDidChange), and line geometry comes fromfirstRect(forCharacterRange:)(SCREEN coords →window.convertFromScreen→ view) because the selection/caret pipeline is the only geometry source that answers under this hosting. SettingsPaneView.swift— Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09):
AppGateState.isFocused(transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F viaFocusModeTogglein MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap).FocusChrome.swift—HoverZone(tracking-area edge strip, click-through viahitTest → nil;zoneWidthis the calibration knob),FocusOverlayPanel(slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden =opacity(0)+accessibilityHidden),CaretCentering(soft caret centering: ±60pt comfort band, puretargetOffsetmath + animated clip-view scroll fromtextDidChangeonly — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; #88 calibration: EDITOR-WIDE, not focus-gated — centering plussyncTypewriterInsetbreathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore thefocusedguard at the two call sites).WorkspaceViewhides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden).PostsPaneViewhides library+mentor columns; right-edge hover slides the mentor back in (same width verdict —showsMentor).PostsLibraryColumn(extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it.PostEditorView— toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the fullSaveStateDot(loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden;ProseTextView.focusedcarries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). #89 two-color world (calibrated live, deliberate departure from the export):DesignTokens.background#FAF9F3 (chrome + focus ground),DesignTokens.surface#FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcodedNSColor.whitesites are gone), rust #C96442 caret (insertionPointColor), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. #90: Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73):
ReadingPresenter.swift(nonisolated, pure) —stampSourceprepends<!--S:N-->sentinels before every blank-line chunk (apex passes HTML comments through);apexRenderruns the bundled apex binary (Museion/Resources/apex, fs-sync group ships it in Resources automatically; fallback chain bundle →APEX_PATH→ Homebrew, dev-only) with-t html --no-mixed-lists --embed-images [--base-dir <postFolder>](no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one- , killing
AppGateState.museionHome— app-scoped Home (UserDefaultsmuseionHome, default~/Documents/Museion=defaultMuseionHome; non-file URLs read back as nil — the Home is always a folder). Explicit init:Selfin a stored-property initializer breaks@ObservationTracked(covariant-Self error).MentorPaneViewno longer carries a root min-frame — it lives in the 356pt mentor column.
1. 1. 1.renumbering; embed-images inlines base64 soloadHTMLStringneeds no file access and nothing is written to the vault);stampHTMLregex-rewrites sentinels todata-source-line="N"on the following element (0 mis-stamps corpus-wide, #74);blocks(for:)builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract);page(for:postFolder:)assembles the shell withstyleSheet()— #72 rework: the whole stylesheet isMuseion/Resources/reading.css, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. #72 polish (critique-directed, 2026-10-07): flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em,body > :first-childno offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover;::selection/:focus-visiblethemed; secondary tokens--secondary/--rule/--substrate. Fallback on apex failure = escaped source in a<pre>(#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision).ReadingSurface.swift—ReadingStateBox/CaretHintBox(flow state, #68) + one WKWebView reloaded in place (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injectedprobeJSmaps click→source line (tap = edit intent at that block), ⌘-click→NSWorkspace.open, scroll→top-visible-line intostateBox.topSourceLocation;decidePolicyForallows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top afterdidFinish; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot:ReadingCanvasView,Decoration,framesForRange,ImagePopoverView(ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched:ProsePresenter,EditorSession,ProseTextView, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.Engine gate (launch gate, tickets #35–#41)
EngineGate.swift—EngineProbe(nonisolated): six-path probe order,acp --checkhealth (stdin closed, 5 s timeout, exit-status branching),acp --versionversion,state.jsonwriter/reader.EngineGateModel(@MainActor @Observable): phases for the UI,onPassseam (fires provisioning, #47),currentBinaryPathhanded to provisioning.execute(_:timeout:)/ProcessOutputare internal — shared child-process machinery.EngineGateView.swift— blocking sheet card: checking / pass (version + Start Writing) / fail (two install steps per #40, Re-check, Technical details disclosure).interactiveDismissDisabled; sheet never closes itself.state.jsonlives at~/Library/Application Support/Museion/— schemaVersion 1, wholesale-replaced after every completed check; fail records carry noengineVersion. Gate renders in-memory; About (AboutEngineViewinMuseionApp.swift) reads the file and never triggers a check.- Gate is app-scoped via
AppGateState(first window per app-launch only, ticket #41);EngineGateView.onEnginePassfires provisioning (#47) in parallel on pass. - Tests:
MuseionTests/EngineGateTests.swiftbuilds fakehermesshell scripts and exercises the real Process path — probe order, first-stderr reporting, timeout kill, state records.
Profile provisioning (S2.1, tickets #43–#48)
ProfileProvisioner.swift—ProfileProvisioner(nonisolated): one idempotent pass per gate pass. Create phase: dir-check first, spawnhermes profile create museion --no-alias --no-skillsonly 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.txtin 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 escapingskills/); 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_Storepurged 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, recordslastFailure(phase-named copy + excerpt); failure never re-raises the gate. #23 register phase: after a seeded pass (and only when BOTHhermesBinaryandserverBinaryPathare non-nil — production always has both after a gate pass; nil = the test-injection seam, skipped with one os_log line),registerToolsrunshermes -p museion mcp list— "museion-tools" present → idempotent skip (a stale binary path after an app move is refreshed manually viahermes -p museion mcp remove museion-tools— ponytail ceiling) — elsehermes -p museion mcp add museion-tools --command <serverBinaryPath> --args --serve-mcpwith 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(inEngineGateView.swift) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (ContentView.failurePresented=hasFailure && gateDismissed, wheregateDismissedis set in the gate sheet'sonDismiss— 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@Stateso 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 anmcp_serversentry is thehermes mcp addCLI 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 → plainResources/writing skills/directory (no zip, no compiled manifest). 11 mentor skills seeded;ste-writing/writing-for-agentsship but never seed. - 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-failsreject 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)
ProfileBackup.swift—ProfileBackup(nonisolated): one pass per launch, fired on gate pass after the provisioning pass finishes (await chain inContentView.onEnginePass— a failed provision doesn't skip the backup). Liveness gate first:gateway.pid(JSON line:pid,hermes_home) pid-liveness viakill(pid, 0)+ps ax -o command=scan forprofiles/museion/-p museion(psScaninjectable for tests); either live →.skippedEngineRunning, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortableyyyyMMdd-HHmmssdir names) older than 24 h. Copy: recursive enumerator with curated exclusions — dirslogs/,cache/,audio_cache/,image_cache/at any depth; files.DS_Store,models_dev_cache.json(+.etag),provider_models_cache.json,ollama_cloud_models_cache.json,context_length_cache.yaml, suffixes.pid/.sock/.lock; everything else includingauth.json,.env,state.db+-wal/-shmsidecars. Directories arecreateDirectoryd, filescopyItemd (the enumerator re-yields children — whole-subtree copyItem would collide); a file vanishing mid-copy is skipped. Install: copy into.<stamp>-<UUID>temp dir, rename into~/Library/Application Support/Museion/Backups/<stamp>/, prune past 7 after a successful rename.RESTORE.md(manual Finder copy-back instructions) written once into the Backups root. Failure = one os_log line, never an alert (contrast #45's provisioning card); constants fixed in code (retentionCount = 7,snapshotInterval = 24 h).BackupModel(@MainActor @Observable): app-scoped (AppGateState.backup), runs the pass off-main, guards stacking, recordslastOutcome(informational only — no UI).- UI: Help → Open Backup Folder (
OpenBackupFolderButtoninMuseionApp.swift) reveals the Backups root in Finder; restore docs live inRESTORE.mdbeside the snapshots. - Tests:
MuseionTests/ProfileBackupTests.swift— injected roots/clock/psScan: liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file →.failed, temp swept).
museion-tools MCP server (S2.4, #23)
MCPServer.swift—MCPServer(nonisolated): the binary's second role.MuseionLauncher(@main, this file) branches on--serve-mcp→MCPServer.serve()(headless — never touches AppKit; blocks on stdin lines, exits 0 on EOF) vsMuseionApp.main(). NDJSON JSON-RPC 2.0 on stdio (wire facts live-verified against hermes' MCP client):initialize→ echo the client'sprotocolVersion(client sends2025-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; #25: the schema descriptions declare the ranked ≤10 contract and the mechanical-fix-as-exact-replacement semantics, and an over-ceiling submit's reply carriesdropped_over_ceiling— the wire tells the truth about the backstop);tools/callresults carrycontent[{type:"text"}]+isError:trueon tool failure;ping→{}; unknown method-32601, unparseable line-32700id 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 onejsonStringserializer serves replies and tool payloads; fflush after every stdout line (piped stdout is block-buffered).run(lines:write:)is the testable seam behindserve(). Registration into themuseionprofile happens at provisioning (see above) — ACP sessions then expose the tools asmcp_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 BEpost.mdunder aprojects/|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). #25 (S3.2/S3.3): the pass ceiling (passCardCeiling= 10 per submit — the attention-budget backstop; the persona's own cap is the primary filter; the ranked HEAD is kept, tail cards drop before validation) +rankstamped 1-based in submit order (optional — pre-#25 cards decode nil);StoredFixCard.Statusenum (open | applied | skipped | done — CONTEXT.md terminals; foreign status strings fail decode → scan's junk-skip);appliedText(of:in:)— the pure mechanical Apply (nth non-overlapping quote occurrence → fix; nil for demonstration lanes or unresolvable anchors — the loud no-match, never a wrong-span patch, ADR-0006; the caller owns the ask + write);close(pieceURL:id:status:anchorStatus:)— the in-place status flip in the card's own JSON file, every other field untouched (Skip records nothing); a non-nilanchorStatusrides the rewrite (apply's stale path flags the card), nil preserves.scan(pieceURL:)sorts submittedAt DESC → rank ASC (nil ranks last — pre-#25 cards) → filename DESC (same-second tiebreak), 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) andMuseionTests/MCPServerWireTests.swift(in-processrun(lines:write:): initialize echo, silent notifications, both tools listed with required arrays, full submit round-trip through the wire, isError path, -32601/-32700).
ACP bridge (S2.2, #14 map)
ACPEngineClient.swift—ACPEngineClient(nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client forhermes 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\nline, stdout = wire, stderr = logs (never parsed for state);session/newrequiresmcpServers(list; Museion sends[]— the #44 no-MCP-servers invariant on the wire);session/cancelis a notification (no response); responses camelCase; updates discriminate onupdate.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 fireonCrashexactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicitclose());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;isStreamingBool). Lazy lifecycle: spawns on firstopenSession()(skipped under hosted tests viaXCTestConfigurationFilePath), handshakeinitialize→ advisory version compare vs state.json (recordedVersionProviderinjectable; 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/newcwd~+mcpServers: [].sendPrompt(#24 seam:@discardableResult, returnsTurnOutcome—.ended(stopReason:)for any completion stopReason incl.refusal,.cancelledforcancelled,.failedon a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streamsagent_message_chunkinto a buffer flushed on turn end; thought lane (#24 dogfood fix):agent_thought_chunkstreams into its ownstreamingThoughtbuffer — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed.thoughtrow FIRST (it preceded the message), andrestart()clears both buffers; an optionallabel:renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); #23 dogfood fix:sendPromptsends session/prompt withpromptTimeout(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 withisStreaming; test-pinnedpromptTimeout >= 600); tool calls with fix-card-shapedrawInput(pattern+problem minimum) render asFixCard(ADR-0006 fields; audit: the parser takes the nestedsubmit_fix_cardsargument 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 missingstopReasonmaps to.failed(a turn without stopReason never advances a pass), andsendPromptguards the client instead of force-unwrapping. Cancel =session/cancelnotification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns.clientRefmirror exists solely so nonisolated deinit can close the child.MentorPaneView.swift— the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note, trailing mini Debug checkbox —@AppStorage("mentorDebugRows"), off by default: the writing-session transcript filters to prose + card events viaisWritingRow(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-lineFixCardEventRows — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; #24 dogfood fix:defaultScrollAnchor(.bottom)— programmaticscrollToraced the growing lazy rows and mislanded at the TOP;.thoughtrows 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 — indeterminateProgressView+ "Mentor is working — Stop to interrupt." caption whileisStreaming; 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-scopeprivate 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.estimateTokenscost 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 whileposts.runningPassstreams) ↔ 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 floatingWindowscene (idfix-cards,FixCardsPaletteinFixCardsWindow.swift,defaultSize340×540) beside About, opened viaopenWindowfrom 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— #25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries#rank, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" whenprovenance.passis stamped and re-contextualizes via@Observableas the open piece changes (audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.title(of:)+ EditorSession.passPieceURL/hasResearchare the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped); paintedDesignTokens.background— app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering isFixCardEventRow— 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.mentoris the app-scoped model ( ContentView rendersMentorPaneView(model:binaryPath:)oncegateModel.currentBinaryPathexists, handing the gate's winner tomentor.binaryPath— no re-probe); quit teardown onNSApplication.willTerminateNotification→mentor.shutdown()(idempotent; scenePhase.inactivewould 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.
Work Guidance
- Native SwiftUI only on the editing side — no web-editor embedding, no Electron-style components (ADR-0001; reading-mode WKWebView is allowed per ADR-0011: reading is presentation).
- Text editing gets built on TextKit 2 / SwiftUI directly; no CodeEdit/CodeMirror/ProseMirror-class editing dependencies.
Verification
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' buildxcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test
Child DOX Index
- None yet — add child docs when subdirectories with distinct responsibilities appear (e.g. editor, library, agent integration).