Files
museion/Museion/AGENTS.md
T
AlexKucera e55747e7fe
CI / ci (push) Canceled after 0s
feat(library): projects & archive UI — S2 (#108)
Variant B per the #104 prototype verdict: the library column groups
pieces by project (serif lowercase heads, collapse toggle, Pass-State
groups inside, 2px edge-bar selection shared with the new Archive
pane via LibraryPostRow). Move to Project / Archive / Move Back /
whole-project Unarchive are folder moves — post.md bytes untouched,
never clobbering, ids globally unique. File ▸ New Post ⌘N and New
Project… ⌥⌘N (CommandGroup, never CommandMenu per #84).

Every folder move flushes pending edits first and aborts when the
write failed — nothing moves without its text. Project membership and
the archived-refusal derive from freshly resolved disk paths, never
the scan snapshot. Slug and project-name comparisons fold through one
canonical key (NFC + lowercase). Two reviewer fanouts this session;
their findings are all fixed or visibly parked.

144/144 tests green (run twice), swiftformat/swiftlint clean.

Closes #108
2026-10-13 22:18:24 +02:00

35 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 — 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 (@main, WindowGroup scene + about window; AppGateState holds app-scoped gate state). #22: File ▸ Open… (⌘O) + Import… (⇧⌘O) via CommandGroup(after: .newItem) — OpenExternalButton / ImportFilesButton over one shared pickMarkdown NSOpenPanel helper (.md/.markdown via PostStore.openableTypes); never CommandMenu("File") (#84 trap). FocusModeToggle arms for the external guest too. #108: the same group leads with New Post ⌘N (NewPostButton, the library + button's draft path) and New Project… ⌥⌘N (NewProjectButton → PostsModel.stageNewProject(); WorkspaceView presents the NewProjectSheet — commands can't present sheets, the pendingImportURLs pattern: create succeeds → newProjectPending sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires).
  • AppMetadata is the single source for the displayed app name and tagline; members are nonisolated (default-MainActor project).
  • Swift language mode 6, SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; deployment target 26.5; bundle id com.babylondreams.Museion.
  • App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed hermes binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No .entitlements file.
  • 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. RailButton per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; column collapse mirrors the export's media queries (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. PaneHeader = 52pt serif-15 title row + border. #22: window-level .dropDestination(for: URL.self) (markdown only via PostStore.isMarkdown, first match — same guest slot as ⌘O), the OriginAskSheet (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. #108: rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); ArchivePaneView = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → PostsModel.unarchiveProject), rows reuse LibraryPostRow with Move Back to <project> + Rename…, row-click selects + hops to Posts (onOpenPiece closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (newProjectAskBinding, the OriginAsk pattern).
  • PostsPaneView.swift — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (PostEditorView), mentor column (MentorPaneView, fixed 356). Selecting a post opens an editing session; PaneHeader carries the New Post button (export .pane-head .icon-btn). #92: the editor column renders the external guest (model.externalSession) ahead of the post session — one guest at a time, mentor column stays. #108 (variant B, ref/prototypes/wf104-library-ui-prototype.html): PostsLibraryColumn regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 · N count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); LibraryPostRow (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; UnevenRoundedRectangle 0/8/8/0 per .vB .post-row), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Move to Project… (MoveToProjectSheet, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; RenamePostSheet internal for the Archive pane's reuse.
  • PostLibrary.swift — Post (nonisolated: id/title/passState/origin + #107 type/project/isArchived; ContentType post|outline) + Post.scan(home:) -> [Post]: #107/ADR-0012 two-level scan — enumerates projects/<name>/<id>/post.md AND archive/<name>/<id>/post.md (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), type read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (untitled on blank, marker-only, or unterminated-frontmatter bodies); pass_state/origin frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before --- tolerated). Scan runs off-main (bind/rescan in PostsModel).
  • PostStore.swift — #18 write side (nonisolated), #107/ADR-0012 re-root: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, untitled fallback), availableSlug(for:home:) collision suffixes -2/-3… over the GLOBAL slug space (all entries under projects/*/ AND archive/*/ — an archived slug is never reused, restore can't collide; all comparisons through private folded(_:) = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift ==/Set hashing already fold canonical equivalence, so folded is the explicit, tested contract with the lowercase load-bearing; createProject's duplicate check uses the same fold), folder(of:home:) = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), writeNew(body:project:home:) (lazy folder under projects/<project>/ — default posts, the selected project flows in from PostsModel; stamp now type: post + pass_state: First Draft + origin: writer), overwrite (resolves via folder(of:), preserves existing type/pass_state/origin, normalizes bare posts on save), rename = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays post.md; a title slugging to the current id only retitles), trash (resolves via folder(of:) + FileManager.trashItem — recoverable), readBody (frontmatter stripped for editing). #22: openableTypes/isMarkdown (.md/.markdown only, local file URLs — a dragged web link is not a document; shared markdownExtensions list), importFile(at:origin:project:home:) (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every \n split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with type/pass_state/origin set-overwritten via mergedFrontmatter — type: post wins even over an external type: outline; absent keys inserted before the closing ---; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private materialize is the one lazy-folder path writeNew shares). #108: move(_:to:home:) (projects→projects folder move; refuses archived pieces via the resolved disk path — never the scan snapshot's isArchived flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via validatedProject, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), archive(_:home:)/restore(_:home:) (folder moves into/out of archive/<project>/, project disk-derived the same way), unarchiveProject(_:home:) (moves every child of archive/<name>/ into projects/<name>/ — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), createProject(named:home:) (empty/slash/dot-prefix/:/control-char names + case-insensitive duplicates throw; lazily materializes projects/<name>/), private relocate behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
  • PostsModel.swift — PostsModel (@MainActor @Observable, app-scoped via AppGateState.posts): posts list + selection + New Post draft (PostDraft, in-memory, no folder until first save; #107: carries project — captured at newPost() from the selected non-archived post's project, else the default posts; importFiles lands in the same target project); the open post's EditorSession (#19) — select(_:home:) ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, shutdown() flushes on app quit; recursive FSEvents stream (kFSEventStreamCreateFlagFileEvents, 0.5 s latency — the debounce; file-level so nested post.md edits fire) on BOTH projects/ and archive/ (#107 — PostsWatcher.start(urls:) takes an array), rescan reusing Post.scan off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); bind(home:) from .task(id: home) creates projects/ + archive/ if missing + rebinds on repoint; lifecycle ops (saveDraft/rename/trash) set lastError on failure, never alert; the session's onError routes save failures into the same strip. #22: externalSession guest slot (#92 — one at a time, transient per launch, takes the editor column; openExternal(url:) refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via dismissExternal; select/newPost both route through the dismissal), a second PostsWatcher on the external file's folder (#93 — its events re-read the file and feed the session's diskDidChange, the #67 conflict check reused verbatim), shutdown() also flushes the guest (#96.3), and the import path: stageImport/cancelImport hold pendingImportURLs for the ONE Origin ask, importFiles(origin:home:) copies each via PostStore.importFile, continues past per-file failures into lastError, opens the last success, wireSession() routes both sessions' onError into the same strip. #108: project ops behind the variant-B library + Archive pane — pendingProject (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on select, and on openExternal — anywhere the draft dies), targetProject = pending ?? selected-non-archived ?? default, flushOrAbort (audit: EditorSession.flush() returns Bool — a failed write aborts the op and appends "— nothing was moved." to the flush-routed reason, never replacing it; the session stays up dirty), moveToProject/archivePost/restorePost/rename/unarchiveProject (all flush-first — audit 2 closed the rename + unarchive gaps; unarchiveProject's membership check is disk-derived via folder(of:), captured before the move, not the posts snapshot), restorePost (reopens the session off the archive path — select alone would keep the init-time folderURL; 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 into lastError), stageNewProject/cancelNewProject/askNewProject (the New Project ask, pendingImportURLs pattern), newProjectPending (no re-validation — the sheet trimmed, createProject validated).
  • 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.8 via 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-doc attribute on load, per-paragraph reattribute on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). EditorSession.swift — @MainActor @Observable session per open document: #22 SessionTarget (.post(id, home) | .externalFile(url) — postID/fileURL computed per target; #107: folderURL is a stored property, resolved once at init for posts via PostStore.folder(of:) (fallback projects/posts/<id> for a vanished piece); the convenience init(postID:home:) keeps #19 call sites unchanged); edit re-arms a ~1 s debounce (#64) → flush (⌘S / selection change / window close / app quit also flush); flush routes through target-aware writeDocument — posts write PostStore.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; openExternal refuses it into lastError and flush is 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); tracks saveState Changed→Saved (+ Save failed in accent, #65/#83, routed to lastError too — 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) bumps loadGeneration + 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); folderURL exposes 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: plain isRichText = false NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session loadGeneration — 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 (EditSpellingToggle in MuseionApp.swift — commands views take gate as a plain property, they don't inherit the window environment) and applied to the live NSTextView in makeNSView/updateNSView. PostStore cursor 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).
  • 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 via FocusModeToggle in 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 via hitTest → nil; zoneWidth is 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, pure targetOffset math + animated clip-view scroll from textDidChange only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; #88 calibration: EDITOR-WIDE, not focus-gated — centering plus syncTypewriterInset breathing 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 the focused guard at the two call sites). WorkspaceView hides 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). PostsPaneView hides 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 full SaveStateDot (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.focused carries 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 hardcoded NSColor.white sites 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) — stampSource prepends <!--S:N--> sentinels before every blank-line chunk (apex passes HTML comments through); apexRender runs 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 1. 1. 1. renumbering; embed-images inlines base64 so loadHTMLString needs no file access and nothing is written to the vault); stampHTML regex-rewrites sentinels to data-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 with styleSheet() — #72 rework: the whole stylesheet is Museion/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-child no 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-visible themed; 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): injected probeJS maps click→source line (tap = edit intent at that block), ⌘-click→NSWorkspace.open, scroll→top-visible-line into stateBox.topSourceLocation; decidePolicyFor allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after didFinish; 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.
    • AppGateState.museionHome — app-scoped Home (UserDefaults museionHome, default ~/Documents/Museion = defaultMuseionHome; non-file URLs read back as nil — the Home is always a folder). Explicit init: Self in a stored-property initializer breaks @ObservationTracked (covariant-Self error).
    • MentorPaneView no longer carries a root min-frame — it lives in the 356pt mentor column.

    Engine gate (launch gate, tickets #35–#41)

    • EngineGate.swift — EngineProbe (nonisolated): six-path probe order, acp --check health (stdin closed, 5 s timeout, exit-status branching), acp --version version, state.json writer/reader. EngineGateModel (@MainActor @Observable): phases for the UI, onPass seam (fires provisioning, #47), currentBinaryPath handed to provisioning. execute(_:timeout:)/ProcessOutput are 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.json lives at ~/Library/Application Support/Museion/ — schemaVersion 1, wholesale-replaced after every completed check; fail records carry no engineVersion. Gate renders in-memory; About (AboutEngineView in MuseionApp.swift) reads the file and never triggers a check.
    • Gate is app-scoped via AppGateState (first window per app-launch only, ticket #41); EngineGateView.onEnginePass fires provisioning (#47) in parallel on pass.
    • Tests: MuseionTests/EngineGateTests.swift builds fake hermes shell 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, spawn hermes profile create museion --no-alias --no-skills only when missing; exit 1 + "already exists" on stdout = success (#43); errors read from stdout; a nil binary path fails the create phase cleanly (no probe fallback — the gate's winner is always handed in). Seed phase: seed-manifest.txt in the payload root is the inclusion list (blank/# lines ignored; entries validated kebab-case at the trust boundary — a traversal-shaped entry fails the copy phase instead of escaping skills/); per-skill dir-check, copy to temp name + rename (atomic), never open or overwrite present skills; orphaned .-prefixed temp dirs from an interrupted copy are swept at pass start; .DS_Store purged from copies. One os_log line per pass (seeded writing skills: <name> <version>, … (N copied, M present)) reading shipped versions from the bundled payload only; at most one os_log line per failure (phase + excerpt, #48). ProvisioningModel (@MainActor @Observable): runs the pass off-main, guards stacking, records lastFailure (phase-named copy + excerpt); failure never re-raises the gate.
    • Provisioning failure UX (#48): ProvisioningFailureCard (in EngineGateView.swift) — separate sheet from the gate, presented only after the gate sheet has fully dismissed (ContentView.failurePresented = hasFailure && gateDismissed, where gateDismissed is set in the gate sheet's onDismiss — keying on dismissal completion avoids macOS dropping a sheet presented during another's dismissal animation); phase rawValue is the title, excerpt behind Technical details; the card snapshots the failure into @State so a successful Retry doesn't blank it mid-dismiss. Retry re-runs the whole pass (idempotent), Not Now (deferFailure) defers to the next launch's silent retry; sheet is interactiveDismissDisabled. Provisioning writes nothing to the profile config — never an mcp_servers entry (#44 negative invariant, test-pinned).
    • Payload: ref/writing skills/ ships as a folder reference → plain Resources/writing skills/ directory (no zip, no compiled manifest). 11 mentor skills seeded; ste-writing/writing-for-agents ship but never seed.
    • Tests: MuseionTests/ProfileProvisionerTests.swift — fake-binary Process harness (fake creates profile at <binaryDir>/profiles/<name>), injected profile/payload dirs, manifest ↔ payload correspondence against the bundled payload.

    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 in ContentView.onEnginePass — a failed provision doesn't skip the backup). Liveness gate first: gateway.pid (JSON line: pid, hermes_home) pid-liveness via kill(pid, 0) + ps ax -o command= scan for profiles/museion / -p museion (psScan injectable for tests); either live → .skippedEngineRunning, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortable yyyyMMdd-HHmmss dir names) older than 24 h. Copy: recursive enumerator with curated exclusions — dirs logs/, 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 including auth.json, .env, state.db + -wal/-shm sidecars. Directories are createDirectoryd, files copyItemd (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, records lastOutcome (informational only — no UI).
    • UI: Help → Open Backup Folder (OpenBackupFolderButton in MuseionApp.swift) reveals the Backups root in Finder; restore docs live in RESTORE.md beside the snapshots.
    • Tests: MuseionTests/ProfileBackupTests.swift — injected roots/clock/psScan: liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file → .failed, temp swept).

    ACP bridge (S2.2, #14 map)

    • ACPEngineClient.swift — ACPEngineClient (nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client for hermes acp -p museion (ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per \n line, stdout = wire, stderr = logs (never parsed for state); session/new requires mcpServers (list; Museion sends [] — the #44 no-MCP-servers invariant on the wire); session/cancel is a notification (no response); responses camelCase; updates discriminate on update.sessionUpdate. JSONValue (nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto -32601 (M0 handles none — the deny option); crash/EOF fail pending requests and fire onCrash exactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicit close()); close() = handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.
    • MentorSessionModel.swift — MentorSessionModel (@MainActor @Observable): pane state machine (idle/starting/ready/crashed; isStreaming Bool). Lazy lifecycle: spawns on first openSession() (skipped under hosted tests via XCTestConfigurationFilePath), handshake initialize → advisory version compare vs state.json (recordedVersionProvider injectable; compares base versions — the gate records the derived version (acp --version → 0.21.5+2177.g735e426) while the handshake answers the base (agentInfo.version → 0.21.5), so raw string equality fabricates drift on every dev install; baseVersion(of:) strips +-build metadata; one os_log line + both versions in the pane, never blocks) → session/new cwd ~ + mcpServers: []. sendPrompt streams agent_message_chunk/thought into a buffer flushed on turn end; tool calls with fix-card-shaped rawInput (pattern+problem minimum) render as FixCard (ADR-0006 fields); every other update type a collapsible raw-JSON row. Cancel = session/cancel notification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns. clientRef mirror exists solely so nonisolated deinit can close the child.
    • MentorPaneView.swift — the debug pane, post-gate main surface (replaces the content placeholder): header (running version + orange drift note), transcript (text rows, FixCardRow cards, RawUpdateRow disclosure), freeform input 1…4 lines + send + Stop while streaming, crash card (Restart, last prompt, stderr tail behind Technical details).
    • Wiring: AppGateState.mentor is the app-scoped model ( ContentView renders MentorPaneView(model:binaryPath:) once gateModel.currentBinaryPath exists, handing the gate's winner to mentor.binaryPath — no re-probe); quit teardown on NSApplication.willTerminateNotification → mentor.shutdown() (idempotent; scenePhase .inactive would fire on plain focus loss).
    • Tests: MuseionTests/ACPClientTests.swift — fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.

    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 yet — add child docs when subdirectories with distinct responsibilities appear (e.g. editor, library, agent integration).