Files
museion/Museion/AGENTS.md
T
AlexKucera 97893147a6 feat(fix-cards): jump to the anchor
Jump on a Fix Card selects the anchor's span in the piece's
editor and makes the main window key (#204). The span is the
card's quote at its 1-based occurrence, resolved against the
LIVE session text so a dirty buffer still lands, and it rides
the reading flip-back's caret rail: caretHint widens from a
(location, token) tuple to FixCardRevealRequest (SwiftLint
large_tuple), one shared token counter so a jump and a flip-back
can never collide, a zero-length range stays a bare caret and a
non-zero range selects. A jump leaves reading mode first
(reading = false, not exitReading, which stamps its own
zero-length hint), writes nothing, and re-fires per click.

The palette offers Jump on every non-stale card that still shows
an action row; stale anchors have nothing to land on. The
landing math is ProseTextView.landingSpan - a bare caret hops
past leading blanks, a span never does (a quote that IS the
leading blanks selects those blanks) - and appliedText now
routes through anchorRange so Apply and Jump share one
occurrence math.

Two review rounds closed the view-layer gaps the pure pins
could not see: a jump dropped in reading mode; a main window
that never became key (NSApp.activate is a no-op once the
palette's click activated the app - the Coordinator makes
tv.window key instead); a cursor record taken before the scroll.

+3 tests (anchorRange occurrence math with a UTF-16 fixture, the
model's reveal stamp, landingSpan), each flip-verified. Rail
732/732; SwiftFormat and SwiftLint clean. DOX: Museion/AGENTS,
MuseionTests/AGENTS, GLOSSARY gains Jump.
2026-12-03 17:48:55 +01:00

43 KiB
Raw Blame History

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 — disk is truth; 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 — a folder reference can't be expressed through fs-sync groups).

Local Contracts

  • Entry: MuseionApp.swift (WindowGroup + about window; AppGateState holds app-scoped state). 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). WritingLockAppDelegate rides @NSApplicationDelegateAdaptor — quit asks once while a Cold Turkey block holds, unlocked passes straight through.
  • File ▸ Open… (⌘O) + Import… (⇧⌘O) ride CommandGroup(replacing: .newItem) — replacing is load-bearing (single-window ruling 2026-11-05: with after, the stock New Window item kept ⌘N and BOTH fired; replacing makes ⌘N New Post alone and a second window unopenable from the menu). Shared pickMarkdown NSOpenPanel helper; never CommandMenu("File"). New Post ⌘N · New Outline ⇧⌘N · New Project ⌥⌘N (commands can't present sheets — WorkspaceView presents via pending-state). Cold Turkey: Start is focus-gated; focus/reading toggles and every surface-swapping File entry disable while locked.
  • AppMetadata is the single source for displayed name/tagline; members nonisolated.
  • Swift language mode 6, SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; deployment target 27.0 (all six project configs aligned or the test targets can't link the app module); bundle id com.babylondreams.Museion.
  • App Sandbox OFF (ADR-0009) — the engine gate spawns the user-installed hermes binary and provisioning writes outside any container; hardened runtime ON for Developer ID notarization; no .entitlements file.
  • No persistence layer. Exceptions (app metadata only, never content): the engine check's state.json and the session roster's sessions.json (names/ids only; transcripts stay engine-owned, ADR-0007).
  • Tabs for indentation; SwiftFormat + SwiftLint must both stay clean. App icon: single-size 1024×1024 PNG in Assets.xcassets/AppIcon.appiconset.

Workspace shell

The map and the contracts, one bullet per file. Pin-level detail lives in the test files' scenario headers (see MuseionTests/AGENTS.md); devlog narratives in docs/devlog/.

  • DesignTokens.swift — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): background #FAF9F3 (chrome + focus ground), surface #FFFEFB (one page color for edit AND read); light-only, the single semantic exception readyGreen (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors valkyrie/concourse/ubuntuMono (Font.custom falls back to system).
  • WorkspaceView.swift — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level .dropDestination: the drop surface for drags that land OUTSIDE the editor — macOS 27.2.1 routes a drag to the DEEPEST destination, so over the editor the text view takes the drag itself (FileDropTextView's drag handlers) and this destination never fires (the inverse of the 27.0.1 ruling #141 was verified on); both route through AppGateState.routeFileDrop — the ONE file-drop router (pure-markdown → external guest, anything else → ingestDrop, Cold Turkey–guarded; a mixed md+image set and web URLs refuse loudly). A landed drop hops to Posts (unreachable for images today — the editor mounts only there). The house ask sheets present here (pending-state + binding pattern; the sheet structs live in WorkspaceViewSheets.swift, #193). #193 splits: ArchivePaneView → ArchivePaneView.swift, shared chrome (SelectedRowStrip/BorderedSecondaryButtonStyle/PaneHeader) → WorkspaceChrome.swift; RailButton stays here (the rail is its only caller).
  • ArchivePaneView.swift — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses LibraryPostRow.
  • WorkspaceViewSheets.swift — #193: the house ask sheets (moved from WorkspaceView.swift) — OriginAskSheet (the ONE origin ask per import batch, #94), OutlineGuardSheet (#111 mixed-content), ConvertSheet (#114), NewProjectSheet (#108).
  • WorkspaceChrome.swift — #193: the shared chrome (moved from WorkspaceView.swift) — SelectedRowStrip (the selected-row capsule), BorderedSecondaryButtonStyle (the bordered secondary button), PaneHeader (the 52pt pane-head row); every pane reuses them.
  • PostsPaneView.swift — Posts destination (#193: the library column and the row live in their own files): editor column, mentor column (fixed 356). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
  • PostsLibraryColumn.swift — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (RenamePostSheet, MoveToProjectSheet) and the row context menu. Library search: debounced, title+body over non-archived pieces through the file-scope librarySearch mount, body scan off-main through readBody (frontmatter never searched). LaunchFocusReset (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
  • LibraryPostRow.swift — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash; the Archive pane reuses it.
  • PostLibrary.swift — Post + Post.scan: two-level scan over projects/<name>/<id>/post.md AND archive/<name>/<id>/post.md (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, untitled fallbacks; runs off-main. stats_* keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (PostFrontmatter.isUnaidedFirstDraftPair — origin writer, type post; never pass_state, which legitimately advances). scan(home:cache:) takes a PostScanCache (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). micropubURL gated on Micropub.trustworthyURL — imported YAML rides verbatim, so hostile values scan nil.
  • PostFrontmatter.swift — #180: the Post frontmatter codec — the ONE lenient read (parse/split/decoded) and the three write postures behind one known-key table (ownedKeys: type, pass_state, origin — one insertion-order rule): fresh stamp (stamped), merge-import (mergingImport — external keys verbatim, ours win), update-keys (updating — the in-place line-walk, every other line byte-identical). Absorbed and deleted PostStore.stamped/splitFrontmatter/mergedFrontmatter and LearningDecay.stampingFrontmatter byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: isUnaidedFirstDraftPair (writer ∧ post — the scan's read-back gate) and isCaptureEligible (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
  • PostStore.swift — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through folded = NFC + lowercase (APFS is case- and normalization-insensitive); folder(of:home:) is the ONE id→folder resolver — write paths derive their target from the id alone. writeNew defaults type: .post / origin: .writer (session-born pieces pass .ai, immutable). overwrite preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. rename = retitle + move within the same parent. importFile copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our type/pass_state/origin winning. Project ops (move/archive/restore/unarchiveProject/createProject) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; createProject validates names (empty/slash/dot/:/control + case-insensitive duplicates throw). Pass substrate: snapshotPass (pre-pass body verbatim to passes/pass-<n>.md, fixed name per type), advancePassState (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). writeResearchNote is the ONLY path to research/ (a symlinked dir refuses). captureFirstDraftStats — eligibility is the codec's named isCaptureEligible predicate over the file's own frontmatter; failure never fails the pass. ingestImage copies into assets/, publishable types only (what can't ship can't enter; a file the disk can't stat refuses as missing, never as a folder); illustrationRef is the one ![alt](assets/…) builder.
  • DraftStats.swift — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; words(in:) is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift).
  • WritingGoal.swift — the pure goal engine (no UI, no clock): now injected, isMet live and unlatched (deleting below target un-mets).
  • WritingLockState.swift — the lock machine + kiosk: 1 s ticker + per-keystroke feed(text:) drive the goal run, tick(at:) completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session. WritingLockAppDelegate (same file) owns BOTH quit refusals: #162 asks once while a block holds; #200 gates quit-time document departure FIRST (never walk away from a block the quit then refuses to complete) — quitReply(posts:) is the pure decision (nil posts passes; the pins inject here), the one spoken refusal alert is hosted-guarded like the kiosk.
  • TrendsPaneView.swift — per-metric line charts over first-draft captures; only pieces with firstDraftStats appear (the view answers "am I getting better", never "is this draft good"); one capture shows a value, no verdict. TrendMetric (pure): fixed y-domains (burstiness −1…1, TTR + trigram 0…1, sentenceVariation scaled to 1.2× peak, floor 1), verdict at ±0.01 (trigram inverted), one explain line per metric.
  • DeslopLint.swift — the deslop skill's findings computed in Swift at pass invocation (no engine round-trip; a failed lint never blocks a pass). Resources/deslop-lint.json bundled default; <home>/deslop-lint.json override wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position; emit dedups against OPEN cards (closed never block, re-runs make progress).
  • Pass.swift — PassKind (pass1/pass2 — the app's own names) + PassContext.stub (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + estimateTokens (chars/4).
  • BlindRead.swift — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; reveal mapping appended by the model ONLY after the turn ends.
  • Micropub (Micropub.swift, MicropubMedia.swift, MicropubPublishSheet.swift) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; category: frontmatter NEVER travels; NO photo property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through trustworthyURL (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with error_description; preview is display-only, never the publish target. MicropubTokenStore = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys). Media: illustrations(in:) parses only ![alt](assets/…) refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (uploadIllustrations) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (../ or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept.
  • PostsModel.swift — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert PostsModelOutline.swift, passes+Blind Read PostsModelPasses.swift, fix cards PostsModelCards.swift, write rail+structural ops PostsModelWrites.swift, external guest+imports PostsModelImports.swift, watcher+rescan PostsModelWatcher.swift (home of PostsWatcher) — the #146/#193 splits). #179 write rail: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides performWrite — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (watchedHome — written only by the watcher extension's startWatching behind bind, driven by WorkspaceView's root .task(id: museionHome) (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). PostDraft in-memory until first save; mountID keys the editor .id so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. runPass chain: guards through guardOpenPieceRun (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → runningPass live → own-engine run → advance ONLY on .ended with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves watchedHome at call time — stamping into the repointed library would be silent on a slug collision). blindRead rides the same guard rail; nothing advances or records. refreshCards rides the rescan + open tails; applyCard = flush-first, stale anchor flags the card with no text change, the edit lands through EditorSession.adoptText; promoteCard writes a Learning and touches no text; #204 revealCard stamps ONE revealRequest (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (caretHint, now a FixCardRevealRequest — a non-zero range selects the span). micropubSendDraft = flush-first, ONE disk read serves both wire fields, success stamps micropub_url. canArmWritingLock/editorBodyText mirror the editor's outline routing (prose only). #200: quit is a document departure — shutdown() routes both sessions through documentsMayDepart (void — the verdict channel is quitReply's); PostsModel.active (weak static, registered by AppGateState.init — the WritingLockState.active precedent) is the quit gate's reachability, bare test rigs never register.
  • PostsModelWatcher.swift — #193: the watching domain of PostsModel (moved from PostsModel.swift) — PostsWatcher (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH projects/ and archive/; bind(home:) (WorkspaceView's root .task(id: museionHome) drives it); startWatching (the one watchedHome writer); rescan off-main through the app-scoped scan cache, skipping the posts assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping contentRevision on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail.
  • PostsModelWrites.swift — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — performWrite (ONE seam: write + exactly one rescan + the error strip, cleared before the write), flushOrAbort (flush-first; a failed write, an unanswered #67 conflict, or a never-loaded session's retyped words abort with nothing changed — the alert stays up), documentsMayDepart (#200: the departure gate's quit run — shutdown's flush half shared with applicationShouldTerminate; BLOCK-QUIT posture, never silently drop), rename, trash, the #108 project ops (create/stage, moveTargets, move to project, archive/restore/unarchive); document departure (new post/outline, select, open external, guest dismissal) rides the same gates through sessionMayDepart/departOpenDocuments — a navigation whose outgoing flush fails aborts with the dirty session retained (brief-25).
  • PostsModelImports.swift — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — openExternal/dismissExternal (-> Bool — false holds the departure)/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open — held by the departure gate when its flush fails (brief-25: the guest, its buffer, and its watcher stay live until the edits land)); stageImport/cancelImport/importFiles (ONE origin ask per batch, per-file failures continue into lastError).
  • OutlineTree.swift — the one-file plain nested-bullet tree model (ADR-0013): lenient parse, canonical serialize, normalize on save (preamble verbatim, stray prose after the first item drops); parsesWithLoss shares parseItem so detector and parser never disagree; structural ops are path-addressed, id-preserving, boundary-nil; single-node moves CROSS parents at sibling boundaries (LogSeq-style); enter = split/outdent/new-sibling; extract/insertRun are the drag primitives; headingsLadderBody = the Convert transform. Folds live in the view, keyed by node UUID.
  • OutlineEditorView.swift — OutlinePresenter (pure projection: visible rows, fold skipping, zoom re-basing at a node's children, block selection, applyBatch sibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promoted OutlineRowTextView on the focused row, drag grip + drop chrome, zoom breadcrumbs, Esc stack (drag-cancel → selection-collapse → zoom-out). Esc needs a local NSEvent keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before .onExitCommand (probe-pinned in EscEventProbeTests). Every keystroke serializes the whole tree through the existing session machinery; zoom/drag state is view-only, reset on load.
  • OutlineDrag.swift — drag plumbing: NSEvent monitors (global outside the app, so an Esc-cancel never resolves as a drop); the gesture holds STRONG arm-time captures (a mid-drag scroll can drop the origin row's catcher — mouse-up must still clear state); live geometry from CatcherView.rowFrames reading CURRENT window-space frames (SwiftUI 27 removed the .window coordinate space; cached frames go stale on scroll); the pure drop math (DropTarget, draggedIDs, isValidDrop, applyDrop, hitTestDrop) rides a nonisolated presenter extension — resolved by id AFTER extraction.
  • OutlineRowTextView.swift — the promoted row editor: borderless NSTextView, native undo/IME, keyDown intercepts (every intercepted branch returns WITHOUT super), echo-guard update, sizeThatFits floors at 21 (no focus jump). Rides FileDropTextView with no route mounted: a file drag landing on a row bounces (no path paste).
  • FileDropTextView.swift — the editor text views' drag base (macOS 27.2.1 routing): a live NSTextView registers itself for drag types and receives the drag a window-level SwiftUI destination never sees; URL-bearing drops route through onFileDrop (nil = bounce), text-only drops keep the stock drop, everything else bounces — never super for URLs (stock NSTextView pastes the dropped file's PATH via readSelection on NSFilenamesPboardType). The pasteboard probe is memoized per changeCount (draggingUpdated fires per mouse-move).
  • Editor core — ProsePresenter.swift (line-kind → attributes map mirroring the reading surface; plain store stays the source of truth — presentation-only attributes, ADR-0010). EditorSession.swift — per-document session: SessionTarget (post | external file), ~1 s debounce → flush (⌘S / selection change / quit also flush); externals write in place with NO sidecar; loadFailed never opens a writable empty session over a failed read (the first keystroke would destroy the file); the #67 conflict raises when disk ≠ last-flushed ≠ local, and the debounce never fires while the alert is unanswered; adoptText = programmatic writer-consented adoption (the #67 guard is the CALLER's job). Cursor sidecar .museion-state.json in the piece folder, written separately (a failed sidecar is not a failed save). PostEditorView/ProseTextView — plain NSTextView representable, loads keyed by loadGeneration (never per keystroke); spellcheck off by default (markdown on disk carries the spelling). ProseListTextView rides FileDropTextView with onFileDrop → the gate's routeFileDrop, so file drags landing on it ingest (never paste the path); lastIngestNotice is the refusal text the pins read.
  • Prose list machinery — ProseList.swift (pure item scan/mutation over the plain buffer; every structural edit is ONE range replacement = single undo step); ProseListTextView.swift — folds are VIEW state (buffer never changes; hidden scopes styled via foldedAttributes), re-keyed to the nearest same-marker parent, dying when the marker text vanishes; single-line edits re-key in place (rekey), the newline gate is \.isNewline NEVER literal \n/\r compares (a CRLF pair is one grapheme); wholesale restyles self-heal into the full pass via a font probe. Fold chrome renders as tiny per-glyph CALayers in a click-through overlay — NEVER a document-sized bitmap. Image drops bridge through ProseDropBridge into ingestDrop (saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the pure dropIndex (sampling + bracket + binary search; the SwiftUI closure's location is unusable under this hosting, off-screen rects return garbage).
  • Settings — SettingsPaneView.swift (sidebar + detail: Content · Pass 1 · Pass 2 · Chat · Provider Keys; the pane takes the gate's binaryPath and hydrates at open; detail forms left-anchored). SettingsModel.swift — #181: ModelProvider is the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wire dialect (chat/models paths + the SSE decoder selector), authMode (Bearer vs Anthropic's header pair), keyless (nous rides the shared Portal login); the keyless UI branch, the probe's selectors, and both credential consumers key off it. ProviderCredential = the ONE credential resolution (provider key, else the Portal session key for keyless providers — official endpoint ONLY, never a user-set URL) serving Test Connection and pass readiness. Writes COALESCE: the newer write queues past an in-flight one, superseded writes never spawn (partial key prefixes of a secret never reach .env); hydrate reads only and never stomps a pending edit. HermesSettingsWriter.swift — the real write path: surface writes and the base_url write-through ride the HermesConfigRail (#182 — the writer only builds its key list: provider, default, effort set-or-unset, base_url LAST); provider keys upsert into ALL THREE profiles' .env (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection; paths via ProfileLayout). ProviderProbe.swift — Test Connection: every request carries Content-Type: application/json (without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropic x-api-key + pinned version + required max_tokens, zai thinking+reasoning_effort, nous plain chat-completions) — #181: URL paths, auth shape, and the SSE decoder SELECT by the descriptor's dialect, the per-dialect code stays separate functions; 512 token cap; errors riding a 2xx decode as the provider error. onChatSurfaceWrite → requestRestart (chat surface only — pass engines are one-shot). PassReadiness.swift — #181: the per-surface readiness module (ready / missingKey / unknown): reads each surface's provider + .env key through the settings seam and resolves credentials through ProviderCredential (the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself.
  • Focus mode — transient per-launch (no persistence); FocusChrome hover zones + overlay panels float over the measure, never push it; CaretCentering is EDITOR-WIDE, not focus-gated; focus × reading are orthogonal axes. Cold Turkey chrome (ColdTurkeySeat/ColdTurkeyDot) mounts as overlays on the focused branch only.
  • Reading mode (ADR-0011) — ReadingPresenter.swift: the bundled apex binary (arm64, Developer ID–signed with the hardened runtime at commit time, beside libyaml.bundle/libyaml-0.2.dylib — self-contained through the single rpath @executable_path/../Resources/libyaml.bundle; the .bundle wrapper is load-bearing: a bare dylib in the synced folder (with or without extension — Xcode sniffs Mach-O content) becomes the APP's link target; re-sign both when the Developer ID certificate rotates) with -t html --no-mixed-lists --embed-images (no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing 1. 1. 1. renumbering; embed-images inlines base64 so loadHTMLString needs no file access); <!--S:N--> sentinels rewritten to data-source-line stamps; blocks(for:) = the click→edit line map; stylesheet = Resources/reading.css read fresh per build (dev builds prefer the repo copy); fallback on apex failure = escaped source, never a second renderer. ReadingSurface.swift — ONE WKWebView reloaded in place (remount was the dominant switch cost); only our own about:blank main-frame load is allowed.
  • AppGateState.museionHome — fresh installs resolve once and PIN the winner: legacy ~/Documents/Museion (dir-ness gated) → <CloudDocs>/Museion (resolved at the unprefixed path, never a hard-coded iCloud~ form) → silent Documents fallback. Hosted tests take an early return — the machine's real iCloud state and defaults are never touched.

Engine check (gateless launch)

  • EngineGate.swift — EngineProbe (six-path probe order, acp --check health, 5 s timeout) + EngineGateModel (idle/checking/pass/fail; onPass seam; currentBinaryPath handed to provisioning). Gateless flip (#151): AppGateState.startLaunchCheck() from ContentView.task arms the auto-fire chain (provisioning pass → backup pass) and awaits the check async; hasStarted = once per launch, first window only; no-op under hosted tests. No blocking UI — WorkspaceView renders unconditionally, the posts scan starts at first frame.
  • EngineStatusView.swift — visibility mapping (idle/pass+healthy → hidden, checking → pulse, fail AND pass+provisioning-failed → failed — pure, test-pinned), the 44×44 rail pill, and the floating anchored fail card (never blocks layout): install steps + Re-check; provisioning failures ride the same card naming the failing profile in mono. Failure content keeps the "Passes and Sessions need it — the editor keeps working" posture.
  • state.json at ~/Library/Application Support/Museion/ — schemaVersion 1, wholesale-replaced after every completed check (Re-check included); About reads it and never triggers a check.
  • Panes spawn the engine on the nil→value binaryPath arrival (.task(id:); a nil binary never calls openSession).

Profile provisioning

  • ProfileLayout.swift — #182: the ONE owner of the Hermes profile layout: defaultRoot (~/.hermes/profiles) and the per-profile path builders (profileDir, envFile(in:), configuredMarker(in:), gatewayPID(in:), skillsDir(in:)). The provisioner, the settings writer, and backup derive every path through it — no literal profile-root string lives outside (RESTORE.md prose and the ps-scan grep pattern are text, not paths; pinned in ProfileLayoutTests).
  • HermesConfigRail.swift — #182: the ONE owner of the hermes -p <profile> config set/unset contract: argv shape (set value + --force), provider-first ordering (switching providers clears a stale inherited model.base_url — the rail hoists model.provider first, callers can't order it wrong), ✓-line verification (exit 0 AND ✓ Set/✓ Unset on stdout; unset-of-absent = idempotent success). Callers hand it their own key lists: the provisioner seeds provider/default/max_tokens, the settings writer edits provider/default/effort/base_url. Failure carries key/profile/excerpt for both error surfaces; secrets never ride it (argv only carries non-secret keys).
  • ProfileProvisioner.swift — ProfileSurface (chat/pass1/pass2; declaration order = provision order — chat first; names museion/museion-pass1/museion-pass2, Sessions rides Chat; allocatedSkills per the #133 table: Pass 1: 10 · Pass 2: 9 · Chat: 11 — persona pair never co-occurring; #132 fresh-seed defaults as constants: anthropic / claude-sonnet-5-5 / 24000 output tokens). perform = ONE idempotent pass: master-seed every manifest skill additively into the ONE master at ~/Library/Application Support/Museion/skills/ (masterRoot injectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): create (dir-check first; the adopted museion is never re-created), configure (the #132 defaults through the HermesConfigRail — provider first, wire-verified; marker-gated by the layout's .museion-provisioned so user Settings changes survive; the adopted museion is NEVER configured), skills (symlink each allocation from the master; copy-era real dirs migrate to symlinks only on byte-match — diverged stays a copy, untracked untouched), register (museion-tools via mcp add CLI — never hand-written yaml; only for adopted/engine-owned configs do fresh config set writes not apply). Outcome.failed names the profile.
  • Payload: ref/writing skills/ ships as a folder reference → plain Resources/writing skills/. 12 mentor skills ship; the master seeds all 12, each profile symlinks its allocation; ste-writing/writing-for-agents never seed.

Profile backup

  • ProfileBackup.swift — one pass per launch, fired after provisioning finishes (a failed provision doesn't skip it). One stamp, three profile subdirs (NEVER the profiles root — non-Museion profiles are not ours; profile + pid paths via ProfileLayout, #182); any live profile skips the WHOLE stamp (gateway.pid liveness + ps scan, injectable); 24 h age check; curated exclusions (caches/logs/pids/locks) with credentials and state.db included; dir symlinks resolve so restores are self-contained; temp+rename install under ~/Library/Application Support/Museion/Backups/, retention 7; RESTORE.md written once. Failure = one os_log line, never an alert.

museion-tools MCP server

  • MCPServer.swift — the binary's second role (headless, never AppKit). NDJSON JSON-RPC on stdio: initialize echoes the client's protocolVersion; notifications never answered; three tools with typed schemas — query_learnings (serves the visible learnings files), submit_fix_cards (ranked ≤10 ceiling; an over-ceiling reply carries dropped_over_ceiling), submit_research_notes (decode-validate ONLY — research is engine-owned session cargo, NOTHING is written; the only path to disk is the writer's keep). Lines over 1 MB → -32600; fflush after every stdout line; run(lines:write:) is the test seam. #177: both submit tools decode through ToolPayloads (below) — the strict entry throws named CardErrors (an empty cards/notes array is an error, never a silent no-op; the strict side takes snake_case only, no camelCase alias).
  • FixCardStore.swift — StoredFixCard (ADR-0006 fields verbatim, snake_case, ISO dates). submit: the piece must resolve to a post.md under a projects/|archive/ component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinked cards/ dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head; rank stamped in submit order. anchorRange = the nth-occurrence span (nil = stale, empty quote, or occurrence below 1 — never a wrong span; the lane never gates it); appliedText = the mechanical apply over that span (lane-gated, nil on a stale anchor, never a wrong-span patch); close flips status in place. learnings serves only visible (non-decayed) files. promote: ONE confirm = ONE Learning — the on-disk card is the truth (not-found or already-stamped throws before anything is written); symlinked learnings components refuse; the Learning is written first, then the card stamped; learningMarkdown is the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).
  • LearningDecay.swift — the pass clock learnings/pass-counts.json (lenient read, clamped values); passesHidden is the ONE visibility verdict (interval doubles per re-dismiss, capped; garbage dismiss state means VISIBLE — a malformed dismiss never hides a Learning forever); dismiss stamps decay in the Learning's own frontmatter behind write-path guards (traversal/hidden/symlinked/foreign-dir/already-hidden refusals).
  • ToolPayloads.swift — #177: THE tool-payload decoder, one home for the submit_fix_cards/submit_research_notes wire shapes; the MCP server (strict — required fields throw CardError) and the session model's transcript rail (lenient — the nested card-rail shape first, the flat #14-era fake shape kept; unparseable payloads fall to a raw row) both read through it. Every wire-shape fact, lenient and strict, is pinned in ToolPayloadsTests — a shape change fails one suite.

ACP bridge

  • EngineHost.swift — #178: the engine lifecycle owner + the EngineTransport seam. The seam is the whole engine surface — onMessage/onCrash/onStderrLine hooks + start() throws + request(_:params:timeout:) + notify + close() — with two adapters: ACPEngineClient (real stdio, production) and ScriptedEngine (in-process, MuseionTests — engine-behaviour tests run without child processes). EngineHost (@MainActor) owns spawn (makeTransport factory, profile → transport, reads binaryPath at spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived 0.21.5+build, the handshake answers the base; never blocks), teardown, and the per-surface residency (ADR-0014): ONE resident chat engine (startChat()/killChat()) plus at most one one-shot engine (withOneShot(profile:) — spawn per run, teardown at the body's end = the verdict). Hook wiring lives in the host: each hook rides DispatchQueue.main.async, never Task { @MainActor } (the #28 main-queue FIFO wire-order guarantee); the one-shot transport gets onMessage ONLY — a pass crash must not flip the pane. nonisolated(unsafe) mirrors close children in deinit.
  • ACPEngineClient.swift — hand-rolled thin NDJSON JSON-RPC stdio client (hermes acp -p <profile>; no Swift SDK exists), conforming to EngineTransport (notifications arrive on the onMessage property — always set before start()). Wire facts: stdout = wire, stderr = logs (never parsed for state); session/new REQUIRES mcpServers (Museion sends []); session/cancel is a notification; requests time out (15 s default); crash/EOF fail pending requests and fire onCrash exactly once (latched); close() = handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serial writerQueue — the state queue NEVER touches the pipe, so a full pipe (hung engine) can block a send but never a deadline, Stop delivery, or teardown.
  • MentorSessionModel.swift — @MainActor @Observable, and the ONLY observable the panes see (#178: engine processes live behind EngineHost — the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on first openSession() (hosted-guarded; resumes the newest roster entry — a fresh transcript over an engine that knows the session would prompt/fork against unloaded state); spawn/handshake/teardown route through host (startChat() answers the engine version + the advisory drift note the pane displays). sendPrompt returns a TurnOutcome (a response missing stopReason maps to .failed — it never advances a pass); thought chunks stream to their OWN buffer (a collapsed .thought row, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode through ToolPayloads (#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry (body, speaker, notice) — Speaker agent|user|system, NoticeKind refused|interrupted|connectionLost|kickoff|failed|plain — typed at EVERY append site, never a stored "Mentor: "/"You: " prefix; the two wire-only classifications are sniffed ONCE at the append seam (replayedUserContent — a replayed "Pass Pass N…" kick-off → system/kickoff; agentSpeakerNotice — "Operation interrupted:" → system/interrupted); the refusal and connection-lost rows are agent-voice by pinned render; draftCandidateText is pure over .agent, .plain rows. Sessions: MULTIPLE engine-owned sessions on the one bridge; SessionRoster persists NAMES ONLY (id/name/pieceTitle/createdAt; transcripts are engine-owned per ADR-0007, replayed on demand); resume accepts BOTH load-response shapes (the real 0.21.5 id rides _meta.hermes.sessionProvenance; empty-everywhere = engine unknown → honest refusal row, never a fabricated session); fork/compact/brainstorm ride the same rails; research candidates route by PAYLOAD SHAPE (a top-level notes array) BEFORE the fix-card parse — titles are display text, never a routing key; candidates are session cargo (dispositions reset on resume). Per-surface engines (ADR-0014): passes and Blind Read run on ONE private one-shot rail (runOneShot → host.withOneShot, spawn per run + teardown at the verdict) into a TRANSIENT unrostered transcript (passes never mint sessions); the turn pipeline is one shared turnCore; restart()/requestRestart() share respawn() (deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ride host.killChat()/host.startChat()). PassReadiness per kind (the enum + refresh live in PassReadiness.swift, #181 — the model only stores): missingKey names the provider and runPass guards it after the shared open-piece rail (still before anything touches disk); .unknown never blocks; credentials resolve through ProviderCredential (the Portal login path injectable).
  • MentorPaneView.swift — header (serif title + engine status + session chip; ready = the semantic green dot + lowercase ready), shared transcript + composer (SessionTranscriptView — one conversation surface, two panes; interpreted markdown opens http(s) ONLY, every other scheme discards), crash card, PassBarView (Pass 1/2 tabs, token estimate, Cancel ↔ Blind Read ↔ Run Pass — disabled states carry the reason; the missing-key line links to Settings), the Fix Cards palette (a floating window; open cards first; Apply = ask-before — a blocking sheet showing the exact edit, never apply-all; demonstration → Done; stale anchor → Skip only; Promote = one confirm; #204 Jump on every non-stale card that still shows an action row (a closed-and-promoted card has none) — leaves reading mode, selects the anchor span in the editor, reveals it, and makes the main window key (the coordinator owns tv.window; NSApp.activate is a no-op once the palette's click already activated the app)), and research candidate cards (Keep = ask-before sheet → writeResearchNote; Reject = no confirm).
  • Wiring: AppGateState.mentor is the app-scoped model; quit teardown on NSApplication.willTerminateNotification → mentor.shutdown() (idempotent — scenePhase .inactive would fire on plain focus loss). #200: quit FIRST routes through WritingLockAppDelegate.applicationShouldTerminate's departure gate (AppGateState.init registers PostsModel.active) — a piece that can't depart blocks quit with one spoken reason; willTerminate's posts.shutdown() stays as the belt (conflict-held flush + watcher stop).

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' build
  • xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test

Child DOX Index

  • None — flat directory; test-suite contracts live in MuseionTests/AGENTS.md.