Files
museion/Museion/AGENTS.md
T
AlexKucera 5bf09552f6
CI / ci (push) Canceled after 0s
refactor(posts): route every library write through one rail
#179: every library-reflecting store write (draft save, session-born
post, rename, move to project, archive/restore, trash, convert,
project creation, import batch, pass advance) now rides one internal
seam — performWrite pairs the write with exactly one rescan and owns
the error strip (cleared BEFORE the write so importFiles' per-file
failure messages survive the success tail; a nil-Home refusal writes
nothing). The model owns the Home: watchedHome is private(set), set
only by bind (construction + the Settings repoint); no public method
takes a Home parameter — 14 view call sites and ~115 test call sites
swept, dead home plumbing cut. The editor's debounced flush, the card
closes, the pass substrate and the micropub publish stay off the rail
by design (own error semantics, no library regroup).

A converged review finding is closed with a guard: the pass advance
re-resolves watchedHome after the engine's minutes-long turn, so a
mid-pass Settings repoint now refuses the advance with an honest strip
message instead of silently stamping pass state into the repointed
library (wrong-piece write on a slug collision). createProject
failures now surface in the sheet AND the strip — the rail-owns-the-
strip posture supersedes the #108 sheet-only rule.

Five rail pins (PostsModelWriteRailTests, suite members): write → one
library refresh + strip cleared, failed write owns the strip, nil-Home
refusal, import batch keeps per-file messages, mid-pass repoint
refuses the advance — the last two flip-verified against their guards.
ScriptedEngine gains endHeldPrompt (release a held turn as ended).

Verification: suite 657/657 the evening this landed; the next-morning
re-run could not start — both test runners hung before establishing
connection (#134 testmanagerd wedge; an untouched control suite hangs
identically — machine state, not this diff; reboot pending). Rail pins
5/5 isolated after the last test-only edit; swiftlint at baseline
parity; swiftformat clean.

Closes #179

[Generated by AI]
2026-11-10 08:45:04 +01:00

33 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 (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): OriginAskSheet (one ask per import batch), OutlineGuardSheet, ConvertSheet, NewProjectSheet.
  • PostsPaneView.swift — Posts destination: library column (PostsLibraryColumn: project section heads + Pass-State groups, collapse toggle per-view; LibraryPostRow — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through readBody (frontmatter never searched). 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.
  • 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 immutable pair (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.
  • 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 stampingFrontmatter — 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 read from the file's own frontmatter (writer/First Draft/post); failure never fails the pass. ingestImage copies into assets/, publishable types only (what can't ship can't enter); 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.
  • 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; watcher+rescan in a file-scope extension). #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, private(set) — set only by bind, construction + Settings repoint; 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). FSEvents stream (file-level, 0.5 s latency) on BOTH projects/ and archive/; 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); the rescan hands the session the open post's disk text (the #67 external-change check, watcher echo suppressed by equality). 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. External guest: one at a time, symlink-resolved (an atomic write renames over a symlink), its own watcher, dismissed flush-first by any post/draft open. Imports: ONE origin ask per batch, per-file failures continue into lastError. Structural ops are flush-first via flushOrAbort (a failed write or an unanswered #67 conflict aborts with nothing changed — the alert stays up). 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 (one rail, mentor not mid-turn, engine ready, open saved piece) → 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 mirrors the guards; 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. micropubSendDraft = flush-first, ONE disk read serves both wire fields, success stamps micropub_url. canArmWritingLock/editorBodyText mirror the editor's outline routing (prose only).
  • 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).
  • 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).
  • 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 — ModelProvider slugs + effort ladders + pinned switch defaults (nous: Portal endpoint, flagship anthropic/claude-sonnet-5, Bearer; an unkeyed nous test falls back to the shared Portal session key ONLY on the official https endpoint — the session credential never rides a user-set URL). 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: everything through the engine's own CLI, wire-verified ✓ Set lines; provider keys upsert into ALL THREE profiles' .env (foreign lines byte-preserved, 0600, line-broken values REFUSED — env injection); model.base_url written LAST (config set model.provider clears it). 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); 512 token cap; errors riding a 2xx decode as the provider error. onChatSurfaceWrite → requestRestart (chat surface only — pass engines are one-shot).
  • 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 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

  • 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 engine's own CLI, provider first; success WIRE-VERIFIED ✓ Set on stdout; marker-gated by .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); 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. appliedText = the pure nth-occurrence mechanical apply (nil, 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.
  • 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: missingKey names the provider and runPass guards it BEFORE the open-piece guard; .unknown never blocks; the nous fallback reads the Portal login (injectable path).
  • 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), 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).

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.