CommandGroup(after: .newItem) left the WindowGroup's stock File ▸ New Window item in place with its ⌘N, so both actions fired — a second Museion window AND a new post. Switching to replacing: .newItem kills the stock item: the app stays single-window and ⌘N belongs to New Post alone. Update the AGENTS.md contract, NewPostButton doc, and the kiosk ⌘W/⌘N key-swallow comments to match the new menu reality.
136 KiB
136 KiB
Museion (app target)
Purpose
The Museion application target: the native SwiftUI macOS app shell of the Agentic Writing Environment. Everything user-visible lives here.
Ownership
Owned by the root AGENTS.md contract. The .xcodeproj uses filesystem-synchronized groups — files on disk are the truth; add/move/delete sources here and Xcode follows. Never hand-edit project.pbxproj beyond plain build-setting values and the one sanctioned exception: the ref/writing skills folder reference into the Resources phase (#46 map decision — a folder reference can't be expressed through fs-sync groups).
Local Contracts
- Entry point:
MuseionApp.swift(WindowGroupscene +aboutwindow;AppGateStateholds app-scoped state; #151 gateless —ContentView.taskfiresstartLaunchCheck, the async engine check + auto-fire chain). #23: no@mainhere —MuseionLauncher(MCPServer.swift) is the@mainentry:--serve-mcpin argv runs the headlessmuseion-toolsMCP server (never touches AppKit), anything else runsMuseionApp.main(). One binary, two roles (ADR-0008). #22: File ▸ Open… (⌘O) + Import… (⇧⌘O) ride the sameCommandGroup(replacing: .newItem)—replacingis load-bearing (single-window dogfood ruling 2026-11-05): withafter, the stock File ▸ New Window item the WindowGroup owns kept its ⌘N and BOTH fired — a new window AND a new post; replacing kills the stock item, so ⌘N is New Post alone and a second Museion window cannot open from the menu. One sharedpickMarkdownNSOpenPanel helper (.md/.markdown viaPostStore.openableTypes); neverCommandMenu("File")(#84 trap).FocusModeTogglearms for the external guest too. #162 (Cold Turkey S2):WritingLockAppDelegaterides@NSApplicationDelegateAdaptor(quit refused while a block holds); the View group gains Start Cold Turkey… (focus-gated, disabled on outline/no piece — the #160 second path behind the dot) and the lock refusals — Toggle Focus Mode, Toggle Reading Mode, and every File entry that would swap the editor surface (New Post/Outline/Project, Open…, Import…) disable while locked; ⌘W is swallowed by the kiosk's key monitor (WritingLockState.swift). #108: the same group leads with New Post ⌘N (NewPostButton, the library + button's draft path), New Outline ⇧⌘N (#109:NewOutlineButton→PostsModel.newOutline()— same draft path, outline type) and New Project… ⌥⌘N (NewProjectButton→PostsModel.stageNewProject(); WorkspaceView presents theNewProjectSheet— commands can't present sheets, the pendingImportURLs pattern: create succeeds →newProjectPendingsets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; the stock New Window item is REPLACED — ⌘N is New Post alone, no second window). AppMetadatais the single source for the displayed app name and tagline; members arenonisolated(default-MainActor project).- Swift language mode 6,
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; deployment target 27.0 (bumped from 26.5 with the Xcode 27 settings pass — all six project configs, tests included, stay aligned or the test targets can't link the app module); bundle idcom.babylondreams.Museion. - App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed
hermesbinary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No.entitlementsfile. - No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exceptions (both app metadata, never content): the engine gate's
state.jsonand the session roster'ssessions.json(#28 — names/ids only; transcripts stay engine-owned per ADR-0007). - 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, and — 2026-11-05 owner ruling — the chat's three face constructorsvalkyrie/concourse/ubuntuMono(Valkyrie OT B / Concourse OT Book / UbuntuMono NFM, PostScript names mirroring ProseTypography; Font.custom falls back to system when absent). #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, with the single semantic exceptionreadyGreen(#153/#156: the mentor header's ready dot; a meaning, never a style color).WorkspaceView.swift— the first-frame main surface (#151: gateless — rendered unconditionally by ContentView; the engine check runs async beside it): nav rail (Posts/Sessions/Learnings/Trends + the #151 engine-status pill + Settings at bottom) + active pane.RailButtonper the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). #32 (S5.2): the rail's fourth destination — Trends (chart.xyaxis.line, after Learnings — measurement beside memory) →TrendsPaneView(own file). #28 (S2.3): Sessions is real —SessionsPaneView(own file) over the engine-owned session model:PaneHeader("Sessions")carries the New Session control (#30: always a Menu — "New Session" / "New Session on <title>" when Posts has an open piece / "New Brainstorm" →beginBrainstormSession; the plain-button branch died with the second action; association stays by name/convention,pieceTitleon the roster entry; disabled on!canStartSession), two-column body — roster list atlibraryWidth(rows inLibraryPostRow's exact 2px-strip language: serif-13 name + mono-11 metapieceTitle · yyyy-MM-dd HH:mm; row click =resumeSession, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the sharedSessionTranscriptView(home passed through — #29 research candidates curate in either pane; #30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, #30: New Post · Fork · Compact bordered mono-11 — Fork · Compact disabled on!canStartSession, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask —sessionDraft@State seeded fromdraftCandidateText(), the privateNewPostFromSessionSheetprefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create →PostsModel.newPostFromSession, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's.taskruns the same idempotentopenSession()(XCTest-guarded) and seedsmodel.binaryPathfrom the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live inSessionTranscriptView(own file) — MentorPaneView's transcript views moved there verbatim (#24'sdefaultScrollAnchor(.bottom)preserved);isWritingRowmoved with it and MentorPaneView delegates; #30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes (the Mentor pane keeps the crash card). #155 (map #153, contractref/prototypes/wf154-mentor-pane-prototype.html): the surface wears the editorial chat voice —speaker(of:)(static, test-pinned) maps the model's"Mentor: "/"You: "prefixes onto agent serif-15/1.6 prose (2026-11-05: the three voices wear the editor's faces — Valkyrie OT B prose/thinking, Concourse OT Book the user capsule + composer, UbuntuMono the mono voice; lineSpacings recalibrated to the faces' natural line boxes) (markdown at flush, verbatim while streaming — Vivarium #97; interpreted markdown opens http(s) ONLY —linkVerdictgates the surface'sopenURLenvironment, every other scheme discards: engine prose echoes imported content, #34 gate-at-sink doctrine) / right-aligned terracotta-wash-14% capsule (radius 12/12/2/12, 85% of live column width —onGeometryChange, both panes' columns) / mono-11 status box on the fg-wash-6% card (refusals, pass kick-off labels, reveals — the system voice); ThinkingBlock port (mono-11 toggle, serif-13 muted on the wash card, open while live, collapsed when flushed, per-instance expansion state); research-note cards inherit the wash family; the composer restyles per contract — surface-fill input, ONE accent Send flipping to terracotta-outlined Stop (default-action shortcut rides Send only), floating.thinMaterialliveness chip above the composer (streaming only, hit-through), plain Return sends / Shift+Return breaks the line (Vivarium owner-report fix;send()gained the empty-trim guard), and the debug toggle seats at the composer's trailing edge viadebugBinding: Binding<Bool>?(nil = no toggle). #26: Learnings is real —LearningsPaneView(own file), a list-only pane (Archive posture) over<home>/learnings/:LearningsIndex(nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (YYYYMMDD-filename prefix desc, undated last), pattern/problem/promoted read leniently viaPost.frontmatter(missing pattern → filename minus date+ext), scan detached off MainActor from.task(id: home)with aTask.isCancelledgate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. #27 (S4.2):EntrygainsresurfacesIn(nil = visible, positive = passes until resurface;currentPassinit param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) andscanreadsLearningDecay.passCounts(home:)once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a privaterescan(_:)reused after a dismiss (detached task; errors land in a mono-11 orangelastErrorstrip under the header, cleared on the next successful rescan; assignments gate onscannedHome— a dismiss Task holds the OLD home beyond.taskcancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; column collapse mirrors the export's media queries (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips.PaneHeader= 52pt serif-15 title row + border. #22: window-level.dropDestination(for: URL.self)(markdown only viaPostStore.isMarkdown, first match — same guest slot as ⌘O), theOriginAskSheet(ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. #162: the window drop destination refuses while a Cold Turkey block holds (the open Piece stays the counted one), and the left-edge focus overlay is suppressed for the same window (hover reveal dies with the lock, PostsPaneView's mentor overlay alike). #108: rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure);ArchivePaneView= list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project →PostsModel.unarchiveProject), rows reuseLibraryPostRowwith Move Back to<project>+ Rename…, row-click selects + hops to Posts (onOpenPiececlosure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (newProjectAskBinding, the OriginAsk pattern). #111 (S7): the third ask —OutlineGuardSheet(outlineGuardBinding, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal →cancelOutlineGuard, Esc included). #114 (S4): the fourth ask —ConvertSheet(convertAskBinding) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (=cancelConversion); a ladder-drops-prose warning whenlossy; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip).PostsPaneView.swift— Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (PostEditorView), mentor column (MentorPaneView, fixed 356). Selecting a post opens an editing session;PaneHeadercarries the New Post button (export.pane-head .icon-btn). #92: the editor column renders the external guest (model.externalSession) ahead of the post session — one guest at a time, mentor column stays. #108 (variant B,ref/prototypes/wf104-library-ui-prototype.html):PostsLibraryColumnregroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11· Ncount, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted);LibraryPostRow(extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift;UnevenRoundedRectangle0/8/8/0 per.vB .post-row), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (MoveToProjectSheet, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash;RenamePostSheetinternal for the Archive pane's reuse. #144: the library search — a plain-text field under the Posts header (debounced 250 ms, title+body filter over non-archived pieces; body scan runs off-main throughPostStore.readBody, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, sameLibraryPostRow); state is view-local (query/matches, nil = sections render), so both render sites (unfocused layout + focus-mode reveal) get the field; clearing returns the project sections. #33 (S6.1): the editor column's session branch passespublish:to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts theMicropubPublishSheet(.sheet(isPresented:)beside.task(id: home)). #162: the focused branch mounts the Cold Turkey chrome as overlays (ColdTurkeySeatbottom-center,ColdTurkeyDotbottom-right) and suppresses the mentor hover reveal while a block holds; leaving focus drops a stale arm-bar (onDisappear).PostLibrary.swift—Post(nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32firstDraftStats: FirstDraftStats?;ContentTypepost|outline) +Post.scan(home:) -> [Post]: #107/ADR-0012 two-level scan — enumeratesprojects/<name>/<id>/post.mdANDarchive/<name>/<id>/post.md(archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs),typeread leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (untitledon blank, marker-only, or unterminated-frontmatter bodies);pass_state/originfrontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before---tolerated). Scan runs off-main (bind/rescan in PostsModel). #32 (S5.2): scan also reads the fivestats_*keys intofirstDraftStats—Post.FirstDraftStats(captured Date parsed from theyyyy-MM-dd'T'HH:mm:ssstamp, per-access POSIX formatter — the repo's no-static convention; +DraftStats), nil unless EVERY key parses to a FINITE Double (Double("nan")/"inf"parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, andstats_*arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. #143 (OPT-F3):scan(home:cache:)takes an optionalPostScanCache(path+mtime+size-keyed parse memo — an unchanged post.md is never re-read, a moved piece re-parses at its new path, project/isArchived re-derive from the walk; nil default = the old read-everything behavior, so every other caller is unchanged). The stamp is taken BEFORE the read and keys the store — a mid-scan rewrite can never be pinned as fresh (a late overlapping store keys its own pre-read stamp; the next scan mismatches and re-reads). #33 (S6.1):PostgainsmicropubURL: String?(frontmattermicropub_url, read leniently but gated onMicropub.trustworthyURL— imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructedPost(id:…)site keeps compiling).PostStore.swift— #18 write side (nonisolated), #107/ADR-0012 re-root: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap,untitledfallback),availableSlug(for:home:)collision suffixes-2/-3… over the GLOBAL slug space (all entries underprojects/*/ANDarchive/*/— an archived slug is never reused, restore can't collide; all comparisons through privatefolded(_:)= NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift==/Set hashing already fold canonical equivalence, sofoldedis the explicit, tested contract with the lowercase load-bearing;createProject's duplicate check uses the same fold),folder(of:home:)= the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)),writeNew(body:project:type:home:)(lazy folder underprojects/<project>/— defaultposts, the selected project flows in from PostsModel; #109:typeparam default.post, stamped first in the block — New Outline passes.outline; the returned Post carries it; #30:originparam default.writer— New Post from Session passes.aiso a session-born piece stamps immutableorigin: ai),overwrite(resolves viafolder(of:), preserves existing type/pass_state/origin, normalizes bare posts on save; #31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's),rename= retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stayspost.md; a title slugging to the current id only retitles),trash(resolves viafolder(of:)+FileManager.trashItem— recoverable),readBody(frontmatter stripped for editing). #114 (S4):convert(id:headingsLadder:home:)— the one-time in-place Convert to Post:typeflips to post, body transforms once (verbatim = unchanged; ladder =OutlineTree.headingsLadderBody), id/folder never move, vanished piece throws. One-way in v1.overwrite+convertshareexistingStamp(id:home:)(folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). #22:openableTypes/isMarkdown(.md/.markdown only, local file URLs — a dragged web link is not a document; sharedmarkdownExtensionslist),importFile(at:origin:project:home:)(copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every\nsplit sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim withtype/pass_state/originset-overwritten viamergedFrontmatter—type: postwins even over an externaltype: outline; absent keys inserted before the closing---; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; privatematerializeis the one lazy-folder pathwriteNewshares). #108:move(_:to:home:)(projects→projects folder move; refuses archived pieces via the resolved disk path — never the scan snapshot'sisArchivedflag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name viavalidatedProject, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers),archive(_:home:)/restore(_:home:)(folder moves into/out ofarchive/<project>/, project disk-derived the same way),unarchiveProject(_:home:)(moves every child ofarchive/<name>/intoprojects/<name>/— one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly),createProject(named:home:)(empty/slash/dot-prefix/:/control-char names + case-insensitive duplicates throw; lazily materializesprojects/<name>/), privaterelocatebehind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). #24 (S3.1): a same-fileextension PostStorecarries the pass write side —snapshotPass(id:kind:body:home:)(pre-pass body verbatim to<piece>/passes/pass-<n>.md; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) andadvancePassState(id:kind:home:)(monotonic: the new state is the higher of the file's pass_state and the pass's doneState via privatehigherState— passes run in any order, never regress; #31 (S5.1): the state update is an IN-PLACE key stamp (stampingFrontmatter— bare blockless posts still normalize throughstamped), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws). #27 (S4.2):advancePassStatealso ticks the decay clock —try? LearningDecay.recordPass(home:type:)after the stamped write (every completed pass counts, re-runs included;try?because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). #29 (S8.2): a same-file extension carries the research write side —writeResearchNote(piecePath:title:url:quote:note:home:), the keep write (the writer's explicit act — the ONLY path toresearch/; the tool rail writes nothing): the piece resolves through the ONEfolder(of:)id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinkedresearch/refuses before any write (promote's posture), file<yyyyMMdd>-<slug(title)>.mdvia FixCardStore's now-internaluniqueFile(collision-2/-3), flat single-line frontmatter (source/kept— title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. #31 (S5.1): a same-file extension carries the first-draft stats capture —captureFirstDraftStats(id:body:home:) -> Bool(@discardableResult,try?-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come fromDraftStats.compute(body:)and five flatstats_*keys (stats_captured=yyyy-MM-dd'T'HH:mm:sslexically sortable; four metrics%.3f) stamp IN PLACE throughstampingFrontmatter(widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan ofPost.frontmatter. #33 (S6.1):stampMicropubURL(id:url:home:)— in-placemicropub_urlstamp throughstampingFrontmatter(frontmatter-only: body + foreign keys byte-identical, so the open session's readBody echo check never fires); vanished piece throws. #141: same-file extension — the illustration ingest write side:ingestImage(from:pieceFolder:)copies (never moves) a dropped image into the piece'sassets/and returns the ref destination; type gate = #34'sMicropub.mimeTypeset (PNG/JPEG/GIF/WebP/SVG — nothing enters assets/ that can't ship,IngestError.notPublishable), a Finder folder with an image extension refuses (isFolder), a symlinked/file-shapedassets/refuses (hostileAssets— never write through it, the rail would refuse the send anyway); base name through the sharedslug(parser-clean: the #34 regex never matches space-bearing destinations, so ref and file agree at ingest), collisions suffix-2/-3withinassets/;illustrationRef(_:)is the onebuilder the drop surface and tests share.DraftStats.swift— #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'):DraftStats.compute(body:)→ burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercasedisLetter||isNumberruns (ponytail ceiling: no apostrophe joining); sentences = chunks between.!?with a token count > 0 (heading text gloms into the first sentence). Full precision out; the%.3frounding lives at store time (captureFirstDraftStats). #32 re-addedEquatable(Post's synthesized equality ridesfirstDraftStats). #161: internalwords(in:)(tokens(in:).count) is the one word-count rail — Cold Turkey net-words counts with it, so text metrics can never drift.WritingGoal.swift— #161 (Cold Turkey S1, map #158) the pure goal engine the writing lock consumes (nonisolated, no UI, no clock):WritingGoal(words(Int)|minutes(Int), one goal per block, fixed at arm) +WritingGoalRun(the armed block: goal +armedAt+ baseline/current word counts viaDraftStats.words).update(text:)takes whole-document text — typing/deleting/pasting/undo all land the same way,netNewWordsfalls out of the delta (deleting costs; a big paste counts).nowis INJECTED (isMet(now:),secondsRemaining(now:),progress(now:)0…1 clamped) — the countdown cannot pause by construction; minutes deadline is arm+minutes, inclusive boundary;isMetis live truth, unlatched (delete below target un-mets — the lock completes on the first true tick). S2'sWritingLockStateowns the ticker and calls this.WritingLockState.swift— #162 (Cold Turkey S2, map #158) the writing lock machine + kiosk:WritingLockState(@Observable, app-scoped asgate.writingLock;static weak activeis the app-delegate's quit-refusal handle) —start(goal:body:at:)arms (refuses a second block while locked), a 1 s ticker + the per-keystrokefeed(text:)(ProseTextView.onTextChange, both editor modes) driveWritingGoalRun,tick(at:)completes on the first met tick (internal seam — tests inject the decisive moments),complete()exits the kiosk and leavescompletionNotefading ~6 s.WritingLockKiosk— the #159 recipe verbatim (6-option combo +.disableScreenCornerInteractions), enter = activate→options→toggle (returns whether WE toggled fullscreen — an already-fullscreen window is entered in place; exit replays only what entry toggled), exit = options-clear-FIRST then toggle (never churn mid-transition); ⌘W + ⌃⌘F + ⌘N refusals = a local keyDown monitor (matched by KEY CODE with the exact modifier set plus a lowercased character net — audit 2026-11-04: charactersIgnoringModifiers is layout- and Caps-Lock-dependent, a Cyrillic/caps ⌘W slipped past while the stock Close still fired; ⌘N covers the stock New Window item SwiftUI owns, which stays enabled mid-lock) swallowing all three while locked (⌃⌘F added 2026-11-04: the kiosk holds even windowed, so a user-initiated fullscreen exit mid-block left a windowed kiosk — menu bar gone, quit refused — the dogfood trap; fullscreen now leaves only via completion) (SwiftUI owns the stock window delegate and.closeItemhas no CommandGroupPlacement — the OutlineDrag monitor pattern, installed/removed with the lock); hosted-test guard = full no-op (never kiosk the test machine).WritingLockAppDelegate(@NSApplicationDelegateAdaptorin MuseionApp) —applicationShouldTerminatewhile locked asks ONCE (#163 ruling 2026-11-04: "Walk away from the block?" — Walk Away clears the kiosk and quits, the block dying quietly with the process; Keep Writing cancels; unlocked quits pass straight through, all quit paths route here). Nothing persists — the block dies with the session.TrendsPaneView.swift— #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift ChartsLineMark+PointMark, one card per metric, adaptive ≥340 2-col grid). ReadsPostsModel.posts— the watched scan — so it refreshes with the library; no scan of its own. Only pieces withfirstDraftStatsappear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades).TrendMetric(nonisolated, pure, pinned in TrendViewTests): title /higherIsBetter(trigramRepetitionis the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) /verdict(first:last:)— improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11first → last · verdict(accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture showsvalue · one capture, no verdict — an arc needs two. Below the readout,TrendMetric.explain— one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).DeslopLint.swift— #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data:Resources/deslop-lint.jsonis the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly;key/landscape/highlight/bareunderscoredeliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the<home>/deslop-lint.jsonoverride, which wins whenever it exists AND decodes; any read/decode failure → bundled,Config(tiers: [], emDashBudget: .max)= silent no-op).compute(body:config:): one finding per phrase over its tier allowance (case-insensitive whole-word ICU match —delvednever matchesdelve), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration.emitdedups against OPEN cards (pattern + anchor.quote + occurrence) BEFOREFixCardStore.submit— closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). TherunPassseam fires it right aftercaptureFirstDraftStats.Pass.swift— #24 (S3.1) the pass substrate's shared vocabulary (nonisolated):PassKind(pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md;level= paragraph-level-and-up / sentence-level-and-below,snapshotFileName= pass-1.md/pass-2.md,doneState= .pass1Done/.pass2Done) andPassContext(stub(kind:pieceURL:hasResearch:)— the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), #29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them);estimateTokens= (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).BlindRead.swift— #122 the Blind Read's prompt vocabulary (nonisolated):prompt(snapshot:current:snapshotFirst:)— both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rollsBool.random()), ask pinned to a pick ("A"/"B") + one line why, no rewrites;reveal(kind:snapshotFirst:)— the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue.Micropub.swift+MicropubMedia.swift+MicropubPublishSheet.swift— #33 (S6.1, M6) + #34 (S6.2) the Micro.blog publish path:Micropub.swift(nonisolated) holdsMicropub(the client: fixed endpointhttps://micro.blog/micropub, ProviderProbe's Transport seam — URLSession live, canned in tests;makeDraftRequest= JSON h=entry create withname[Title],content[markdown body verbatim — GLOSSARY: never stripped, except #34's asset illustration refs which REWRITE to their uploaded URLs on the WIRE — position and alt stay the writer's; the piece on disk never changes],post-status: draft, sorted keys,category:frontmatter never travels; #34: uploaded illustrations ride INLINE insidecontent— the rail rewrites each asset ref to its uploaded URL exactly where it stands; NOphotoproperty (a property renders wherever the theme decides — live-verified 2026-11-01: bottom of the post, position lost));makePublishRequest=action=update+replace.post-status: publishedagainst the draft URL; outcome decode: Location header → bodyurl— thepreviewlink is display-only, NEVER the publish target; every draft URL passestrustworthyURL(https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline----rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub'serror_description, transport throw → unreachable;decodeFailureis internal (the one failure decode — MicropubMedia's media steps share it rather than fork it) andMicropubTokenStore(the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from.env; legacy login keychain, NOkSecUseDataProtectionKeychainwhich needs keychain-access-groups this undistributed app doesn't sign with;kSecAttrAccessibleWhenUnlockedThisDeviceOnly; servicecom.babylondreams.Museion.micropub, accountmicro.blog; read/save-replaces/delete,accountparam defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries thePostsModelpublish-flow extension (see the PostsModel bullet).MicropubMedia.swift— #34 (S6.2, G12) illustrations travel with it (anonisolated extension Micropub):illustrations(in:)parses the body'srefs — the ONLY images Museion uploads (remote http(s) refs ride as prose; ceiling (ponytail): plain paren form, no fence scan, no space-bearing destinations);rewritingIllustrations(_:uploaded:)builds the wire content (each UPLOADED ref swaps exactly where it stands — position and alt are the writer's, a quoted title drops, foreign images and unuploaded refs ride byte-identical, and a URL carrying markdown-active characters ()/(/<>/space) rides the ANGLE form— a plain-paren dest would close at the first)and smuggle a live attacker link; trustworthyURL was built for line-bounded frontmatter, not this sink — parse and rewrite share ONE regex (alet) so they can never drift);mimeType(forDestination:)= exactly the endpoint's formats (png/jpg/jpeg/gif/webp/svg — anything else refuses, no guessed content type ships);mediaEndpoint(token:transport:)=GET ?q=configdecode ofmedia-endpointbehind the trustworthyURL gate (the writer's PNG and token POST to the discovered endpoint);makeMediaUploadRequest/uploadMedia= the multipartfilePOST (boundary per request; the filename is sanitized — a quote/control char can't break the Content-Disposition) decoding exactly like the create (Location → bodyurl→ trust gate → requestFailed; 401/403 → authFailed);Illustration/MediaResultare the shared shapes (Photodied with the property path); the alt group in the shared regex is SINGLE-LINE by design — a ref whose alt spans lines doesn't parse at all (rides as prose, never uploads, never rewrites — a parsed-but-unrewritten ref would ship a broken relative link). The publish FLOOR lives in ONE gate (#6: where all callers route — a parsed body ref is the ONLY way an image ships, and every send routes through it): the model rail —uploadIllustrations(private PostsModel helper besidemicropubSendDraftin Micropub.swift) — refuses BEFORE any wire traffic (the refusal names the destination — the parse itself never hides a ref), pre-flights every payload read and CONTAINS it in the piece — a../ref OR a symlinked asset refuses (resolvingSymlinksInPathboth sides, the cards/learnings posture; the payload list is one entry per FILE — duplicate refs share it and upload once) — before the first upload, uploads are all-or-nothing (a failed upload never sends a half-illustrated piece), and the engine is consulted for nothing — style judgment stays with the author (G12). ponytail: a re-send re-uploads (Micro.blog keeps both copies; dedup viaq=sourceis v2's call).MicropubPublishSheet.swift— the G9 ask-before surface owning both steps: Send as Draft → (review via the preview link) → Publish, each its own explicit click; refusals inline orange with buttons kept (ApplyAskSheet posture); the token field appears when none is saved or after an auth failure (re-entry replaces — never a dead end), a fresh entry is saved ONCE to the Keychain;Send Againre-drafts (the piece changed post-draft) and overwrites the remembered URL;.onAppearseeds from the piece'smicropubURLso a draft from an earlier session still publishes.PostsModel.swift—PostsModel(@MainActor @Observable, app-scoped viaAppGateState.posts): #146: the domain extensions live in their own files — outline guard + Convert (PostsModelOutline.swift), pass + Blind Read (PostsModelPasses.swift), fix cards ×3 (PostsModelCards.swift) — andstartWatching+rescansit in a file-scope watcher extension (type-body ceiling); members the moves straddle are internal and the two wrapped guards unwrapped (#142 posture) — nothing else changed. posts list + selection + New Post draft (PostDraft, in-memory, no folder until first save; #107: carriesproject— captured atnewPost()from the selected non-archived post's project, else the defaultposts; #109: carriestypetoo, default.post—saveDraftthreads it intowriteNew;mountID(UUID per staging) keys the editor's.idso every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree;newOutline()is newPost's exact dismissal/selection path with a"- "/.outlinedraft instead;importFileslands in the same target project; #30 (S2.7):newPostFromSession(body:home:)— the session-born materialize+open path:writeNewwithorigin: .ai(never stats-eligible), thenselect(the WorkspaceView selection onChange hops the pane) + rescan; nil +lastErroron failure); the open post'sEditorSession(#19) —select(_:home:)ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session,shutdown()flushes on app quit; recursive FSEvents stream (kFSEventStreamCreateFlagFileEvents, 0.5 s latency — the debounce; file-level so nestedpost.mdedits fire) on BOTHprojects/andarchive/(#107 —PostsWatcher.start(urls:)takes an array), rescan reusingPost.scanoff-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text; #143 (OPT-F3): the rescan threads one app-scopedPostScanCachethrough the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips thepostsassignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observingpostswould regroup on the app's own autosave echoes);bind(home:)from.task(id: home)createsprojects/+archive/if missing + rebinds on repoint; lifecycle ops (saveDraft/rename/trash) setlastErroron failure, never alert; the session'sonErrorroutes save failures into the same strip. #111 (S7) mixed-content outline guard:selecton atype: outlinepiece whose bodyOutlineTree.parsesWithLossflags ends the old session, nils the new one, and holds the open (outlineGuardPieceID) — theOutlineGuardSheetask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answersopenGuardedOutlineInProse(home:)(setsproseOverridePostID— a routing override withlastDraftWasOutline's exact lifecycle, cleared in newPost/newOutline/select/openExternal) /openGuardedOutlineAsOutline(home:)(consented drop on save) /cancelOutlineGuard()(no session, selection cleared; still guarded next open);outlineGuardPieceIDalso dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes throughopenUnguarded(the one open body; it clears the hold too);isGuardedOutlinedoes ONE disk read deriving type (scan-known, else frontmatter) + body viasplitFrontmatter; guard members live inextension PostsModelin PostsModelOutline.swift (#146). Routing: PostsPaneView suppresses outline forproseOverridePostIDand renders an inert notice while a guard hold is up. #22:externalSessionguest slot (#92 — one at a time, transient per launch, takes the editor column;openExternal(url:)refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first viadismissExternal;select/newPostboth route through the dismissal), a secondPostsWatcheron the external file's folder (#93 — its events re-read the file and feed the session'sdiskDidChange, the #67 conflict check reused verbatim),shutdown()also flushes the guest (#96.3), and the import path:stageImport/cancelImportholdpendingImportURLsfor the ONE Origin ask,importFiles(origin:home:)copies each viaPostStore.importFile, continues past per-file failures intolastError, opens the last success,wireSession()routes both sessions'onErrorinto the same strip. #108: project ops behind the variant-B library + Archive pane —pendingProject(the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, onselect, and onopenExternal— anywhere the draft dies),targetProject= pending ?? selected-non-archived ?? default,flushOrAbort(audit:EditorSession.flush()returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unansweredconflictAlertaborts the same way — "answer the reload question first", the alert stays up),moveToProject/archivePost/restorePost/rename/unarchiveProject(all flush-first — audit 2 closed the rename + unarchive gaps;unarchiveProject's membership check is disk-derived viafolder(of:), captured before the move, not the posts snapshot),restorePost(reopens the session off the archive path —selectalone would keep the init-timefolderURL; a cold restore still selects),moveTargets(home:)(audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects),createProject(named:) -> String?(nil = success; the failure reason shows inline in the sheet, never double-messaged intolastError),stageNewProject/cancelNewProject/askNewProject(the New Project ask, pendingImportURLs pattern),newProjectPending(no re-validation — the sheet trimmed,createProjectvalidated). #114 (S4) Convert to Post:pendingConversion(PendingConversion {id, lossy}— id-scoped, survives background selects; lossy =parsesWithLoss, drives the sheet's ladder warning) staged bystageConversion(_:home:)(outline pieces only; lossy fromsession.textwhen the piece is open — disk lags the debounce, else disk),cancelConversion();convertToPost(headingsLadder:home:)=flushOrAbort(failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) →PostStore.convert→ when the piece was the open session: teardown-no-flush + reopen viaopenUnguardedwithproseOverridePostIDset (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in the Convert extension (PostsModelOutline.swift, #146). rescan's #67 echo check is gated by session IDENTITY (openSession === session— a same-id reopen must not receive the old session's stale disk text as a conflict). #24 (S3.1) pass orchestration:runningPass(stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) +runPass(_:home:mentor:)in PostsModelPasses.swift (#146): guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse withlastError) →flushOrAbort(the engine reads disk) →PostStore.snapshotPass(pre-pass, unconditional — even a cancelled pass snapshots) → #31 (S5.1):PostStore.captureFirstDraftStats(id:body:home:)— fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass → #6 (S3.4):DeslopLint.emit(body:pieceID:pieceURL:kind:home:)— the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitterlintfix cards in<piece>/cards/(seeDeslopLint.swift) → #137 (S4, per #129/ADR-0014):runningPassgoes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) →mentor.runPass(kind:stub:pieceTitle:)— the pass runs on its OWN one-shot engine (hermes acp -p museion-passN), streams into the transient unrostered transcript underpassTranscriptKey, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions) → advance ONLY on.ended(stopReason)with stopReason ≠ "refusal":PostStore.advancePassState+ rescan (the library regroups).cancelPass(mentor:)= the existing session/cancel rail (stopStreaming); cancel/refusal/crash advance nothing — the transcript tells the story. #122 Blind Read:blindRead(home:mentor:)(PostsModelPasses.swift, #146) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail —runningPass/runningBlindReadrefuse each other; mentor not mid-turn; engine ready; OPEN saved piece) →flushOrAbort→PostStore.latestPassSnapshot(newest snapshot on disk, either kind; none → honestlastError"run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) →runningBlindRead+mentor.runBlindReadwithBlindRead.prompt(order randomized per trigger) and the reveal;lastErrorclears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable.openPieceHasSnapshot(the pass bar's disabled-with-help gate) derives inrefreshCards. #23 (S2.4) fix-card surfacing:openPieceCards([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed byrefreshCards(home:)(session's piece id →PostStore.folder(of:)→FixCardStore.scan; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires oncards/writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. #25 (S3.2/S3.3) card lifecycle:applyCard(_:home:)→FixCardApplyOutcome(.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session),flushOrAbort(dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor →close(status: .open, anchorStatus: .stale)+ NO text selected or changed, the edit lands throughEditorSession.adoptText(buffer and disk agree, both surfaces re-seed), the card closes .applied,refreshCardsre-derives;skipCard/doneCard→ one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). #26 (S4.1):promoteCard(_:home:)→FixCardPromoteOutcome(.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), callsFixCardStore.promote(pieceURL: session.passPieceURL, …), failure →lastError"learning write failed: …", success →refreshCards; touches no text, flushes nothing (writes a Learning, not an edit). #33 (S6.1):micropubSendDraft(home:token:transport:)(same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates,flushOrAbortfirst (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (Post.title= the entry's name,splitFrontmatterbody = the content; no scan dependency),Micropub.sendDraftover the injected Transport, and a successful draft stamps the piece'smicropub_url(try?— the draft already landed; a stamp failure only costs the cross-reopen memory). #34 (S6.2): the send first routes through the privateuploadIllustrationsrail (same file) whenever the body carries asset illustration refs — floor + pre-flight +q=config+ one upload per PNG — then handsMicropub.sendDraftthe wire body with every uploaded ref REWRITTEN to its URL in place (position preserved, no photo property); a piece WITHOUT illustrations keeps the exact #33 single-request wire (pinned). #162 (Cold Turkey S2):canArmWritingLock(can the lock arm on what's open — mirrors the editor branch's outline routing: prose drafts, the external guest, prose posts qualify; outline pieces never) andeditorBodyText(the live whole-document text of the surface the editor is showing — the lock's arm-time baseline; the per-keystroke feed rides ProseTextView.onTextChange).OutlineTree.swift— #109 (ADR-0013) the Outline tree model (nonisolated, pure):OutlineNode(id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) +OutlineTreeparse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save:-/*+ space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (# Titlefrom the renamer survives above the tree), non-item lines after it drop; serialize emits" " * depth + "- " + text, no trailing newline. #111:parsesWithLoss(_:)— true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; sharesparseItemso detector and parser never disagree). Structural ops are path-addressed ([Int]), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op):indent(last child of previous sibling),outdent(right after parent),move(up:)(sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil),enter(caretOffset:)(empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") withEnterResultfor focus routing. #112 drag primitives:extract(_:path:)(remove + return a whole subtree) andinsertRun(_:parentPath:index:in:)(splice consecutive siblings at any parent, index clamps to append) over privatewithChildren— id-preserving like every op; the presenter sequences them for drops. #114:headingsLadderBody(_:)— the Convert-to-Post ladder transform (roots##, steps to the######floor, deeper stay bullets re-based flush; preamble verbatim; sharesscanso depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.OutlineEditorView.swift— #109 the outliner editing surface (#105 verdict, variant B):OutlinePresenter(nonisolated, pure, tested) projects the tree into visibleRows (preorder, fold-skipping, per-row childCount + foldedDescendantCount; #112:zoomRootIDroots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document;rangeIDsis zoom-aware), resolves id↔path/node +setTextby identity,rangeIDs(block-selection span, ⇧↑/⇧↓ anchor↔focus) andapplyBatch(block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY viaOutlineTree.siblingMovewith boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style).OutlineEditorView(SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; #112: double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promotedOutlineRowTextViewon the focused row (see its own file), static inline-markdown text elsewhere. #112 (S6, wf113 verdict — variant A "fat gaps"): the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at thekeyDownhead in OutlineRowTextView.swift: function-key scalars"\u{F700}"/"\u{F701}"—String(NSUpArrowFunctionKey)is its decimal description;.function/.numericPadbits stripped before modifier compare; ⇧⇥ = backtab\u{19}with aninsertBacktaboverride; Esc via a localNSEventkeyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before.onExitCommand, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter →enter(UTF-16→grapheme caret conversion). Typography contract: live rows carryProseTypography.outlineRowAttributes(body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's.padding(.vertical, 3), andsizeThatFitsfloors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-fileextension OutlineEditorView(type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery —session.edit(md)oronDraftEditfor drafts; focus follows node IDs; folds are session-scoped view state. Routing:PostEditorView.outlineflag swapseditingSurfaceto the outliner;PostsPaneViewpassesdraft.type == .outlinefor drafts andlastDraftWasOutline || posts-lookupfor sessions.OutlineDrag.swift— #112 (S6) the drag plumbing + drop math:OutlineDragCatcher/CatcherView(one transparent NSView per row —.gripowns the left margin, click focuses / drag always runs;.bodyoverlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past itDragTrackerowns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY inarmDrag— a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); astatic currentguard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry =CatcherView.rowFrames(in:), a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the.windowcoordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as anonisolated extension OutlinePresenter:DropTarget(.before/.afterLast/.lastChild, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings),draggedIDs(selection rides deduped — a selected ancestor carries its selected descendants),isValidDrop(ref at/inside the moving run),applyDrop(extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot),hitTestDrop(fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). PlusDragInfo,DropGeometry(grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift),HLine(dashed invalid seam).OutlineRowTextView.swift— #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (RowTextView), native undo/IME, rust caret, wraps at the column width;keyDownintercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission);sizeThatFitsfloors at 21 so the row never grows on focus.- Editor core (#19 / S1.2, ADR-0010 mode B):
ProsePresenter.swift(nonisolated) — #77 reading-parity rework: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS--lh 1.8via font metrics (lineHeightMultiple(font:cssLineHeight:)— copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits:**bold**/_italic_/`code`/ link labels (ink + underline; brackets+URL dim; CommonMark intraword-_never emphasizes), list markers + heading hashes + quote markers dim; full-docattributeon load, per-paragraphreattributeon edit; plain store stays the source of truth (ADR-0010: presentation-only attributes).EditorSession.swift— @MainActor @Observable session per open document: #22SessionTarget(.post(id, home)|.externalFile(url)— postID/fileURL computed per target; #107:folderURLis a stored property, resolved once at init for posts viaPostStore.folder(of:)(fallbackprojects/posts/<id>for a vanished piece); the convenienceinit(postID:home:)keeps #19 call sites unchanged);editre-arms a ~1 s debounce (#64) →flush(⌘S / selection change / window close / app quit also flush);flushroutes through target-awarewriteDocument— posts writePostStore.overwrite+ the cursor sidecar, externals write the whole text in place with NO sidecar (#93);loadFailed(audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session;openExternalrefuses it intolastErrorandflushis a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on\n; a CRLF pair is one Swift grapheme); trackssaveStateChanged→Saved (+ Save failed in accent, #65/#83, routed tolastErrortoo — dirty = local text ≠ last flushed, shown honestly while the debounce holds);diskDidChange(diskText:)raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher);reloadFromDisk(alert Yes) bumpsloadGeneration+ re-reads (posts restore the sidecar cursor, externals reset it — #93);keepLocal(No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then);teardown(flushFirst:)is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); #25:adoptText(_:)— Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (loadGenerationbump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict);folderURLexposes the document's folder for reading image resolution (#71).PostEditorView.swift— toolbar (mono crumb +SaveStateDot: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; #92: the external guest's crumb is the file name) +ProseTextView(NSViewRepresentable: plainisRichText = falseNSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by sessionloadGeneration— never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; #22: message names the file, post.md or the external's). #77 spellcheck posture:AppGateState.spellChecking(default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (EditSpellingTogglein MuseionApp.swift — commands views takegateas a plain property, they don't inherit the window environment) and applied to the live NSTextView inmakeNSView/updateNSView.PostStorecursor sidecar (#66):CursorState{selectionLocation,selectionLength,scrollOffset}Codable in the resolved piece folder's.museion-state.json(#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - Prose list machinery (#115 / S5, map #110):
ProseList.swift(nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer:Item(marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared withProsePresenter.listMarkerPattern(marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item.ProseListTextView.swift— NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (Foldkeyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height viaProseTypography.foldedAttributes(buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. #142 paragraph-scoped fold maintenance: ashouldChangeTextoverride records the last accepted single-line edit (range + UTF-16 delta,pendingPlainEdit);refreshFoldsroutes it to the in-place re-key (rekey— pure,RekeyOutcome: survivors shifted by delta, marker-line edits kill the fold and return the scope for un-hiding, scope-interior edits grow/shrink it and flag the edited line for re-hide + caret park) — no parents rescan, nosetAttributedStringswap. The single-line gate is\.isNewline, never a literal"\n"/"\r"compare —"\r\n"is ONE grapheme equal to neither, and a CRLF-carrying edit must reach the full pass (finish-audit pin);apply()nullspendingPlainEditoutright — structural edits reshape blocks even when the replacement is single-line (a childless unterminated block's outdent; finish-audit pin,performOutdentinternal for it). A font probe at each survivor's scope head guards the path: hidden styling still present, else fall back to the full pass (wholesale restyles like the fence-flip self-heal this way); dead-scope un-hides are bounds-hardened at the sink. Full pass stays for structural edits, wholesale loads, and toggleFold.Foldcarries the hiddenscope(shift-maintained; the full pass re-derives it). Chrome rendering (#115 field findings, #142 rework): SwiftUI-hosted TextKit2 never callsNSTextView.draw(_:)and everyNSTextLayoutManagerfragment query (location bridge,textLayoutFragment(for:), enumeration) yields nothing — chevrons/⋯N render as one TINY per-glyph CALayer (contents = a small flipped NSImage raster,isGeometryFlippedon the overlay layer so sublayer frames speak lineRect's top-left y) in the click-throughProseChromeViewoverlay (deferred one main-queue tick past textDidChange) — NEVER a document-sized bitmap (~35M pixels per keystroke on a tall doc, #142/F2); glyph rasters are cached by string (chromeGlyphImages— 50k parents share a handful of images; layers stay unculled because scroll fires no refresh, ponytail-noted); an edit at/after every parent line skips the rebuild outright (parentsUnmoved), and line geometry comes fromfirstRect(forCharacterRange:)(SCREEN coords →window.convertFromScreen→ view) because the selection/caret pipeline is the only geometry source that answers under this hosting. #141 illustration ingest: window-level SwiftUI.dropDestinations STARVE every deeper drag destination — an NSTextView registered for.fileURLnever received one callback, and a nested editor-level SwiftUI destination never fired either, whileWorkspaceView's #91 window destination claimed every drag (green copy badge, silent refusal; field-verified 2026-11-02 via stderr tracing — the docs' nested/innermost-first destination model does NOT hold; one window-level target is the whole routing surface). Routing inside its perform: a PURE-markdown set (allSatisfy— a mixed md+image set falls through and refuses loudly, finish-audit 2026-11-02; images must not vanish silently behind the md) forwards throughopenExternal(#91's open-as-guest preserved), everything else bridges throughProseDropBridge(app-scoped onAppGateState.proseDrop, weak live-text-view handle, set in ProseTextView make/updateNSView, non-optional at both constructor call sites) intoProseListTextView.ingestDrop(_:): gates = non-nilingestFolder(saved posts only — drafts/guests get the strip) + every file publishable (#34'sMicropub.mimeTypeset; mixed md+image refuses too), then copies each URL viaPostStore.ingestImageand inserts the joinedillustrationRefs at the drop point. The source must be a PLAIN file — a dropped symlink refuses (IngestError.isLink:copyItemwould land the LINK itself and the #34 rail would refuse the whole send; finish-audit 2026-11-02, empirically verified), a Finder folder with an image extension refuses (isFolder); collisions rideFixCardStore.uniqueFile(-2/-3, the research-note helper — no bespoke loop). Drop-point mapping (the hard-won part, #115's family): the SwiftUI closure'slocationis UNUSABLE under this hosting; the pointer's screen position (NSEvent.mouseLocation) maps to an index viafirstRect(forCharacterRange:)— its y is bottom-up screen coords like the mouse (no flip), non-contiguous layout makes OFF-SCREEN characters return garbage rects (whole-doc searches converge on the layout boundary), sodropIndex(length:targetY:bandMinY:bandMaxY:rectY:)— anonisolated staticPURE function (pinned by tests without a window) — SAMPLES the document (512 points), keeps only rects inside the viewport band (plain NSView geometry), brackets the drop between two in-band samples, binary-searches the bracket; a pointer above every in-band sample clamps to the first visible char, below all to the last in-band sample, no in-band evidence to 0 (never the old silent index-0-on-garbage), then slides the index to the next whitespace gap (never splices inside a word or an existing ref; dogfood-verified 2026-11-02, landing within one line).altselected (offset +2, length 3) and scrolled to, withCaretCentering.syncTypewriterInsetre-synced after the edit — without it the typewriter inset is stale and the editor freezes scrolling until the next keypress; one shouldChangeText step = one undo, didChangeText driving the coordinator (reattribute + session.edit + folds); refusals land in the transientshowIngestNoticestrip (mono-11 rust pill pinned to the scroll view's top-center, auto-hide ~4 s), multi-image ingest is non-atomic by design (ponytail comment). Outline surfaces have no ProseTextView → the bridge is nil → image drags bounce (AC4), markdown forwards. Reading mode swaps the surface away — no editor drop target while reading. - Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014):
SettingsPaneView.swift— sidebar + detail shell (SettingsPage: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current; #136: the pane takesbinaryPath— the gate's winner — builds the model overHermesSettingsWriter, and.task { await model.hydrate() }reads the live profile state at pane open). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded).SettingsPagesView.swift— the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header —resetToDefault(for:), a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship).ModelComboBox.swift— NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), andcomboBoxSelectionDidChangefor dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read fromobjectValueOfSelectedItemand the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). #136:ModelRegistry(the lenient~/.hermes/provider_models_cache.jsonload, memoized vialoadedDefault) lives here — the combobox's own data source.SettingsModel.swift—ModelProvider(rawValues are hermes slugs; OpenAI =openai-api) with per-provider effort ladders + pinned switch-default models,ZaiKeyTypeendpoint families,SettingsModel(@MainActor @Observable, pane-local still — the AppGateState lift waits on the restart-on-change slice):config(for:)clamps a hydrated effort outside the provider's ladder to nil (a blank menu selection never renders),hydrate()reads each profile's model block IN PARALLEL through the writer'sreadSurfaceCLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint inferszaiKeyType+ the endpoint family, any OTHER non-empty zai base_url seeds the endpoint field — a custom endpoint survives hydration, never clobbered to a family default; an edit that fired while a read was in flight owns the truth (hydrate skips targets with a pending write task — 2026-10-28 audit fix, no mid-hydrate stomp); reads only — hydrate never writes),testConnection(for:)runs the probe per provider (testStatesdrives the Provider Keys page; the empty-key precondition fails fast off the network),probeModel(for:)picks the first surface on a provider else its flagship, and writes COALES per target —persist/persistKeycapture-and-cancel the predecessor then (2026-10-28 audit fix)awaitits value past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write QUEUES — the last edit is always the last write to land (injectablewriteDebounce, default 0.35 s; a superseded-in-window write never spawns, so partial key prefixes of a secret never reach.env; tests pass 0);awaitPendingWrites()is the tests' sync point; write failures land inlastWriteError(orange strip under the header, cleared by the next SUCCESSFUL write).writeSurfacecalls carryzaiEndpoint(the endpoint family when the surface is zai — written LAST becauseconfig set model.providerCLEARS a stalemodel.base_url, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three.envfiles (2026-10-28 dogfood amendment). #136 (Profiles S3) — the real write path + Test Connection:HermesSettingsWriter.swift— the productionSettingsWriting(the protocol +NoopSettingsWriterlive here beside it,: Sendable, three methods): surface writes ride the engine's own CLI (hermes -p <profile> config set model.provider/model.default/model.reasoning_effortset-or-unset +model.base_urlfor the z.ai family; wire-verified✓ Set/✓ Unset <key>lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsertVAR=valueinto ALL THREE profiles'.env(2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are ignored by hermes for other providers — and pre-lands for any later provider switch; var names from hermes' own registry,ModelProvider.envVarName: GLM_API_KEY/ANTHROPIC_API_KEY/OPENAI_API_KEY; foreign lines preserved byte-for-byte via pureupsertEnv; a value containing a line break/NUL is REFUSED at the shared sink before any file is touched (2026-10-28 audit fix: a pastedkey\nOTHER_VAR=xis an env-file injection — the error rideslastWriteError); anNSLockserializes the read→upsert→write across concurrent cross-provider key writes (the same three files — a racing last writer would drop the other's var); 0600 — hermes' own .env posture; an EMPTY key leaves.envalone — the field sets, never removes; the zaimodel.base_urlwrite-through rides only the profiles on zai —profilesis that target list, not the .env list),readSurfacehydrates viaconfig get×4 (provider/model/effort/base_url) andreadProviderKeyreads each provider's var back (first non-empty across the three.envfiles) so a restart neither blanks the key fields nor refuses Test Connection; all blocking work hops off-main insideTask.detached; secrets never ride argv and never reachlastWriteError;hermesBinarynil (pre-gate) refuses writes honestly.ProviderProbe.swift— Test Connection (factsheet §4, live-probed wire shapes 2026-10-27, corrected 2026-10-28 after dogfood): step 1GET /models(key validity + reachability; z.ai proves nothing about key-type pairing — §1.2), step 2 a minimal STREAMING chat call — every request carriesContent-Type: application/json(the 2026-10-28 live incident: without it URLSession defaults to form-urlencoded — z.ai answers HTTP 200 with an error envelope, OpenAI can't parse the body at all; curl set it, the app didn't, Anthropic tolerated it); zai pins the stable GLM wire (thinking:enabled+reasoning_effort:low) at{endpoint}/chat/completions; OpenAI speaks the RESPONSES API ({endpoint}/responses,input+max_output_tokens— maintainer correction 2026-10-28, chat-completions is the retired path); Anthropic posts{endpoint}/v1/messages(max_tokensrequired) authing viax-api-key+ pinnedanthropic-version2023-06-01, never Bearer; the token cap is 512 (probeTokenCap— the live tail proved 64 starves reasoning models: glm-5.3 burned 64/64 on thinking, finish=length, zero content); decode is honest per the factsheet envelopes — zaierror.code1113 → wrongKeyType, 401s → authFailed (Anthropic detail carriesrequest_id), transport errors → unreachable,finish=length/max_tokens/incomplete+ empty content → starved, an empty 200 → requestFailed, and errors riding a 2xx decode as the provider error (z.ai's 200-carried content-type envelope live-probed; OpenAI nests it underresponse.error);workscarries latency + model count (the reply payload died in the 2026-10-28 audit — no consumer); theTransportclosure is injectable (production buffers the streamed response over URLSession); URL builders are nil-safe (a garbage endpoint reads unreachable, never traps). The Provider Keys page carries a per-provider Test Connection button + one-line verdict (TestConnectionResult: accent "✓ works · N ms · N models" / orange decoded failures). DesignTokens gainssettingsSidebarWidth190 /settingsFormWidth480. #137 (S4):SettingsModel.onChatSurfaceWritefires after a SUCCESSFUL chat-surface write ONLY (never pass surfaces — their engines are one-shot — never key writes, never failures);SettingsPaneViewtakes the closure and WorkspaceView wires it togate.mentor.requestRestart(), so a committed Chat model change restarts the resident engine in place (deferred to turn end while streaming, slice A's API). - Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09):
AppGateState.isFocused(transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F viaFocusModeTogglein MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap).FocusChrome.swift—HoverZone(tracking-area edge strip, click-through viahitTest → nil;zoneWidthis the calibration knob),FocusOverlayPanel(slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden =opacity(0)+accessibilityHidden),CaretCentering(soft caret centering: ±60pt comfort band, puretargetOffsetmath + animated clip-view scroll fromtextDidChangeonly — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; #88 calibration: EDITOR-WIDE, not focus-gated — centering plussyncTypewriterInsetbreathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore thefocusedguard at the two call sites).WorkspaceViewhides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden).PostsPaneViewhides library+mentor columns; right-edge hover slides the mentor back in (same width verdict —showsMentor).PostsLibraryColumn(extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. #162 (Cold Turkey S2, map #158): the chrome lineage grows the lock —ColdTurkeySeat(one bottom-center seat: the arm-bar before Start, the live readout while locked, the completion note fading ~6 s; the arm-bar carries a chip that BLENDS into the focus ground — 2026-11-04 dogfood amendment: the ground's own color + the faintest token hairline, no shadow, because the bare seat let the document text show through; readout + note stay bare mono; readout = numerals + 2px hairline, terracotta numerals inside the last 20 %, piece title absent; the arm value is directly typeable — parsed and clamped at every read — with ± steppers for coarse moves; defaults 250 words / 5 min, ranges 1…1000 words / 1…60 min — what's typed is what arms, the 2026-11-04 dogfood amendments; the readout and completion note carry the same blending chip) andColdTurkeyDot(the persistent muted pip bottom-right, label on hover, click opens the arm-bar — hidden while the bar is up, a block runs, or nothing prose is open). The arm-bar's Esc = a hidden.cancelActionbutton (the PostEditorView ⌘S rail —.onExitCommandnever fires behind the hosting view, the #109 probe). Both mount as overlays on PostsPaneView's focused ZStack only, so lock transitions never restructure the editor column (the #87 remount hazard / typing-continuity AC).PostEditorView— toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the fullSaveStateDot(loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden;ProseTextView.focusedcarries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). #89 two-color world (calibrated live, deliberate departure from the export):DesignTokens.background#FAF9F3 (chrome + focus ground),DesignTokens.surface#FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcodedNSColor.whitesites are gone), rust #C96442 caret (insertionPointColor), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. #90: Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73):
ReadingPresenter.swift(nonisolated, pure) —stampSourceprepends<!--S:N-->sentinels before every blank-line chunk (apex passes HTML comments through);apexRenderruns the bundled apex binary (Museion/Resources/apex, fs-sync group ships it in Resources automatically; fallback chain bundle →APEX_PATH→ Homebrew, dev-only) with-t html --no-mixed-lists --embed-images [--base-dir <postFolder>](no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one- , killing
AppGateState.museionHome— app-scoped Home (UserDefaultsmuseionHome; non-file URLs read back as nil — the Home is always a folder). #171: fresh installs (no stored override) resolve once and PIN the winner, so the Home never silently moves: (2) legacy~/Documents/Museionexists as a directory (existingDirectorygate — a stray plain file is not a Home and falls through) → pin it (existing Homes migrate manually, never silently), (3)<CloudDocs>/Museionwhen iCloud Drive is present (CloudDocs resolved dynamically at the unprefixedLibrary/Mobile Documents/com~apple~CloudDocspath — never a hard-codediCloud~form; plain FileManager probing, no ubiquity entitlements per ADR-0009), (4) else the silent Documents fallback — no dialog, no rail pill. The ladder + probes live inHomeResolution.swift(resolvedInitialHome/liveCloudDocsDir/existingDirectory); init takes injectable probes + defaults — hosted tests drive the ladder without touching the machine's real iCloud state, and the DEFAULT construction under hosted tests takes an early return (legacy fallback Home): neither the real probes nor the pin run, so the runner app's real iCloud state and defaults are never touched. Explicit init:Selfin a stored-property initializer breaks@ObservationTracked(covariant-Self error).MentorPaneViewno longer carries a root min-frame — it lives in the 356pt mentor column.
1. 1. 1.renumbering; embed-images inlines base64 soloadHTMLStringneeds no file access and nothing is written to the vault);stampHTMLregex-rewrites sentinels todata-source-line="N"on the following element (0 mis-stamps corpus-wide, #74);blocks(for:)builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract);page(for:postFolder:)assembles the shell withstyleSheet()— #72 rework: the whole stylesheet isMuseion/Resources/reading.css, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. #72 polish (critique-directed, 2026-10-07): flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em,body > :first-childno offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover;::selection/:focus-visiblethemed; secondary tokens--secondary/--rule/--substrate. Fallback on apex failure = escaped source in a<pre>(#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision).ReadingSurface.swift—ReadingStateBox/CaretHintBox(flow state, #68) + one WKWebView reloaded in place (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injectedprobeJSmaps click→source line (tap = edit intent at that block), ⌘-click→NSWorkspace.open, scroll→top-visible-line intostateBox.topSourceLocation;decidePolicyForallows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top afterdidFinish; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot:ReadingCanvasView,Decoration,framesForRange,ImagePopoverView(ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched:ProsePresenter,EditorSession,ProseTextView, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.Engine check (gateless launch, #35–#41 + #151, map #148)
EngineGate.swift—EngineProbe(nonisolated): six-path probe order,acp --checkhealth (stdin closed, 5 s timeout, exit-status branching),acp --versionversion,state.jsonwriter/reader.EngineGateModel(@MainActor @Observable): phase machine (idle/checking/pass/fail) — #151: the pill's state source, unchanged;onPassseam (fires the auto-fire chain),currentBinaryPathhanded to provisioning.execute(_:timeout:)/ProcessOutputare internal — shared child-process machinery.- #151 — the gateless flip:
AppGateState.startLaunchCheck()(called fromContentView.task) arms the auto-fire chain (wireAutoFire— provisioningrunPass(hermesBinary:)thenbackup.runPass(), the gate era's exactonEnginePassbody) and awaitsbeginAutomaticCheck();hasStartedpreserves #41's once-per-app-launch, first-window-only rule (⌘N no-ops). No-ops under hosted tests (XCTestConfigurationFilePath— the panes' guard pattern; never probe or auto-provision there). ContentView rendersWorkspaceViewunconditionally — the posts scan starts at first frame, concurrent with the check; nothing library-side waits on the gate. The blocking sheet, placeholder logo screen,gateRaised/gateDismissed, andEngineGateView/ProvisioningFailureCardare deleted. EngineStatusView.swift— the status surfaces (#149 variant A, prototypeprototypes/GatelessStatusPrototype.swift):EngineStatusSurface.visibility(phase:provisioningFailed:)(pure, test-pinned — the mapping: idle/pass+healthy → hidden, checking → pulse, fail/pass+provisioning-failed → failed),EngineStatusPill(44×44 rail slot above Archive: 8pt pulsing accent dot while checking,exclamationmark.triangle.fillon an accent-12% wash when failed, nothing when healthy — the slot collapses and rail spacing closes),EngineStatusCard(the anchored fail card: 340pt, bottom-leading at railWidth+12/bottom 14, surface bg, accent-0.5 border, radius 12, shadow — floats, never blocks, never pushes layout; auto-expands on each failure arrival via WorkspaceView's.onChange(of: visibility), chevron collapses, slot click re-opens; WorkspaceView hosts slot + card overlay — focus mode recesses the CARD with the rail, the expanded state surviving for exit-focus). Engine-fail content = #40 copy with the gateless subtitle ("Passes and Sessions need it — the editor keeps working"), the two install steps + Copy + Installation guide link, Re-check (accent, disabled-while-checking, label "Checking…"), Technical details (stderr excerpt + "Probed: "; bare Probed line when stderr is empty). Provisioning failure rides the same card: title "Setup failed", phase rawValue + failing profile mono (#134), the safe-to-retry body, Retry inline (re-runs provisioning; success nilslastFailureand the surface disappears — live-read, no snapshot).state.jsonlives at~/Library/Application Support/Museion/— schemaVersion 1, wholesale-replaced after every completed check (Re-check included); fail records carry noengineVersion. About (AboutEngineViewinMuseionApp.swift) reads the file and never triggers a check.- Panes spawn the engine the moment the check lands:
MentorPaneView/SessionsPaneViewseed.task(id: binaryPath)(nil→value arrival re-fires; a nil binary never callsopenSession— that path lands the crash card, so the gate's fail state owns the interim). The mentor pane header carries mono-10 engine states beside the serif "Mentor" title (checking… muted + mini spinner / engine missing accent / setup failed accent / #156: ready = the semantic green dot + lowercaseready— the BASE version rides the tooltip, handshake answer first, gate's derived string+-stripped meanwhile; drift note keeps its orange text + help). The session chip renders only once ready; status text wins layout priority. Both panes' idle branches show the honest missing-engine notice when the gate failed (never an eternal "Starting…" spinner — SessionsPaneView takesgatefor it). The header's state derivation isMentorEngineStatus.state(phase:provisioningFailed:)— pure, test-pinned (the outrank rule: engine failure wins over a lingering provisioning failure). - Tests:
MuseionTests/EngineGateTests.swift(untouched — probe order, first-stderr reporting, timeout kill, state records, onPass-fires-per-passing-check, once-per-model) +MuseionTests/GatelessLaunchTests.swift(#151: startLaunchCheck hosted-test no-op, wireAutoFire arms the chain, the pill visibility mapping incl. provisioning-failure-under-passed-gate, the mentor header mapping).
Profile provisioning (S2.1 #43–#48; #134 Profiles S1)
ProfileProvisioner.swift— the #134 surface registry + the provisioner.ProfileSurface(nonisolated enum, chat/pass1/pass2; declaration order = provision order — chat first so the resident surface is healthy before any pass-profile failure stops the loop):profileName(museion adopted in place / museion-pass1 / museion-pass2, Sessions rides Chat per #126),allocatedSkills(#133 table: P1 10 · P2 9 · Chat 11 — #58 adds owned-insight on all three; persona pair never co-occurring),init?(passKind:)(the PassKind→profile seam), and the #132 fresh-seed defaults as constants (defaultModelProvideranthropic,defaultModelIDclaude-sonnet-5-5,outputBudgetTokens24000 — reasoning_effort never written).ProfileProvisioner.perform(nonisolated): one idempotent pass = master-seed + per-surface phases. Phase 0 master: every manifest skill seeded additively as REAL dirs into the ONE master copy at~/Library/Application Support/Museion/skills/(masterRootinjectable) —seed-manifest.txtis still the shipped-set list (kebab-validated at the trust boundary); temp+rename per skill, never touch present ones, orphaned.-temps swept,.DS_Storepurged. Then per surface (first failure wins; the next pass heals): create — dir-check first,hermes profile create <name> --no-alias --no-skillsonly when missing (#43 already-exists semantics);museionis adopted, never re-created (ADR-0014). configure — the #132 defaults written through the engine's own CLI (hermes -p <profile> config set model.provider/model.default/model.extra_body.max_tokens 24000 --force, provider first — switching providers clears a stale inherited base_url, live-probed; #128: never rely on create-time inheritance); success is WIRE-VERIFIED (exit 0+✓ Set <key>on stdout — not exit code alone, finish-audit) and a marker write that fails surfaces as a configure-phase failure (an unrecorded configure must not count as done). MARKER-GATED by.museion-provisionedin the profile dir so a re-pass is a no-op and a user's later Settings change survives: runs for fresh creates and for an unconfigured PASS profile (interrupted before its marker landed — Retry heals); the adopted museion is NEVER configured (its glm-5.3-max is the user's until Settings switches it). skills — per profile, symlink each manifest name into the master: an existing link (live or dangling) is never retargeted; a copy-era REAL dir swaps to a symlink only ontreesByteMatchagainst the MASTER (the link's target — identical to the payload on first seed;.DS_Storefiltered from both listings so a Finder-browsed dir still migrates) with move-aside → link → delete-aside, restored on failure; a diverged dir stays a copy, untracked/user skills never touched (G3a); a missing skill links only when the surface ALLOCATES it (curation). register — museion-tools per profile (ADR-0008 amendment):-p <profile> mcp listskip /mcp addwith repeated-y stdin, both binaries required (nil = test seam).Outcome.seeded(copied:present:)aggregates master copies + links;.failed(profile:phase:excerpt:)names the profile (nil for payload-level failures) — phases create/copy/register/configure.ProvisioningModelunchanged in shape;runPassgainedmasterRoot.- Provisioning failure UX (#48, reborn #151): rides the rail fail card (
EngineStatusCard's setup branch —EngineStatusView.swift) — the blocking-sheetProvisioningFailureCardis deleted; phase rawValue + failing profile name in mono (#134 — with three profiles, "which one?" is the first question; nil profile hides the row), excerpt behind Technical details; Retry re-runs the whole idempotent pass (a success nilslastFailureand the surface disappears; Not-Now defer died with the sheet and the deaddeferFailuremethod is deleted with its test — collapse is view-state, the orange pill stays until a pass succeeds, #38's no-silent-degradation carried by the pill). Provisioning still never hand-writes profile config — mcp registration AND the model defaults both go through the engine's ownhermesCLI (#44 as amended by #23/ADR-0008 and #134/ADR-0014: the provisioner writes no config.yaml bytes itself, but a FRESH pass profile's config.yaml IS legitimately written byconfig set— byte-identity now holds only for adopted/engine-owned configs, test-pinned). - Payload:
ref/writing skills/ships as a folder reference → plainResources/writing skills/directory (no zip, no compiled manifest). 12 mentor skills ship (#58 added owned-insight); the master seeds all 12, each profile symlinks its allocation;ste-writing/writing-for-agentsnever seed. - Tests:
MuseionTests/ProfileProvisionerTests.swift— fake-binary Process harness (fake creates profiles at<binaryDir>/profiles/<name>, speaks-p <any-profile> mcp list/mcp addwith per-profile marker/invocation files andconfig setwith a per-profile argv log +config-set-fails/mcp-add-failsknobs, logs everyprofile create), injected profile/payload/master dirs, manifest ↔ payload correspondence. #134:ProfileSurfaceTests.swift(own file) pins the registry (names/order, PassKind mapping, allocation counts + persona split, defaults, allocation ⊆ bundled manifest), ×3 provisioning with exact config-set command lines, master-once + per-allocation symlinks, re-pass no-op (config-set log byte-stable, no re-creates), adopted-museion untouched, marker heal/no-stomp, failing provision names the profile, configure-phase failure.ProfileSkillMigrationTests.swift(own file) pins the byte-match migration (browsed dir with.DS_Storestill migrates, content identical through the swap; diverged stays a copy; untracked untouched; a symlinked entry inside a copy-era dir refuses the match — never followed, finish-audit). Failure-path tests inProfileProvisionerFailureTests.swift(config.yaml byte-identity through failed/nil-skip/CLI-registering passes, fresh-profile case in its own test, copy-phase catch, path traversal, orphan sweep).
Profile backup (S2.6, #15 map / #50)
ProfileBackup.swift—ProfileBackup(nonisolated): one pass per launch, fired on check pass after the provisioning pass finishes (await chain inAppGateState.wireAutoFire— a failed provision doesn't skip the backup). #134/#129 — one stamp, three subdirs: the sources are the three surface profiles fromProfileSurface.allCases; a missing profile dir is simply absent from the stamp (only NO profile at all →.skippedProfileMissing); NEVER the profiles root (non-Museion profiles are not ours to back up). Any-live-skip-all: every existing profile dir must be idle or the WHOLE stamp skips (one stamp = one consistent point in time) — per-dirgateway.pid(JSON line:pid,hermes_home) pid-liveness viakill(pid, 0)+ theps ax -o command=scan forprofiles/museion/-p museion(already substring-matches the pass profiles;psScaninjectable for tests) →.skippedEngineRunning, one os_log line, no state — the age check governs retry. Age check: newest snapshot (lexicographically sortableyyyyMMdd-HHmmssdir names) older than 24 h. Copy: per profile into<stamp>/<name>/, recursive walk with curated exclusions — dirslogs/,cache/,audio_cache/,image_cache/at any depth; files.DS_Store,models_dev_cache.json(+.etag),provider_models_cache.json,ollama_cloud_models_cache.json,context_length_cache.yaml, suffixes.pid/.sock/.lock; everything else includingauth.json,.env,state.db+-wal/-shmsidecars; dir symlinks resolve (fileExists(isDirectory:)follows) so profile skill symlinks snapshot as content, keeping restores self-contained (#133 folded). 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.mddocuments the three folders (written once into the Backups root). Failure = one os_log line, never an alert; constants fixed in code (retentionCount = 7,snapshotInterval = 24 h).BackupModel(@MainActor @Observable): app-scoped (AppGateState.backup), runs the pass off-main, guards stacking, recordslastOutcome(informational only — no UI).- UI: Help → Open Backup Folder (
OpenBackupFolderButtoninMuseionApp.swift) reveals the Backups root in Finder; restore docs live inRESTORE.mdbeside the snapshots. - Tests:
MuseionTests/ProfileBackupTests.swift— injected roots/clock/psScan (makeProfileFixture(at:name:)builds any profile): liveness branches (live pid / stale pid / ps match), exclusion list + credentials & sidecars present, age check, retention, failure path (unreadable file →.failed, temp swept). #134: one stamp carries all three profile dirs with RESTORE.md naming them, a live PASS-profile pid skips the whole stamp (nothing half-written), missing pass profiles snapshot the rest.
museion-tools MCP server (S2.4, #23)
MCPServer.swift—MCPServer(nonisolated): the binary's second role.MuseionLauncher(@main, this file) branches on--serve-mcp→MCPServer.serve()(headless — never touches AppKit; blocks on stdin lines, exits 0 on EOF) vsMuseionApp.main(). NDJSON JSON-RPC 2.0 on stdio (wire facts live-verified against hermes' MCP client):initialize→ echo the client'sprotocolVersion(client sends2025-11-25) +capabilities {tools}+ serverInfo;notifications/*never answered;tools/list→ the three tools with typed JSON Schemas (the submit schema IS the fix-card schema, ADR-0006 — one schema serves card UI, apply-write, learning promotion; #25: the schema descriptions declare the ranked ≤10 contract and the mechanical-fix-as-exact-replacement semantics, and an over-ceiling submit's reply carriesdropped_over_ceiling— the wire tells the truth about the backstop; #29 (S8.1): the third toolsubmit_research_notesis the candidates rail —{piece_path, notes:[{title, url, quote?, note?}]}, decode-validate ONLY (missing fields fail decode = tool error; empty title/url throw) and reply{"received": N}; NOTHING is written — findings are engine-owned session cargo, the only path to disk is the writer's keep);tools/callresults carrycontent[{type:"text"}]+isError:trueon tool failure;ping→{}; unknown method-32601, unparseable line-32700id null; audit: lines over 1 MB answer-32600"Line too long" (frame cap mirroring the ACP reader side; readLine's own buffering is a commented ceiling), and onejsonStringserializer serves replies and tool payloads; fflush after every stdout line (piped stdout is block-buffered).run(lines:write:)is the testable seam behindserve(). Registration into themuseionprofile happens at provisioning (see above) — ACP sessions then expose the tools asmcp_museion_tools_query_learnings/mcp_museion_tools_submit_fix_cards/mcp_museion_tools_submit_research_notes.FixCardStore.swift—FixCardStore(nonisolated): the durable card store + tool bodies.StoredFixCard(Codable, snake_case, ISO-8601 dates): pattern/problem/diagnosticQuestion/fix, anchor {quote, occurrence (1-based), context?}, lane mechanical|demonstration, emitter lint|engine, provenance {piece, date?, engine?, pass?} (pass= the finding pass number — optional, pre-schema cards decode to nil; the palette renders "pass N" in the card meta; #23 follow-up), status "open", anchorStatus valid|stale — the ADR-0006 fields verbatim.submit(piecePath:cards:)— piece resolves to post.md (dir or file path; audit guard: the file form must BEpost.mdunder aprojects/|archive/component — any readable file passing as a "piece" made submit a JSON-drop beside it and the anchor check a substring oracle over it; one resolvePostURL guard closed both security MEDIUMs), raw text loaded once; anchor validation = exact substring, non-overlapping occurrence count vs 1-based occurrence, stale → the card still lands flagged (never rejected — the finding survives for the writer; malformed input/vanished piece → thrown error = tool error, the trust boundary); writes<piece>/cards/<yyyyMMdd-HHmmss>-<PostStore.slug(pattern)>.json(collision-2/-3), no dedup (v1 decision — the writer skips repeats); #6 audit: a symlinkedcards/dir refuses before any write (promote's learnings posture — the native lint auto-fires submit on every Run Pass, closing the arbitrary-directory JSON-drop the engine-only rail left theoretical). #25 (S3.2/S3.3): the pass ceiling (passCardCeiling= 10 per submit — the attention-budget backstop; the persona's own cap is the primary filter; the ranked HEAD is kept, tail cards drop before validation) +rankstamped 1-based in submit order (optional — pre-#25 cards decode nil);StoredFixCard.Statusenum (open | applied | skipped | done — CONTEXT.md terminals; foreign status strings fail decode → scan's junk-skip);appliedText(of:in:)— the pure mechanical Apply (nth non-overlapping quote occurrence → fix; nil for demonstration lanes or unresolvable anchors — the loud no-match, never a wrong-span patch, ADR-0006; the caller owns the ask + write);close(pieceURL:id:status:anchorStatus:)— the in-place status flip in the card's own JSON file, every other field untouched (Skip records nothing); a non-nilanchorStatusrides the rewrite (apply's stale path flags the card), nil preserves.scan(pieceURL:)sorts submittedAt DESC → rank ASC (nil ranks last — pre-#25 cards) → filename DESC (same-second tiebreak), skips junk.learnings(piecePath:)— home/type derivation extracted into privatehomeAndType+ publiclearningsDir(home:type:)shared with promote, reads<home>/learnings/<type>s/(literal plural, PRD S4.3) returning raw markdown per file — the consult rail (query_learnings serves exactly these files). #26 (S4.1/S4.3) promote:promotedAt: Date?on StoredFixCard (snake_casepromoted_at; pre-#26 cards decode nil) — the explicit-confirm stamp;promote(pieceURL:card:now:)rejects a symlinked learnings component before any write (security audit: a pre-plantedlearnings/postslink must not become a file-plant primitive), then consults the ON-DISK card as the truth — not-found or already-stamped throws BEFORE anything is written (one confirm = one entry, never a counter; a stale palette copy cannot double-write), resolves home/type from the piece, writes ONE plain markdown Learning<learningsDir>/<yyyyMMdd>-<PostStore.slug(pattern)>.md(collision -2/-3 viauniqueFile(ext:)), then rewrites the card JSON in place withpromotedAt(close()'s pattern; learning-first ordering is deliberate — the inverse would lock re-promotion forever);learningMarkdownis the pinned file shape — the TEACHING text, never the instance: flat single-line frontmatter (pattern/problem/diagnostic_question?/fix-for-demonstration-lanes-only/lane/emitter/piece?/pass?/engine?/promoted yyyy-MM-dd/from_card uuid; newlines flatten to spaces; the anchor + mechanical replacement stay on the card JSON — a Learning informs, it never gets applied) + readable body (# pattern, Problem/Diagnostic lines,**Example.**for demonstrations, italic provenance footer omitting missing parts). #27 (S4.2):learnings(piecePath:)filters DECAYED learnings — the consult rail (query_learnings) serves only visible ones:LearningDecay.passesHidden(Post.frontmatter(of:), currentPass:) == nil, the clock fromLearningDecay.passCounts(home:)underLearningDecay.passKey(type);formatted(_:_:)is internal (LearningDecay's dismiss date stamp shares it).LearningDecay.swift— #27 (S4.2; own file — FixCardStore sits at its type-body ceiling): Dismiss & Decay, nonisolated. The pass clock is<home>/learnings/pass-counts.json(flat {typeDir: completed-pass count}; keys = the LITERAL plural dir names viapassKey(_:)— one place so writer and readers can't drift):passCounts(home:)reads leniently (missing/corrupt → empty, non-integers dropped; values clamp into [0, 1e9] — a hostile hand-edit can't trap the arithmetic),recordPass(home:type:)ticks atomically (.sortedKeys; a symlinkedlearnings/refuses — promote's posture, so the per-pass tick can never write outside the Home's tree).isClocked(_:)names the dirs that carry a clock — only the content-type plurals (recordPassticks exactly those); a foreign dir (a hand-madeessays/) is pane-visible but its clock reads 0 forever, so a dismiss there would hide permanently — the store refuses and the pane offers no button.passesHidden(_:currentPass:)is the ONE pure visibility verdict the consult rail, the pane rows, and the dismiss stamp ride: nil = visible, positive = passes until resurface; interval = (resurface_after??baseInterval10) doubled per re-dismiss (doubling capped at 30 — a hand-editeddismiss_count9999 can't overflow Int), garbagedismiss_countdefaults 1 when an anchor exists, a missing/garbage anchor means VISIBLE (a malformed dismiss never permanently hides a Learning).dismiss(home:typeDir:file:)stamps decay state IN the Learning's own frontmatter —dismissed(yyyy-MM-dd),dismiss_count(+1, clamped first),dismissed_at_pass(the type's current clock) — throughstampingFrontmatter(mergedFrontmatter's line-walk generalized to ordered pairs, ponytail-marked — extraction would grow PostStore at its ceiling; no block → fresh block prepended; every other line verbatim — leading hand-edit lines above the block included, #27-review-pinned), behind write-path guards (traversal/hidden names refuse; symlinked learnings components OR learning file refuse — a planted file link must not become a copy-into-the-consult-tree primitive; a foreign unclocked type dir refuses; a currently-HIDDEN Learning refuses — re-dismiss means AFTER the resurface, CONTEXT.md, which also makes a double-click's second stamp harmless; promote's posture throughout).- Tests:
MuseionTests/MCPToolsTests.swift(anchor matrix incl. occurrence 3-of-2 → stale, empty quote → stale; submit round-trip + snake_case keys; scan ordering + junk skip; learnings per type + missing dir → empty) andMuseionTests/MCPServerWireTests.swift(in-processrun(lines:write:): initialize echo, silent notifications, all three tools listed with required arrays — #29 research schema pins piece_path+notes / title+url — full submit round-trip through the wire, isError path, -32601/-32700; #29: a well-formedsubmit_research_notesround-trip replies{"received": N}and lands NOTHING on disk, a note missingtitleanswers isError).
ACP bridge (S2.2, #14 map)
ACPEngineClient.swift—ACPEngineClient(nonisolated, @unchecked Sendable): hand-rolled thin NDJSON JSON-RPC stdio client forhermes acp -p museion(#137:init(binaryPath:profile:)— defaultmuseionfor chat, pass engines pass their own profile; ponytail: no Swift SDK exists; revisit if one appears). Wire facts baked in (verified adapter 0.21.5 + acp SDK): one JSON message per\nline, stdout = wire, stderr = logs (never parsed for state);session/newrequiresmcpServers(list; Museion sends[]— the #44 no-MCP-servers invariant on the wire);session/cancelis a notification (no response); responses camelCase; updates discriminate onupdate.sessionUpdate.JSONValue(nonisolated enum) is the decoded-wire value type. Serial queue confines all mutable state; requests time out (15 s default) — a hung engine surfaces as an error → restart prompt, never an eternal await; server→client requests get an auto-32601(M0 handles none — the deny option); crash/EOF fail pending requests and fireonCrashexactly once (latched — child-exit and stdout-EOF both arrive for one crash; never on explicitclose());close()= handlers-off → SIGTERM → 1 s grace → SIGKILL → reap (EngineProbe pattern); SIGPIPE ignored.MentorSessionModel.swift—MentorSessionModel(@MainActor @Observable): engine state machine (idle/starting/ready/crashed;isStreamingBool; #28:.readycarries NO sessionId — session ids live in the roster). Lazy lifecycle: spawns on firstopenSession()(skipped under hosted tests viaXCTestConfigurationFilePath; #28: openSession = spawn + ensure ONE session — the default freeform "Mentor" on first launch, the newest roster entry on relaunch, RESUMED (session/load replays its history — the review fix; a fresh transcript over an engine that knows the session would prompt/fork/compact against unloaded state)), handshakeinitialize→ advisory version compare vs state.json (recordedVersionProviderinjectable; compares base versions — the gate records the derived version (acp --version→0.21.5+2177.g735e426) while the handshake answers the base (agentInfo.version→0.21.5), so raw string equality fabricates drift on every dev install;baseVersion(of:)strips+-build metadata; one os_log line + both versions in the pane, never blocks). #28: the handshake is initialize ONLY — sessions are created separately (newSession/ensureDefaultSession), the bridge is session-agnostic.sendPrompt(#24 seam:@discardableResult, returnsTurnOutcome—.ended(stopReason:)for any completion stopReason incl.refusal,.cancelledforcancelled,.failedon a thrown transport error or the not-ready/streaming guard refusal; the model appends NO extra row on cancel — the orchestrator owns pass wording) streamsagent_message_chunkinto a buffer flushed on turn end; thought lane (#24 dogfood fix):agent_thought_chunkstreams into its ownstreamingThoughtbuffer — a pass's thinking runs to hundreds of lines and conflating it with the critique made one giant blob; it flushes to a collapsed.thoughtrow FIRST (it preceded the message), andrestart()clears both buffers; an optionallabel:renders verbatim as the user row INSTEAD of the raw prompt (pass wire stubs never hit the transcript); #23 dogfood fix:sendPromptsends session/prompt withpromptTimeout(nonisolated, 1800 s), NOT the client's 15 s request default — the prompt response arrives when the TURN ends, minutes into a pass; the default abandoned live turns ("connection lost" while the engine kept working, Stop vanished withisStreaming; test-pinnedpromptTimeout >= 600); tool calls with fix-card-shapedrawInput(pattern+problem minimum) render asFixCard(ADR-0006 fields; audit: the parser takes the nestedsubmit_fix_cardsargument shape first —{piece_path, cards:[…]}, snake_case, anchor as{quote,occurrence}object — the LIVE rail; the flat #14-era shape stays as fallback; the old flat-only parser never matched the real tool); every other update type a collapsible raw-JSON row. Audit hardening: a prompt response missingstopReasonmaps to.failed(a turn without stopReason never advances a pass), andsendPromptguards the client instead of force-unwrapping. Cancel =session/cancelnotification, Stop button. Crash keeps transcript + last prompt; Restart re-spawns.clientRefmirror exists solely so nonisolated deinit can close the child. #28 (S2.3) session lifecycle: the model hosts MULTIPLE engine-owned sessions on the ONE bridge. Transcripts are per-session structs keyed by wire sessionId;rows/streamingText/streamingThoughtare same-named computed proxies over the ACTIVE session (every existing caller compiles unchanged).SessionEntry(nonisolated, Codable:sessionId/name/pieceTitle/createdAt) +SessionRoster(nonisolated; JSON array at~/Library/Application Support/Museion/sessions.json,rosterDirectoryinjectable —init(binaryPath:rosterDirectory:); an injected-nil dir under hosted tests redirects to a unique temp dir so suites never touch the real roster; EngineGate's silent-fail write posture). The roster persists NAMES ONLY — id/name/pieceTitle/createdAt (the "name/convention" of PRD S2.7); transcripts are engine-owned (ADR-0007: swap the engine, transcripts stay behind), replayed on demand. API:newSession(name:pieceTitle:)(wire session/new, rostered newest-first, activated),resumeSession(_)(wire session/load — the adapter replays full history assession/updateBEFORE responding; user turns arrive asuser_message_chunkand RENDER on replay, live-turn echoes stay ignored; #30 dogfood: the REAL 0.21.5 load response carries NO top-levelsessionId— the id rides_meta.hermes.sessionProvenance.acpSessionId, so extraction accepts both shapes and empty-everywhere alone means the engine doesn't know it →false+ an honest row, entry stays rostered — never a fabricated empty session; the top-level-only read made every real-engine resume fail as "unknown"),forkActiveSession()(wire session/fork → " (fork)", pieceTitle carried, fresh transcript; the adapter's empty-string sessionId = refusal),compactActiveSession()(the/compressslash prompt over the existing sendPrompt rail, label "Compact…" — the raw command never renders; refused while streaming),beginBrainstormSession(pieceTitle:)(#30: the brainstorm flavor — a "Brainstorm" rostered session whose first turn isbrainstormPrompt, the normal prompt rail, no new machinery; pinned: roster head + labeled opener + raw prompt absent + reply streams into ITS transcript),draftCandidateText()/draftCandidateText(in:)(#30: the New-Post-from-Session candidate — the LAST "Mentor: " text row, prefix stripped; user/thought/card/research/raw rows never prefill, blank bodies skipped, and the refusal/connection-shaped rows sharing the display prefix are excluded — ponytail-marked until SessionRow carries speaker identity),canStartSession(ready && !isStreaming — the pane's enable-flag),transcriptRows(of:)(internal — read any transcript without activating). Notification routing files updates under the PARAMS' sessionId (multi-session safe), not the active one; notification→MainActor hops rideDispatchQueue.main.async, NOTTask { @MainActor }— the unstructured-Task hops starved behind parallel test work (replay updates landed seconds late or never) and only the main queue gives FIFO ordering with the continuation resume, making the adapter's replay-before-response contract guaranteed rather than probabilistic. #29 (S8.1–S8.3) research candidates:ResearchCandidate(nonisolated: piecePath/title/url/quote/note +Dispositionpending|kept(fileName)|rejected) ridesSessionRow.Content.researchNote—appendToolCallroutes on PAYLOAD SHAPE (a top-levelnotesarray) BEFORE the fix-card parse — titles are display text, never a routing key, and a research payload with stray pattern/problem keys must not vanish into a card row — then parses viaResearchCandidate.batch(one candidate PER note; missing piece_path/empty notes/note missing title-url or whitespace-only title/url — the wire's trim rule, both boundaries agree — → [] → the raw row owns it, all-or-nothing per batch), so candidates live in the transcript = engine-owned cargo: resume replays the tool calls and re-materializes them (dispositions reset — honest, they were never persisted).setResearchDisposition(rowID:_:)flips the ACTIVE session's row in place (unknown id = no-op).isWritingRowkeeps.researchNotevisible in the writing voice. #137 (S4, ADR-0014) per-surface engine lifecycle: passes run on their OWN one-shot engines —runPass(kind:stub:pieceTitle:)spawnsACPEngineClient(binaryPath:, profile: ProfileSurface(passKind:))(museion-passN), streams the verdict into a TRANSIENT unrostered transcript underpassTranscriptKey("pass", the active entry lives only for the run — #129: passes are never rostered;handleNotificationmaps the pass wire sid onto the key), and tears the engine down at the verdict (teardownPassEngine; onCrash deliberately nil — a pass-engine crash lands the honest failure row, never the crash card; KNOWN EDGE, accepted v1: a chat-engine crash mid-pass flips the pane while the pass completes underneath). #122: the spawn/session/new/teardown block is ONE private rail —runOneShot(profile:name:prompt:pieceTitle:)— shared byrunPassandrunBlindRead(prompt:pieceTitle:reveal:)(the Blind Read rides the CHAT profilemuseion: context-free = a fresh session, not a different judge — decision #120; the reveal row appends only on.endedwith stopReason ≠ "refusal" — a refusal still ends .ended, and a 2×-document prompt makes length refusals realistic — after the turn-end flush, so the mapping can never leak to the judge).name("Pass 1"/"Blind Read") composes the label; the rail's failure rows speak\(label) failedso a Blind Read spawn failure never reads "Pass failed". The turn pipeline is ONEturnCore(client:wireSid:key:prompt:label:)shared by sendPrompt and the pass run (label row, session/prompt, stopReason mapping, buffer flush);sendPromptrefuses the pass surface with a visible row (read-only transcript). Restart posture:restart()(crash button) andrequestRestart()(model-change, Settings fires it) sharerespawn()— teardown, fresh spawn, resume the PRE-restart active rostered session (not blindly the newest);requestRestartdefers to turn end whileisStreaming(pendingRestart, fired from both turn-end defers — a reply is never cut mid-stream) and ignores .idle/.starting (a future spawn reads fresh config).stopStreamingroutessession/cancelto the PASS engine while a pass runs. Internal test observables:passEngineChildPid,isPassEngineRunning. Run Pass readiness (#137 acceptance 3, slice B):PassReadiness(ready | missingKey(providerLabel) | unknown) per kind, stored in the class body (passReadiness;passReadinessWriter= injectable read seam, nil → ad-hocHermesSettingsWriterover the gate's binary, no binaryPath → stays empty);refreshPassReadiness()reads both pass profiles' providers in ONE task group, then each DISTINCT provider's key — an unreadable surface maps.unknown(never block on our own read failure).PostsModel.runPassguards.missingKeyBEFORE the open-piece guard:lastErrornames the provider and nothing touches disk, not even the pre-pass snapshot.MentorPaneView.swift— the debug pane (post #28 no longer the only session surface — Sessions pane shares the transcript renderer): header (#156 contract.pane-head: serif-15/600 "Mentor" title (icon + "Session" died, settled #5) + engine status + mono-10 muted-0.75 session chip — checking… / engine missing / setup failed unchanged (#151); ready = the semantic green dot (DesignTokens.readyGreen, the sole palette exception) + lowercase monoready, base version in the tooltip, orange drift note still visible when gate and handshake disagree; gate's phase machine the source, chip only once ready, status text wins layout priority; #155: the Debug toggle moved to the shared composer's trailing edge (debugBinding— mono-10 lowercase text toggle; the header keeps title + engine status + session chip) —@AppStorage("mentorDebugRows"), off by default: the writing-session transcript filters to prose + card events viaisWritingRow(static, test-pinned); raw session/tool rows, collapsed thinking, and live thinking render only when checked — the model keeps every row either way, so the toggle flips with history intact), transcript — #28: rendered by the sharedSessionTranscriptView(model:showsDebugRows:)(own file); MentorPaneView passes the debug binding (text rows, fix-card tool calls as one-lineFixCardEventRows — pattern title only, the detail lives in the palette; RawUpdateRow disclosure; #24 dogfood fix:defaultScrollAnchor(.bottom)— programmaticscrollToraced the growing lazy rows and mislanded at the TOP;.thoughtrows render as collapsedThinkingBlocks (the engine's thinking — kept out of the critique text; live thinking mounts the block open, spinner toggle, #155)), composer — #155: restyled per contract inside the shared surface (the pane's own freeform-input/liveness row died with the #30 move; liveness is the floating chip, Stop is the Send slot), crash card (#156.state-card: accent tri — danger = terracotta, no second hue — serif-14/600 head, sans-12 muted body, Restart as the solid-accentMonoButton; last prompt mono-11 muted, stderr tail behind Technical details; crash card lives in the file-scopeprivate extension MentorPaneView— type_body_length posture; the idle/starting interim is the same quiet mono voice, and the missing-engine card already spoke it). #24 (S3.1) → #156: the segmented Pass 1 | Pass 2 | Chat picker is DEAD (settled #4 — chat is not a mode; the bar always carries, transcript + composer always present, the pass's streamed critique renders in the same transcript).PassBarView(private, owns@State kind: PassKind) per the #154 contract: the compact selector — Pass 1 / Pass 2 text tabs, mono-10 uppercase tracked, active = fg ink + 2pt accent underline — then thePASS N · STATEstatus line (mono-10 uppercase tracked, the open piece's Pass State, library's post-meta voice), the sans-11 muted cost line (PassContext.estimateTokens"· ~N tokens" or "Open a post to run a pass."), then the actions asMonoButton(private, #156.btn: mono-11, h 28, radius 6, three looks — accent solid / surface+border / accent outline; #155 sendButton precedent, hand-drawn fills — borderedProminent carries the system tint): Cancel (outline, only whileposts.runningPassstreams or (#122)posts.runningBlindRead— one Cancel rail ends either run) ↔ #122: Blind Read (secondary, beside Run — disabled with the reason in help: no open post,!posts.openPieceHasSnapshot("run a Pass first"), or the engine can't take the turn; one click firesposts.blindRead; help otherwise names it advisory-only, records nothing) ↔ Run Pass N (solid accent; disabled with no open piece, engine not ready, mid-turn, or (#137) the pass profile's provider is unkeyed — a mono-11Missing <provider> key —line under the actions carries a borderless accent Open Settings button (onOpenSettings, threaded MentorPaneView→PostsPaneView→WorkspaceView'sselection = .settings, ArchivePaneView closure precedent), the disabled Run's help names the reason, and.unknownnever disables (the spawn's honest failure owns that path). The header's session chip hides while the transient pass transcript (passTranscriptKey) owns the active surface, and the pane's.task(id: binaryPath)runsrefreshPassReadiness()before the hosted-test guard — #151: keyed on the nil→value arrival so the engine spawns the moment the gateless check lands (a nil binary never calls openSession); re-fires re-run it, so a key added in Settings re-enables Run Pass.gate: AppGateState?(#151 header states) +posts: PostsModel?+home: URL?params (nil = previews); PostsPaneView's mentor column passes all three. #23 follow-up (dogfood): card detail lives in the Fix Cards palette — a floatingWindowscene (idfix-cards,FixCardsPaletteinFixCardsWindow.swift,defaultSize340×540) beside About, opened viaopenWindowfrom a mono "Fix Cards · N" row below the pass bar (shown only when cards exist; #156 ruling: a plain mono row — no card, no hairline of its own, a link not content). The palette shows the open piece's title +posts.openPieceCards— #25 (S3.2/S3.3): the card WORK surface, open cards first (scan order preserved: newest pass first, rank ascending), closed cards dimmed at 0.45 with their status in the meta and no actions; row actions per lane: mechanical + valid → Apply + Skip, demonstration → Done + Skip (never Apply, ADR-0006), stale anchor → Skip only; Apply = ask-before, a BLOCKING sheet showing the exact edit (anchored quote → replacement, "(cut)" when the fix is empty) with Apply/Cancel — .stale swaps the sheet to the stale alert (no retry), .refused shows the reason inline; no apply-all, no batch, the sheet is the only path from Apply to a write (S3.3); meta carries#rank, "apply · ask-before" on appliable mechanical cards, and the footer line "apply = ask-before · one card at a time" (S2.5 trust visibility — nothing auto-applies, so never-do needs no control); stale anchors orange + "· stale anchor"; card meta leads with "pass N" whenprovenance.passis stamped and re-contextualizes via@Observableas the open piece changes (audit: the card scan runs detached off MainActor — typing re-triggers rescan; PostsModel.title(of:)+ EditorSession.passPieceURL/hasResearchare the shared facts runPass, the pass bar, and the palette ride — three hand-copies deduped); paintedDesignTokens.background— app chrome warm, matching the rail, not document white. The transcript's live tool-call rendering isFixCardEventRow— the pattern title alone, one line; the verdict prose carries no card detail (pass-persona v1.2: the card is the finding's only full statement). #26 (S4.1): every card row gains Promote (bordered, small) between the primary action and Skip on open cards, alone on closed unpromoted cards — it outlives the card because the Learning is the durable artifact (the design contract's promote-resolved buttons); a promoted card shows· promotedin the meta and never re-offers. The ask isPromoteAskSheet(own file, OutlineRowTextView extraction precedent): the contract's #promoteDialog — "Promote to Learnings?", the consulted-on-future-Passes body line (type pluralized, "pieces" fallback), learning preview (pattern/problem/provenance viatitle(of:)), Cancel/Promote; ONE confirm →promoteCard, refusal inline orange with buttons kept (ApplyAskSheet posture). #29 (S8.3): the transcript renders.researchNoteas full candidate cards (NOT one-line events — a handful of notes curates in place, no palette): serif-13 title, mono-11 muted url, selectable note, muted-italic quote; pending offers Keep + Reject (mono-11 bordered; hidden when the pane'shomeis nil — previews), kept/rejected dim 0.45 (closed-card voice) with metakept · research/<file>/rejected; the Mentor pane passes itshome, the Sessions pane gainshome: URL?(WorkspaceView handsgate.museionHome). Keep = ask-before (G9):ResearchKeepSheet(own file, PromoteAskSheet posture — "Keep this research note?", the nothing-saves-until-you-keep line, note preview, Cancel/Keep; ONE confirm →PostStore.writeResearchNote→ disposition flips, refusal inline orange with buttons kept). Reject = no confirm (Dismiss-button voice — vanishes, nothing recorded). The sheet state lives in SessionTranscriptView (pendingKeep,.sheet(item:)over the transcript — never inside a lazy row).- Wiring:
AppGateState.mentoris the app-scoped model ( #151: PostsPaneView's mentor column passesgate.gateModel.currentBinaryPathasbinaryPath; the pane re-seedsmentor.binaryPathon the nil→value arrival — no re-probe); quit teardown onNSApplication.willTerminateNotification→mentor.shutdown()(idempotent; scenePhase.inactivewould fire on plain focus loss). - Tests:
MuseionTests/ACPClientTests.swift— fake ACP server (zsh speaking real NDJSON over the real Process path; mode file + base64 card payload beside the binary, self-locating per ProfileProvisionerTests convention). Covers handshake version, streamed updates + fix-card parse (model over the real client+fake path), advisory drift note, crash → onCrash exactly once, cancel fire-and-forget, teardown kills hung child.
Work Guidance
- Native SwiftUI only on the editing side — no web-editor embedding, no Electron-style components (ADR-0001; reading-mode WKWebView is allowed per ADR-0011: reading is presentation).
- Text editing gets built on TextKit 2 / SwiftUI directly; no CodeEdit/CodeMirror/ProseMirror-class editing dependencies.
Verification
xcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' buildxcodebuild -project Museion.xcodeproj -scheme Museion -destination 'platform=macOS' test
Child DOX Index
- None yet — add child docs when subdirectories with distinct responsibilities appear (e.g. editor, library, agent integration).