39 KiB
39 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 — 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+aboutwindow;AppGateStateholds app-scoped state). No@mainhere —MuseionLauncher(MCPServer.swift) is the@mainentry:--serve-mcpin argv runs the headless museion-tools MCP server (never touches AppKit), anything else runsMuseionApp.main(). One binary, two roles (ADR-0008).WritingLockAppDelegaterides@NSApplicationDelegateAdaptor— quit asks once while a Cold Turkey block holds, unlocked passes straight through. - File ▸ Open… (⌘O) + Import… (⇧⌘O) ride
CommandGroup(replacing: .newItem)—replacingis load-bearing (single-window ruling 2026-11-05: withafter, the stock New Window item kept ⌘N and BOTH fired; replacing makes ⌘N New Post alone and a second window unopenable from the menu). SharedpickMarkdownNSOpenPanel helper; neverCommandMenu("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. AppMetadatais the single source for displayed name/tagline; membersnonisolated.- 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 idcom.babylondreams.Museion. - App Sandbox OFF (ADR-0009) — the engine gate spawns the user-installed
hermesbinary and provisioning writes outside any container; hardened runtime ON for Developer ID notarization; no.entitlementsfile. - No persistence layer. Exceptions (app metadata only, never content): the engine check's
state.jsonand the session roster'ssessions.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 exceptionreadyGreen(the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructorsvalkyrie/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(markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern; the sheet structs live inWorkspaceViewSheets.swift, #193). #193 splits:ArchivePaneView→ArchivePaneView.swift, shared chrome (SelectedRowStrip/BorderedSecondaryButtonStyle/PaneHeader) →WorkspaceChrome.swift;RailButtonstays 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); reusesLibraryPostRow.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-scopelibrarySearchmount, body scan off-main throughreadBody(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 overprojects/<name>/<id>/post.mdANDarchive/<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,untitledfallbacks; 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 aPostScanCache(path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh).micropubURLgated onMicropub.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 deletedPostStore.stamped/splitFrontmatter/mergedFrontmatterandLearningDecay.stampingFrontmatterbyte-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) andisCaptureEligible(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 throughfolded= 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.writeNewdefaultstype: .post/origin: .writer(session-born pieces pass.ai, immutable).overwritepreserves 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.importFilecopies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with ourtype/pass_state/originwinning. 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;createProjectvalidates names (empty/slash/dot/:/control + case-insensitive duplicates throw). Pass substrate:snapshotPass(pre-pass body verbatim topasses/pass-<n>.md, fixed name per type),advancePassState(monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass).writeResearchNoteis the ONLY path toresearch/(a symlinked dir refuses).captureFirstDraftStats— eligibility is the codec's namedisCaptureEligiblepredicate over the file's own frontmatter; failure never fails the pass.ingestImagecopies intoassets/, publishable types only (what can't ship can't enter);illustrationRefis the onebuilder.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):nowinjected,isMetlive and unlatched (deleting below target un-mets).WritingLockState.swift— the lock machine + kiosk: 1 s ticker + per-keystrokefeed(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.TrendsPaneView.swift— per-metric line charts over first-draft captures; only pieces withfirstDraftStatsappear (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.jsonbundled default;<home>/deslop-lint.jsonoverride wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position;emitdedups 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;revealmapping 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; NOphotoproperty — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL throughtrustworthyURL(https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed witherror_description;previewis 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 onlyrefs (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+ConvertPostsModelOutline.swift, passes+Blind ReadPostsModelPasses.swift, fix cardsPostsModelCards.swift, write rail+structural opsPostsModelWrites.swift, external guest+importsPostsModelImports.swift, watcher+rescanPostsModelWatcher.swift(home ofPostsWatcher) — 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) ridesperformWrite— 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'sstartWatchingbehindbind, 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).PostDraftin-memory until first save;mountIDkeys the editor.idso 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.runPasschain: guards throughguardOpenPieceRun(#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 →runningPasslive → own-engine run → advance ONLY on.endedwith stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolveswatchedHomeat call time — stamping into the repointed library would be silent on a slug collision).blindReadrides the same guard rail; nothing advances or records.refreshCardsrides the rescan + open tails;applyCard= flush-first, stale anchor flags the card with no text change, the edit lands throughEditorSession.adoptText;promoteCardwrites a Learning and touches no text.micropubSendDraft= flush-first, ONE disk read serves both wire fields, success stampsmicropub_url.canArmWritingLock/editorBodyTextmirror the editor's outline routing (prose only).PostsModelWatcher.swift— #193: the watching domain of PostsModel (moved from PostsModel.swift) —PostsWatcher(recursive FSEvents stream, file-level, 0.5 s latency) on BOTHprojects/andarchive/;bind(home:)(WorkspaceView's root.task(id: museionHome)drives it);startWatching(the onewatchedHomewriter);rescanoff-main through the app-scoped scan cache, skipping thepostsassignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumpingcontentRevisionon 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 or an unanswered #67 conflict aborts with nothing changed — the alert stays up), rename, trash, the #108 project ops (create/stage,moveTargets, move to project, archive/restore/unarchive).PostsModelImports.swift— #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) —openExternal/dismissExternal/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);stageImport/cancelImport/importFiles(ONE origin ask per batch, per-file failures continue intolastError).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);parsesWithLosssharesparseItemso 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/insertRunare 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,applyBatchsibling-only moves) + the SwiftUI surface: chrome bullets by depth, per-depth rails, ONE promotedOutlineRowTextViewon 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 fromCatcherView.rowFramesreading CURRENT window-space frames (SwiftUI 27 removed the.windowcoordinate 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,sizeThatFitsfloors at 21 (no focus jump).- 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;loadFailednever 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.jsonin the piece folder, written separately (a failed sidecar is not a failed save).PostEditorView/ProseTextView— plain NSTextView representable, loads keyed byloadGeneration(never per keystroke); spellcheck off by default (markdown on disk carries the spelling). - 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 viafoldedAttributes), 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\.isNewlineNEVER literal\n/\rcompares (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 throughProseDropBridgeintoingestDrop(saved posts only, publishable files only, PLAIN files only — a dropped symlink refuses); the drop point is solved by the puredropIndex(sampling + bracket + binary search; the SwiftUI closure'slocationis 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'sbinaryPathand hydrates at open; detail forms left-anchored).SettingsModel.swift— #181:ModelProvideris the provider-descriptor TABLE — label, effort ladder, flagship, default endpoint, env var, wiredialect(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);hydratereads 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 carriesContent-Type: application/json(without it z.ai answers 200 with an error envelope); per-provider dialects (OpenAI speaks the Responses API, Anthropicx-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 +.envkey through the settings seam and resolves credentials throughProviderCredential(the keyless fallback included); MentorSessionModel stores the verdicts and reads no keys or auth files itself. - Focus mode — transient per-launch (no persistence);
FocusChromehover zones + overlay panels float over the measure, never push it;CaretCenteringis 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 with-t html --no-mixed-lists --embed-images(no-mixed-lists REQUIRED — the default merges ordered-after-bullets, killing1. 1. 1.renumbering; embed-images inlines base64 soloadHTMLStringneeds no file access);<!--S:N-->sentinels rewritten todata-source-linestamps;blocks(for:)= the click→edit line map; stylesheet =Resources/reading.cssread 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-codediCloud~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 --checkhealth, 5 s timeout) +EngineGateModel(idle/checking/pass/fail;onPassseam;currentBinaryPathhanded to provisioning). Gateless flip (#151):AppGateState.startLaunchCheck()fromContentView.taskarms 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 —WorkspaceViewrenders unconditionally, the posts scan starts at first frame.EngineStatusView.swift—visibilitymapping (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.jsonat~/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
binaryPatharrival (.task(id:); a nil binary never callsopenSession).
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 thehermes -p <profile> config set/unsetcontract: argv shape (set value +--force), provider-first ordering (switching providers clears a stale inheritedmodel.base_url— the rail hoistsmodel.providerfirst, callers can't order it wrong), ✓-line verification (exit 0 AND✓ Set/✓ Unseton 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.Failurecarries 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;allocatedSkillsper 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/(masterRootinjectable; temp+rename, never touch present) → per surface (first failure wins, next pass heals): create (dir-check first; the adoptedmuseionis never re-created), configure (the #132 defaults through the HermesConfigRail — provider first, wire-verified; marker-gated by the layout's.museion-provisionedso 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 viamcp addCLI — never hand-written yaml; only for adopted/engine-owned configs do freshconfig setwrites not apply).Outcome.failednames the profile.- Payload:
ref/writing skills/ships as a folder reference → plainResources/writing skills/. 12 mentor skills ship; the master seeds all 12, each profile symlinks its allocation;ste-writing/writing-for-agentsnever 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.mdwritten 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:initializeechoes 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 carriesdropped_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 throughToolPayloads(below) — the strict entry throws namedCardErrors (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 apost.mdunder aprojects/|archive/component (one guard closed the arbitrary-file JSON-drop + substring-oracle MEDIUMs); a symlinkedcards/dir refuses before any write; a stale anchor LANDS FLAGGED (the finding survives for the writer); the ceiling keeps the ranked head;rankstamped in submit order.appliedText= the pure nth-occurrence mechanical apply (nil, never a wrong-span patch);closeflips status in place.learningsserves 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;learningMarkdownis the TEACHING shape (anchor + mechanical replacement stay on the card — a Learning informs, it never gets applied).LearningDecay.swift— the pass clocklearnings/pass-counts.json(lenient read, clamped values);passesHiddenis the ONE visibility verdict (interval doubles per re-dismiss, capped; garbage dismiss state means VISIBLE — a malformed dismiss never hides a Learning forever);dismissstamps 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 thesubmit_fix_cards/submit_research_noteswire shapes; the MCP server (strict — required fields throwCardError) 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 inToolPayloadsTests— a shape change fails one suite.
ACP bridge
EngineHost.swift— #178: the engine lifecycle owner + theEngineTransportseam. The seam is the whole engine surface —onMessage/onCrash/onStderrLinehooks +start() throws+request(_:params:timeout:)+notify+close()— with two adapters:ACPEngineClient(real stdio, production) andScriptedEngine(in-process, MuseionTests — engine-behaviour tests run without child processes).EngineHost(@MainActor) owns spawn (makeTransportfactory, profile → transport, readsbinaryPathat spawn time), the initialize handshake (advisory BASE-version drift note — the gate records the derived0.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 ridesDispatchQueue.main.async, neverTask { @MainActor }(the #28 main-queue FIFO wire-order guarantee); the one-shot transport getsonMessageONLY — 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 toEngineTransport(notifications arrive on theonMessageproperty — always set beforestart()). Wire facts: stdout = wire, stderr = logs (never parsed for state);session/newREQUIRESmcpServers(Museion sends[]);session/cancelis a notification; requests time out (15 s default); crash/EOF fail pending requests and fireonCrashexactly once (latched);close()= handlers-off → SIGTERM → grace → SIGKILL → reap; SIGPIPE ignored. brief-27: stdin writes AND the stdin write-handle close ride a dedicated serialwriterQueue— 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 behindEngineHost— the model holds no transport, spawns nothing, and stays session + turn coordination; panes never touch the host). Lazy open on firstopenSession()(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 throughhost(startChat()answers the engine version + the advisory drift note the pane displays).sendPromptreturns aTurnOutcome(a response missingstopReasonmaps to.failed— it never advances a pass); thought chunks stream to their OWN buffer (a collapsed.thoughtrow, never the critique text); prompts ride a 1800 s timeout (the response arrives when the TURN ends, minutes into a pass); tool payloads decode throughToolPayloads(#177 — nested card-rail shape, flat fallback). #177 typed rail: text rows carry(body, speaker, notice)—Speakeragent|user|system,NoticeKindrefused|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;draftCandidateTextis pure over.agent, .plainrows. Sessions: MULTIPLE engine-owned sessions on the one bridge;SessionRosterpersists 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-levelnotesarray) 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 sharedturnCore;restart()/requestRestart()sharerespawn()(deferred to turn end while streaming; resumes the PRE-restart active session; teardown + fresh spawn ridehost.killChat()/host.startChat()).PassReadinessper kind (the enum + refresh live inPassReadiness.swift, #181 — the model only stores):missingKeynames the provider andrunPassguards it after the shared open-piece rail (still before anything touches disk);.unknownnever blocks; credentials resolve throughProviderCredential(the Portal login path injectable).MentorPaneView.swift— header (serif title + engine status + session chip; ready = the semantic green dot + lowercaseready), 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), and research candidate cards (Keep = ask-before sheet →writeResearchNote; Reject = no confirm).- Wiring:
AppGateState.mentoris the app-scoped model; quit teardown onNSApplication.willTerminateNotification→mentor.shutdown()(idempotent — scenePhase.inactivewould fire on plain focus loss).
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 — flat directory; test-suite contracts live in
MuseionTests/AGENTS.md.