From efad422e036ad2476e5b1b0fcecd9a64ef1ec069 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 7 Nov 2026 21:13:31 +0100 Subject: [PATCH] =?UTF-8?q?fix(ui):=20finish-audit=20fixes=20=E2=80=94=20b?= =?UTF-8?q?lank=20search=20glyph,=20quadratic=20truncation,=20scope-rail?= =?UTF-8?q?=20refusal=20leak?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three-reviewer audit of the polish overhaul: - magnifyinglass -> magnifyingglass (blank SF Symbol, all 3 seats) - WordBoundaryTruncation.fit measures each word once (O(n^2) -> O(n) on pathological imported titles; live-title pins unchanged) - scopeHostedSession defers behind an in-flight replay instead of refusing (automatic actions never leak a 'Resume refused' row); replay completion re-fires the pending scope — pinned over the real client path with loadReplayHold, flip-verified - transcript ForEach on stable row ids, not indices - delete dead softBorder param; fold caretPastLeadingBlanks onto firstContentLocation; native TextField prompt for the search field - ElidedPathText.candidates/elide nonisolated (off-actor first(where:) trapped the host); new pins: degenerate truncation shapes, firstContentLocation, elide ladder --- Museion/AGENTS.md | 4 +- Museion/MentorSessionModel.swift | 12 +++++ Museion/PostEditorView.swift | 12 +---- Museion/PostsPaneView.swift | 29 ++++------- Museion/ProsePresenter.swift | 17 ++----- Museion/SessionTranscriptView.swift | 4 +- Museion/SessionsPaneView.swift | 25 ++++++--- Museion/SettingsPaneView.swift | 4 +- Museion/WorkspaceView.swift | 6 +-- MuseionTests/AGENTS.md | 2 +- MuseionTests/PolishSeamTests.swift | 47 +++++++++++++++++ MuseionTests/SessionScopeTests.swift | 51 +++++++++++++++++++ .../WordBoundaryTruncationTests.swift | 15 +++++- 13 files changed, 163 insertions(+), 65 deletions(-) create mode 100644 MuseionTests/PolishSeamTests.swift diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 852ae55..2c89efa 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -21,7 +21,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## 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 constructors `valkyrie`/`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 exception `readyGreen` (#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. `RailButton` (44×44, muted icon, hover wash, surface tile + hairline border when current, icon in fg ink — **ui-polish r2 re-ruling:** NO visible edge bar; the export's `::before` selection bar paints BEHIND the app border in the export's own render, so contract-faithful is tile + border + fg-ink icon alone). **#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 \" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`; **owner ruling 2026-11-07 — scoped hosting:** the Mentor pane hosts the open piece's matching roster session (`SessionRoster.hostedSessionId` — exact pieceTitle match, newest first; `MentorPaneView` scopes at mount/remount and on every piece change via `scopeHostedSession`), shows its honest empty presentation when none matches, and never interrupts an in-flight pass transcript or streaming turn — the switch defers to stream end), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s card language, ui-polish r6: selected strip = vertically-inset 2pt rounded accent capsule — part of the card, never a full-height pasted strip; titles truncation-seamed `WordBoundaryTruncation.fit(maxWidth:lines:)`, GLYPH-MEASURED (NSFont serif-13 semibold vs the row's 192pt width, pinned in WordBoundaryTruncationTests) so the seam's output is what renders and lineLimit(2) is a no-op safety net — ui-polish r7 (argon#14/sol#32/47): an overflowing title MIDDLE-elides — **ui-polish r8 (sol#3) HEAD-BIASED ~60/40: the head keeps the "Pass N ·" label + leading words grown into ~60% of the glyph budget (`headShare`), then the longest fitting word SUFFIX — more of the unique topic, less of the shared tail ("Pass 2 · Museion Handoff — … apex) vs. Hand-rolled TextKit"); r7's label-only head + maximal suffix let the topic die at the same elision point**: serif-13 name + mono-11 meta `pieceTitle · 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 shared `SessionTranscriptView` (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, ui-polish r8 mercury#17: the engine-version mono badge sits BESIDE the trailing button group — title | spacer | badge | buttons, never beside the title; **#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 from `draftCandidateText()`, the `NewPostFromSessionSheet` (own file, ui-polish r1 — extracted past the 400-line ceiling; internal) prefills 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 `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from 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 in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved 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, contract `ref/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 — `linkVerdict` gates the surface's `openURL` environment, 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; ui-polish r1: `speaker(of:)` also routes engine operational notices ("Operation interrupted: …") there, and replayed pass kick-offs render FIRST LINE ONLY via `statusDisplayText` — the full dispatch prompt never reaches the UI; the transcript column caps at a 720pt reading measure, centered); 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 `.thinMaterial` liveness 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 via `debugBinding: Binding?` (nil = no toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (ui-polish r2: category heads in the library's pass-state voice — tracked UPPERCASE mono-10 micro-labels, category-break gap ≥ 2× the 4pt entry spacing; entries ~14pt semibold titles; content bounded to a left-anchored ~720pt reading column) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate 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):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init 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) and `scan` reads `LearningDecay.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.85 (r6 contrast final: receding chrome never sits below 0.85 — the 0.45/0.6 dims died) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation 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 via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#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 (ui-polish r2: group labels in the library's pass-state micro voice — tracked UPPERCASE mono-10 — stepping DOWN below the pane title, Unarchive a ~36pt `BorderedSecondaryButtonStyle` hit target at the group header row's TRAILING edge inside the column → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with a #E8E5DF hairline under each child and Move Back to `` + Rename…, content bounded to a left-anchored ~720pt reading column (the transcript's measure language; **r6 D24 FINAL**: one left axis at x14, chevron slot 16pt + label x30 (6-8pt gap), entry cards x44 on the shared library ladder, hairlines + pill bounded 14→706 — final, no more oscillation), row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#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 when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). +- `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. `RailButton` (44×44, muted icon, hover wash, surface tile + hairline border when current, icon in fg ink — **ui-polish r2 re-ruling:** NO visible edge bar; the export's `::before` selection bar paints BEHIND the app border in the export's own render, so contract-faithful is tile + border + fg-ink icon alone). **#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 \" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`; **owner ruling 2026-11-07 — scoped hosting:** the Mentor pane hosts the open piece's matching roster session (`SessionRoster.hostedSessionId` — exact pieceTitle match, newest first; `MentorPaneView` scopes at mount/remount and on every piece change via `scopeHostedSession`), shows its honest empty presentation when none matches, and never interrupts an in-flight pass transcript, streaming turn, or another session's in-flight replay — the switch defers to turn/replay end and the replay's completion re-fires the pending scope; an automatic action never leaks a refusal row), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s card language, ui-polish r6: selected strip = vertically-inset 2pt rounded accent capsule — part of the card, never a full-height pasted strip; titles truncation-seamed `WordBoundaryTruncation.fit(maxWidth:lines:)`, GLYPH-MEASURED (NSFont serif-13 semibold vs the row's 192pt width, pinned in WordBoundaryTruncationTests) so the seam's output is what renders and lineLimit(2) is a no-op safety net — ui-polish r7 (argon#14/sol#32/47): an overflowing title MIDDLE-elides — **ui-polish r8 (sol#3) HEAD-BIASED ~60/40: the head keeps the "Pass N ·" label + leading words grown into ~60% of the glyph budget (`headShare`), then the longest fitting word SUFFIX — more of the unique topic, less of the shared tail ("Pass 2 · Museion Handoff — … apex) vs. Hand-rolled TextKit"); r7's label-only head + maximal suffix let the topic die at the same elision point**: serif-13 name + mono-11 meta `pieceTitle · 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 shared `SessionTranscriptView` (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, ui-polish r8 mercury#17: the engine-version mono badge sits BESIDE the trailing button group — title | spacer | badge | buttons, never beside the title; **#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 from `draftCandidateText()`, the `NewPostFromSessionSheet` (own file, ui-polish r1 — extracted past the 400-line ceiling; internal) prefills 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 `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from 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 in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved 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, contract `ref/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 — `linkVerdict` gates the surface's `openURL` environment, 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; ui-polish r1: `speaker(of:)` also routes engine operational notices ("Operation interrupted: …") there, and replayed pass kick-offs render FIRST LINE ONLY via `statusDisplayText` — the full dispatch prompt never reaches the UI; the transcript column caps at a 720pt reading measure, centered); 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 `.thinMaterial` liveness 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 via `debugBinding: Binding?` (nil = no toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (ui-polish r2: category heads in the library's pass-state voice — tracked UPPERCASE mono-10 micro-labels, category-break gap ≥ 2× the 4pt entry spacing; entries ~14pt semibold titles; content bounded to a left-anchored ~720pt reading column) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate 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):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init 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) and `scan` reads `LearningDecay.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.85 (r6 contrast final: receding chrome never sits below 0.85 — the 0.45/0.6 dims died) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation 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 via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#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 (ui-polish r2: group labels in the library's pass-state micro voice — tracked UPPERCASE mono-10 — stepping DOWN below the pane title, Unarchive a ~36pt `BorderedSecondaryButtonStyle` hit target at the group header row's TRAILING edge inside the column → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with a #E8E5DF hairline under each child and Move Back to `` + Rename…, content bounded to a left-anchored ~720pt reading column (the transcript's measure language; **r6 D24 FINAL**: one left axis at x14, chevron slot 16pt + label x30 (6-8pt gap), entry cards x44 on the shared library ladder, hairlines + pill bounded 14→706 — final, no more oscillation), row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#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 when `lossy`; 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 + origin-only meta — the pass state rides the group label; the row's a11y label still states it), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (11px mono at full muted ink; **r6 indent ladder** — chevron slot x14 / head text x30 / group labels + row CARDS x44 with title text x56, so every level starts at or right of the one above it and the search field's box shares the row card's insets exactly), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · 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; `RenamePostSheet` internal 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 through `PostStore.readBody`, so frontmatter is never searched), flat results with title matches first (Finder order preserved in both halves, count line above, same `LibraryPostRow`); 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 passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`). **#162:** the focused branch mounts the Cold Turkey chrome as overlays (`ColdTurkeySeat` bottom-center, `ColdTurkeyDot` bottom-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 + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, 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, and `stats_*` 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 optional `PostScanCache` (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):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(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, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(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 stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(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; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind 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-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.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) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — 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 through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also 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 to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (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 from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (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 of `Post.frontmatter`. **#33 (S6.1):** `stampMicropubURL(id:url:home:)` — in-place `micropub_url` stamp through `stampingFrontmatter` (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's `assets/` and returns the ref destination; type gate = #34's `Micropub.mimeType` set (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-shaped `assets/` refuses (`hostileAssets` — never write through it, the rail would refuse the send anyway); base name through the shared `slug` (parser-clean: the #34 regex never matches space-bearing destinations, so ref and file agree at ingest), collisions suffix `-2`/`-3` within `assets/`; `illustrationRef(_:)` is the one `![alt](assets/…)` builder the drop surface and tests share. @@ -40,7 +40,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `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; `keyDown` intercepts 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); `sizeThatFits` floors 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.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump 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); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - 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 with `ProsePresenter.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 (`Fold` keyed 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 via `ProseTypography.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:** a `shouldChangeText` override records the last accepted single-line edit (range + UTF-16 delta, `pendingPlainEdit`); `refreshFolds` routes 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, no `setAttributedString` swap. 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()` nulls `pendingPlainEdit` outright — structural edits reshape blocks even when the replacement is single-line (a childless unterminated block's outdent; finish-audit pin, `performOutdent` internal 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. `Fold` carries the hidden `scope` (shift-maintained; the full pass re-derives it). **Chrome rendering (#115 field findings, #142 rework):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render as one TINY per-glyph CALayer (contents = a small flipped NSImage raster, `isGeometryFlipped` on the overlay layer so sublayer frames speak lineRect's top-left y) in the click-through `ProseChromeView` overlay (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 from `firstRect(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 `.dropDestination`s STARVE every deeper drag destination — an NSTextView registered for `.fileURL` never received one callback, and a nested editor-level SwiftUI destination never fired either, while `WorkspaceView`'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 through `openExternal` (#91's open-as-guest preserved), everything else bridges through `ProseDropBridge` (app-scoped on `AppGateState.proseDrop`, weak live-text-view handle, set in ProseTextView make/updateNSView, non-optional at both constructor call sites) into `ProseListTextView.ingestDrop(_:)`: gates = non-nil `ingestFolder` (saved posts only — drafts/guests get the strip) + every file publishable (#34's `Micropub.mimeType` set; mixed md+image refuses too), then copies each URL via `PostStore.ingestImage` and inserts the joined `illustrationRef`s at the drop point. The source must be a PLAIN file — a dropped symlink refuses (`IngestError.isLink`: `copyItem` would 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 ride `FixCardStore.uniqueFile` (`-2`/`-3`, the research-note helper — no bespoke loop). Drop-point mapping (the hard-won part, #115's family): the SwiftUI closure's `location` is UNUSABLE under this hosting; the pointer's screen position (`NSEvent.mouseLocation`) maps to an index via `firstRect(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), so `dropIndex(length:targetY:bandMinY:bandMaxY:rectY:)` — a `nonisolated static` PURE 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). `alt` selected (offset +2, length 3) and scrolled to, with `CaretCentering.syncTypewriterInset` re-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 transient `showIngestNotice` strip (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" in the P1/P2 uppercase-badge voice; selected row = fg-ink 0.10 wash (one step over the 0.06 hover) + accent bar inset from the highlight edge; header title inset 18 shares the sidebar labels' edge; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded; ui-polish r2: the MUSEION HOME row is ONE bounded field-group (surface fill + 1pt #E8E5DF hairline) — the path expands to fill the available width before eliding (r6: `ElidedPathText` — glyph-measured slash-boundary ladder, full path first then dropping middle components down to `/first/…/last`, each candidate measured in the real mono face against the actual row width, longest fit renders, character-middle only if even the shortest overflows; full-strength hairline on Choose… inside the group — the softBorder halving died), Choose… adjacent at 8pt in the `BorderedSecondaryButtonStyle` (WorkspaceView.swift — mono-11 on surface + hairline, 36pt hit target by default, 28 in compact rows); all detail forms are LEFT-anchored per wf130 `.vC .detail` padding 18/26/48, never HORIZONTALLY centered in the pane; r6: every page pins a serif-15 header at top 17 — baseline-aligned with the sidebar's 'Settings' across the divider — and TOP-ALIGNS its form stack ~24pt under the intro with NO ScrollView - ui-polish r8 owner-reported fix: the r6 vertical-centering left a ~320px dead gap and a phantom scrollbar; one leading control column, every control label-above at the page title's x). `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; **#175:** the nous block carries the Portal note — chats ride the hermes Portal login, a pasted key bills the same account credits, `hermes auth add nous` signs in). `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), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and 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.json` load, memoized via `loadedDefault`) 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 (**#175 adds `nous` — Nous Portal: endpoint `https://inference-api.nousresearch.com/v1`, env `NOUS_API_KEY`, switch flagship `anthropic/claude-sonnet-5` keeping the app's sonnet posture — the portal's catalog is the vendor-prefixed router list, live-probed; ladder = the 5-level OpenAI-compatible set hermes clamps nous to; engine auth rides the hermes Portal login, API key and subscription bill the same account credits), `ZaiKeyType` endpoint 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's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + 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 (`testStates` drives the Provider Keys page; the empty-key precondition fails fast off the network; **#175:** an unkeyed NOUS test falls back to `PortalAuth.sessionKey` — the shared `~/.hermes/auth.json` device-code agent_key read off-main, the engine's own nous credential — and names `hermes auth add nous` when neither key nor login exists; **the fallback fires only on the official https endpoint** — a hand-edited nous endpoint with an empty key refuses pre-network ("paste an API key"): the implicit session credential never rides a user-set URL, cleartext http included; `probeTransport`/`portalAuthPath` are injectable init params so the fallback tests run offline), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its 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 (injectable `writeDebounce`, 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 in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset ` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **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 pure `upsertEnv`; a value containing a line break/NUL is REFUSED at the shared sink before any file is touched (2026-10-28 audit fix: a pasted `key\nOTHER_VAR=x` is an env-file injection — the error rides `lastWriteError`); an `NSLock` serializes 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 `.env` alone — the field sets, never removes; the zai `model.base_url` write-through rides only the profiles on zai — `profiles` is that target list, not the .env list), `readSurface` hydrates via `config get` ×4 (provider/model/effort/base_url) and `readProviderKey` reads each provider's var back (first non-empty across the three `.env` files) so a restart neither blanks the key fields nor refuses Test Connection; all blocking work hops off-main inside `Task.detached`; secrets never ride argv and never reach `lastWriteError`; `hermesBinary` nil (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 1 `GET /models` (key validity + reachability; z.ai proves nothing about key-type pairing — §1.2), step 2 a minimal STREAMING chat call — **every request carries `Content-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_tokens` required) authing via `x-api-key` + pinned `anthropic-version` 2023-06-01, never Bearer; **nous (#175, live-probed 2026-11-05) speaks PLAIN OpenAI chat-completions** (`{endpoint}/chat/completions`, `messages` + the 512 cap, NO thinking knobs — the portal is a router: `/models` answers ~385 vendor-prefixed ids) with Bearer auth — a pasted key OR the shared Portal session's agent_key both work; error decode falls back to a bare root `message` (the portal's `{status, message}` envelope carries no error object — a bad model id answers 404 + message, and `Hermes-4.3-36B`-style docs ids 404: the catalog is the router list, so the switch flagship is `anthropic/claude-sonnet-5`); 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 — zai `error.code` 1113 → wrongKeyType, 401s → authFailed (Anthropic detail carries `request_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 under `response.error`); `works` carries latency + model count (the reply payload died in the 2026-10-28 audit — no consumer); the `Transport` closure 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 gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480. **#137 (S4):** `SettingsModel.onChatSurfaceWrite` fires after a SUCCESSFUL chat-surface write ONLY (never pass surfaces — their engines are one-shot — never key writes, never failures); `SettingsPaneView` takes the closure and WorkspaceView wires it to `gate.mentor.requestRestart()`, so a committed Chat model change restarts the resident engine in place (deferred to turn end while streaming, slice A's API). +- 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" in the P1/P2 uppercase-badge voice; selected row = fg-ink 0.10 wash (one step over the 0.06 hover) + accent bar inset from the highlight edge; header title inset 18 shares the sidebar labels' edge; **#136:** the pane takes `binaryPath` — the gate's winner — builds the model over `HermesSettingsWriter`, and `.task { await model.hydrate() }` reads the live profile state at pane open). Content page = the #17 Home control (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded; ui-polish r2: the MUSEION HOME row is ONE bounded field-group (surface fill + 1pt #E8E5DF hairline) — the path expands to fill the available width before eliding (r6: `ElidedPathText` — glyph-measured slash-boundary ladder, full path first then dropping middle components down to `/first/…/last`, each candidate measured in the real mono face against the actual row width, longest fit renders, character-middle only if even the shortest overflows; full-strength hairline on Choose… inside the group — the softBorder param died with it), Choose… adjacent at 8pt in the `BorderedSecondaryButtonStyle` (WorkspaceView.swift — mono-11 on surface + hairline, 36pt hit target by default, 28 in compact rows); all detail forms are LEFT-anchored per wf130 `.vC .detail` padding 18/26/48, never HORIZONTALLY centered in the pane; r6: every page pins a serif-15 header at top 17 — baseline-aligned with the sidebar's 'Settings' across the divider — and TOP-ALIGNS its form stack ~24pt under the intro with NO ScrollView - ui-polish r8 owner-reported fix: the r6 vertical-centering left a ~320px dead gap and a phantom scrollbar; one leading control column, every control label-above at the page title's x). `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; **#175:** the nous block carries the Portal note — chats ride the hermes Portal login, a pasted key bills the same account credits, `hermes auth add nous` signs in). `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), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and 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.json` load, memoized via `loadedDefault`) 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 (**#175 adds `nous` — Nous Portal: endpoint `https://inference-api.nousresearch.com/v1`, env `NOUS_API_KEY`, switch flagship `anthropic/claude-sonnet-5` keeping the app's sonnet posture — the portal's catalog is the vendor-prefixed router list, live-probed; ladder = the 5-level OpenAI-compatible set hermes clamps nous to; engine auth rides the hermes Portal login, API key and subscription bill the same account credits), `ZaiKeyType` endpoint 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's `readSurface` CLI rail (unknown provider slugs stay seeded — never stomped; a zai base_url on the coding endpoint infers `zaiKeyType` + 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 (`testStates` drives the Provider Keys page; the empty-key precondition fails fast off the network; **#175:** an unkeyed NOUS test falls back to `PortalAuth.sessionKey` — the shared `~/.hermes/auth.json` device-code agent_key read off-main, the engine's own nous credential — and names `hermes auth add nous` when neither key nor login exists; **the fallback fires only on the official https endpoint** — a hand-edited nous endpoint with an empty key refuses pre-network ("paste an API key"): the implicit session credential never rides a user-set URL, cleartext http included; `probeTransport`/`portalAuthPath` are injectable init params so the fallback tests run offline), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its 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 (injectable `writeDebounce`, 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 in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset ` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **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 pure `upsertEnv`; a value containing a line break/NUL is REFUSED at the shared sink before any file is touched (2026-10-28 audit fix: a pasted `key\nOTHER_VAR=x` is an env-file injection — the error rides `lastWriteError`); an `NSLock` serializes 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 `.env` alone — the field sets, never removes; the zai `model.base_url` write-through rides only the profiles on zai — `profiles` is that target list, not the .env list), `readSurface` hydrates via `config get` ×4 (provider/model/effort/base_url) and `readProviderKey` reads each provider's var back (first non-empty across the three `.env` files) so a restart neither blanks the key fields nor refuses Test Connection; all blocking work hops off-main inside `Task.detached`; secrets never ride argv and never reach `lastWriteError`; `hermesBinary` nil (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 1 `GET /models` (key validity + reachability; z.ai proves nothing about key-type pairing — §1.2), step 2 a minimal STREAMING chat call — **every request carries `Content-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_tokens` required) authing via `x-api-key` + pinned `anthropic-version` 2023-06-01, never Bearer; **nous (#175, live-probed 2026-11-05) speaks PLAIN OpenAI chat-completions** (`{endpoint}/chat/completions`, `messages` + the 512 cap, NO thinking knobs — the portal is a router: `/models` answers ~385 vendor-prefixed ids) with Bearer auth — a pasted key OR the shared Portal session's agent_key both work; error decode falls back to a bare root `message` (the portal's `{status, message}` envelope carries no error object — a bad model id answers 404 + message, and `Hermes-4.3-36B`-style docs ids 404: the catalog is the router list, so the switch flagship is `anthropic/claude-sonnet-5`); 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 — zai `error.code` 1113 → wrongKeyType, 401s → authFailed (Anthropic detail carries `request_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 under `response.error`); `works` carries latency + model count (the reply payload died in the 2026-10-28 audit — no consumer); the `Transport` closure 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 gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480. **#137 (S4):** `SettingsModel.onChatSurfaceWrite` fires after a SUCCESSFUL chat-surface write ONLY (never pass surfaces — their engines are one-shot — never key writes, never failures); `SettingsPaneView` takes the closure and WorkspaceView wires it to `gate.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 via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. **#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) and `ColdTurkeyDot` (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 `.cancelAction` button (the PostEditorView ⌘S rail — `.onExitCommand` never 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 full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir ]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one
    , killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `
    ` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView` (ui-polish r1: the document title — first non-blank body line — renders at the 22pt title rung in the SERIF body face (#ui-r2: face change only, Valkyrie not the sans heading face; after-space measured so the title→body ink gap is 24–28pt, editor top padding 40pt), list lines hang at their marker-prefix width MEASURED IN THE EXACT RENDER ATTRIBUTES (#ui-r2: markers render in the body face at foreground-0.8 ink — the r1 mono-render/body-measure drift put continuations ~4pt left), and programmatic caret landings hop past leading blank lines via `caretPastLeadingBlanks` — the r1 stray-caret artifact was the caret parked in an invisible leading blank fragment), toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
     - `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`; 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/Museion` exists as a directory (`existingDirectory` gate — a stray plain file is not a Home and falls through) → pin it (existing Homes migrate manually, never silently), (3) `/Museion` when iCloud Drive is present (CloudDocs resolved dynamically at the unprefixed `Library/Mobile Documents/com~apple~CloudDocs` path — never a hard-coded `iCloud~` 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 in `HomeResolution.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: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
    diff --git a/Museion/MentorSessionModel.swift b/Museion/MentorSessionModel.swift
    index 8c4fe76..73ecde7 100644
    --- a/Museion/MentorSessionModel.swift
    +++ b/Museion/MentorSessionModel.swift
    @@ -551,6 +551,9 @@ final class MentorSessionModel {
     				timeout: Self.promptTimeout,
     			)
     			replayingSessionId = nil
    +			// Finish-audit: the replay slot is free — a scope switch that
    +			// deferred BEHIND this replay applies now.
    +			firePendingScopeIfRequested()
     			// The real adapter (0.21.5, live-verified #30 dogfood) answers
     			// session/load WITHOUT a top-level sessionId — the id rides
     			// `_meta.hermes.sessionProvenance.acpSessionId`. The fake's
    @@ -585,6 +588,7 @@ final class MentorSessionModel {
     			return true
     		} catch {
     			replayingSessionId = nil
    +			firePendingScopeIfRequested()
     			// Partial replay rows (if any) + the failure row stay in the
     			// ENTRY's store — attributed, visible on its next row click.
     			appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId)
    @@ -609,6 +613,14 @@ final class MentorSessionModel {
     			pendingScopePieceTitle = pieceTitle
     			return
     		}
    +		// Finish-audit: a replay in flight defers the switch too — the
    +		// scope rail is an AUTOMATIC action and must never leak a
    +		// "Resume refused" row into the transcript (the replay's
    +		// completion re-fires the pending scope).
    +		guard replayingSessionId == nil else {
    +			pendingScopePieceTitle = pieceTitle
    +			return
    +		}
     		pendingScopePieceTitle = nil
     		let target = SessionRoster.hostedSessionId(forOpenPieceTitle: pieceTitle, in: roster)
     		guard activeEntry?.sessionId != target else { return }
    diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift
    index e75f949..c04349d 100644
    --- a/Museion/PostEditorView.swift
    +++ b/Museion/PostEditorView.swift
    @@ -424,17 +424,7 @@ struct ProseTextView: NSViewRepresentable {
     	/// over leading blanks to the first content line; interactive
     	/// placements (click, drag, typing) never route through here.
     	static func caretPastLeadingBlanks(_ location: Int, in text: String) -> Int {
    -		let buffer = text as NSString
    -		var lineStart = 0
    -		while lineStart < buffer.length {
    -			let line = buffer.lineRange(for: NSRange(location: lineStart, length: 0))
    -			let lineText = buffer.substring(with: line)
    -			if !lineText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
    -				return location < line.location ? line.location : location
    -			}
    -			lineStart = NSMaxRange(line)
    -		}
    -		return location
    +		max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location)
     	}
     
     	func makeNSView(context: Context) -> NSScrollView {
    diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift
    index de280ef..4eb1f83 100644
    --- a/Museion/PostsPaneView.swift
    +++ b/Museion/PostsPaneView.swift
    @@ -409,32 +409,23 @@ struct PostsLibraryColumn: View {
     
     	/// #144 + mercury#54 (r4): a real field surface — surface fill + hairline
     	/// border on the column's chrome, taller than a text row; the placeholder
    -	/// renders in the palette's muted ink via the under-Text trick (stronger
    -	/// than the system's faint default — it reads as an input, not sidebar
    -	/// text). r5 (argon#44, mercury#52, sol#37): the insertion caret tints
    +	/// r5 (argon#44, mercury#52, sol#37): the insertion caret tints
     	/// terracotta (.tint on the field), and the small magnifier glyph sits at
    -	/// the field's leading edge (icon→text spacing rides the HStack's 6pt).
    +	/// the field's leading edge (icon→text spacing rides the HStack's 6pt);
    +	/// the placeholder is the native prompt wearing the palette's muted ink
    +	/// (the composer's pattern).
     	/// r8 (argon#6, mercury#12): focus draws a QUIET 1pt ring — accent at 0.6,
     	/// present but never the strongest saturation on screen.
     	private var searchField: some View {
     		HStack(spacing: 6) {
    -			Image(systemName: "magnifyinglass")
    +			Image(systemName: "magnifyingglass")
     				.font(.system(size: 11))
     				.foregroundStyle(DesignTokens.muted)
    -			ZStack(alignment: .leading) {
    -				if query.isEmpty {
    -					Text("Search posts")
    -						.font(.system(size: 12))
    -						.foregroundStyle(DesignTokens.muted)
    -						.allowsHitTesting(false)
    -				}
    -				TextField("", text: $query)
    -					.textFieldStyle(.plain)
    -					.font(.system(size: 12))
    -					.focused($searchFocused)
    -					.tint(DesignTokens.accent)
    -					.accessibilityLabel("Search posts")
    -			}
    +			TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted))
    +				.textFieldStyle(.plain)
    +				.font(.system(size: 12))
    +				.focused($searchFocused)
    +				.tint(DesignTokens.accent)
     			if isSearching {
     				Button {
     					query = ""
    diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift
    index 804c325..be824ff 100644
    --- a/Museion/ProsePresenter.swift
    +++ b/Museion/ProsePresenter.swift
    @@ -486,20 +486,9 @@ nonisolated extension ProsePresenter {
     		var lineStart = 0
     		while lineStart < nsText.length {
     			let line = nsText.lineRange(for: NSRange(location: lineStart, length: 0))
    -			var len = line.length
    -			while len > 0 {
    -				let char = nsText.character(at: line.location + len - 1)
    -				if char == 0x0A || char == 0x0D {
    -					len -= 1
    -				} else {
    -					break
    -				}
    -			}
    -			if len > 0 {
    -				let text = nsText.substring(with: NSRange(location: line.location, length: len))
    -				if !text.trimmingCharacters(in: .whitespaces).isEmpty {
    -					return line.location
    -				}
    +			let lineText = nsText.substring(with: line)
    +			if !lineText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
    +				return line.location
     			}
     			lineStart = NSMaxRange(line)
     		}
    diff --git a/Museion/SessionTranscriptView.swift b/Museion/SessionTranscriptView.swift
    index 6d46423..c3f0030 100644
    --- a/Museion/SessionTranscriptView.swift
    +++ b/Museion/SessionTranscriptView.swift
    @@ -130,8 +130,8 @@ struct SessionTranscriptView: View {
     			// PREDECESSOR in reach — the warning-styling and gap rules
     			// below are pairwise, not per-row.
     			LazyVStack(alignment: .leading, spacing: 18) {
    -				ForEach(visible.indices, id: \.self) { index in
    -					rowView(visible[index], previous: index > 0 ? visible[index - 1] : nil)
    +				ForEach(Array(visible.enumerated()), id: \.element.id) { pair in
    +					rowView(pair.element, previous: pair.offset > 0 ? visible[pair.offset - 1] : nil)
     				}
     				if showsDebugRows, !model.streamingThought.isEmpty {
     					// Live thinking: open while it runs (spinner toggle),
    diff --git a/Museion/SessionsPaneView.swift b/Museion/SessionsPaneView.swift
    index 9c4b98a..10ff600 100644
    --- a/Museion/SessionsPaneView.swift
    +++ b/Museion/SessionsPaneView.swift
    @@ -522,7 +522,14 @@ nonisolated enum WordBoundaryTruncation {
     	/// (lineLimit catches it).
     	static func fit(_ text: String, maxWidth: CGFloat, lines: Int = 2) -> String {
     		let words = text.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
    -		guard !words.isEmpty, lineCount(words, maxWidth) > lines else { return text }
    +		guard !words.isEmpty else { return text }
    +		// Finish-audit: measure each word ONCE — a pathological title (an
    +		// imported post's first line is unbounded) must not turn the
    +		// candidate loop into quadratic glyph measurement on the main actor.
    +		// ponytail: one pass per word is fine to ~10k words; bail to native
    +		// lineLimit if a roster row ever renders slower than a frame.
    +		let widths = words.map { width($0) }
    +		guard lineCount(widths, maxWidth) > lines else { return text }
     		var head = [words[0]]
     		if words.count > 2, words[2] == "·" {
     			head = [words[0], words[1], words[2]]
    @@ -537,22 +544,24 @@ nonisolated enum WordBoundaryTruncation {
     			index += 1
     		}
     		let tail = Array(words.dropFirst(head.count))
    +		let ellipsis = width("…")
    +		let headWidths = Array(widths[0 ..< head.count])
     		for count in stride(from: tail.count, through: 1, by: -1) {
    -			let candidate = head.joined(separator: " ") + " … " + tail.suffix(count).joined(separator: " ")
    -			if lineCount(candidate.split(separator: " ").map(String.init), maxWidth) <= lines {
    -				return candidate
    +			let candidateWidths = headWidths + [ellipsis] + Array(widths[(words.count - count)...])
    +			if lineCount(candidateWidths, maxWidth) <= lines {
    +				return head.joined(separator: " ") + " … " + tail.suffix(count).joined(separator: " ")
     			}
     		}
     		return head.joined(separator: " ") + "…"
     	}
     
     	/// Greedy word wrap (the text system's own algorithm): how many
    -	/// lines `words` need at `maxWidth`.
    -	private static func lineCount(_ words: [String], _ maxWidth: CGFloat) -> Int {
    +	/// lines `widths` (per-word glyph widths, measured once) need at
    +	/// `maxWidth`.
    +	private static func lineCount(_ widths: [CGFloat], _ maxWidth: CGFloat) -> Int {
     		var lines = 1
     		var used: CGFloat = 0
    -		for word in words {
    -			let tokenWidth = width(word)
    +		for tokenWidth in widths {
     			if used == 0 {
     				// A word wider than the line keeps its own line — the
     				// mid-word break is SwiftUI's, never the seam's.
    diff --git a/Museion/SettingsPaneView.swift b/Museion/SettingsPaneView.swift
    index b2b4623..70c98a7 100644
    --- a/Museion/SettingsPaneView.swift
    +++ b/Museion/SettingsPaneView.swift
    @@ -328,7 +328,7 @@ struct ElidedPathText: View {
     
     	/// The candidate ladder, longest first: the full path, then each
     	/// shorter variant with one more leading component kept whole.
    -	static func candidates(_ path: String) -> [String] {
    +	nonisolated static func candidates(_ path: String) -> [String] {
     		let comps = path.split(separator: "/").map(String.init)
     		guard comps.count > 2 else { return [path] }
     		var ladder = [path]
    @@ -339,7 +339,7 @@ struct ElidedPathText: View {
     	}
     
     	/// The longest candidate whose glyph-measured width fits `width`.
    -	static func elide(_ path: String, into width: CGFloat) -> String {
    +	nonisolated static func elide(_ path: String, into width: CGFloat) -> String {
     		let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
     		func fits(_ candidate: String) -> Bool {
     			(candidate as NSString).size(withAttributes: [.font: font]).width <= width
    diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift
    index 577f752..698a1f0 100644
    --- a/Museion/WorkspaceView.swift
    +++ b/Museion/WorkspaceView.swift
    @@ -774,12 +774,8 @@ struct SelectedRowStrip: View {
     /// surface fill with a #E8E5DF hairline (Archive's Unarchive, Settings'
     /// Choose…). 36pt tall by default — a real hit target, not a text-size
     /// pill; pass a smaller `minHeight` where the row is compact.
    -/// r5 (argon#21): `softBorder` halves the hairline's opacity for the one
    -/// placement that sits INSIDE a field group (Choose…) — a full-strength
    -/// stroke there read as a double border.
     struct BorderedSecondaryButtonStyle: ButtonStyle {
     	var minHeight: CGFloat = 36
    -	var softBorder: Bool = false
     
     	func makeBody(configuration: Configuration) -> some View {
     		configuration.label
    @@ -792,7 +788,7 @@ struct BorderedSecondaryButtonStyle: ButtonStyle {
     					.fill(DesignTokens.surface)
     					.overlay(
     						RoundedRectangle(cornerRadius: 8)
    -							.strokeBorder(DesignTokens.border.opacity(softBorder ? 0.5 : 1)),
    +							.strokeBorder(DesignTokens.border),
     					),
     			)
     			.opacity(configuration.isPressed ? 0.7 : 1)
    diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md
    index 6a3a089..33847ea 100644
    --- a/MuseionTests/AGENTS.md
    +++ b/MuseionTests/AGENTS.md
    @@ -34,7 +34,7 @@ Owned by the root AGENTS.md contract.
     - `PassRunTests.swift` (#24, S3.1) — the pass orchestration over the REAL client + fake ACP path, via `makePassRig` (temp home + bound `PostsModel` + `MentorSessionModel` over `makeFakeACP`, reusing the now-internal ACPClientTests helpers): end-to-end run (pre-pass snapshot in `passes/pass-1.md`, disk stamp `Pass-1 Done`, label row "Pass 1 · " renders, the wire stub never lands in the transcript, library regroups after the rescan — poll pattern), cancelled (`cancelOnPrompt`) and refused (`refuseOnPrompt`) turns never advance (the snapshot still lands — pre-pass is unconditional), a staged draft refuses with `lastError` and writes nothing, **the full guard matrix (#24 close-out): a second `runPass` while one streams refuses with "already running" and `cancelPass` ends the held turn (state stays First Draft — `hangOnPrompt` holds the turn open; the UI's Cancel rail is exercised directly, the trailing `mentor.shutdown()` a regression bound only), a pass while the mentor streams a chat turn refuses "mid-reply" (nothing on disk — the guard fires before the snapshot), a pass against a never-opened engine refuses "isn't ready"**, a dirty session flushes BEFORE the snapshot (snapshot + disk both carry the edit), and Pass 2 runs straight from First Draft (order-free, monotonic). **#124:** the Cancel rail individually pinned — `cancelling a held pass ends the turn cancelled with no advance` (the cancel-acknowledging fake answers the held prompt, bounded polls, no teardown assist — the pin fails if `cancelPass`'s body is emptied); every rig test tears down via `defer { mentor.shutdown() }` at rig creation. **#137 flip (per #129):** passes are TRANSIENT and never roster — the #28 roster pin died with per-surface engines; the own-engine/spawn-log/reap pins live in `EngineLifecycleTests.swift` (a PassRunTests duplicate of that pin was deleted in the #137 finish audit), the transient-entry pin in `SessionLifecycleTests.swift`; `textRows(of:)` is internal here (the shared-helper convention) for EngineLifecycleTests' rigs. **#31 (S5.1) wiring pins:** a pass on a writer First Draft piece captures the five stats keys AND completes (Pass-1 Done — capture never blocked the pass), a CANCELLED pass (`cancelOnPrompt`) still captured at the invocation with the state untouched, an ai-origin piece runs with NO stats (origin alone decides, never the outcome). **#6 (S3.4) wiring pin** (`DeslopLintWiringTests`, suite member at file tail — the #31/#134 vacuous-filter lesson): a pass invocation on a sloppy piece seeds emitter `lint` cards under `<piece>/cards/` AND the `stats_*` keys — stats capture and lint both fired at the one invocation seam.
     - `BlindReadTests.swift` (#122 — scenario headers at file top, `@Suite` so suite-filters run it) — the Blind Read pins: `BlindRead.prompt` (both bodies inline under "Version A/B" in the given order, flip swaps, NO origin words — snapshot/current/original/revised never appear, the pick+one-line ask) and `reveal` (exact mapping per kind+flip); `PostStore.latestPassSnapshot` (newest mtime wins across pass-1/pass-2 — decisive +60 s attribute set, the write-order race is real; none → nil); the advisory run over `makeBlindRig` (makeModelHome + `makeFakeACP` + the fake's DIR — makePassRig doesn't expose it): the mentor rail (fresh `acp -p museion` spawn counted in the spawn log — the resident engine is the only other `museion` spawn, pass profiles never; label row "Blind Read · <title>"; reveal lands ONLY on `.ended`, `cancelOnPrompt` leaves none; roster never grows) and the model orchestration (`blindRead`: prompt-log carries both bodies and no path; `pass_state` stays First Draft — records nothing; `runningBlindRead` clears; no-snapshot → `lastError` "run a Pass first" with nothing spawned beyond the resident engine; snapshot == current → "No edits since" refusal). **Finish-audit pins:** a REFUSED read (`refuseOnPrompt`) ends `.ended(stopReason: "refusal")` and reveals nothing (the gate is the stopReason, never the outcome — a refusal still ends .ended; flip-verified), and a held read (`hangOnPrompt`) owns the rail — a concurrent pass refuses "already running", `cancelPass` ends the turn with no reveal and `pass_state` untouched.
     - `DeslopLintTests.swift` (#6, S3.4 — scenario header at file top, all tests `@Suite` members) — the native deslop lint pins: the exact finding set AND rank order over a known sloppy draft (em-dash first, Tier 1 by first-match position, Tier 2 after; exact owner-facing problem/diagnostic copy, mixed-case anchor preservation `Utilize` with its exact-substring occurrence, mechanical lane for the mapped `utilize`→`use`, demonstration for `delve`, counts inside the problem strings, NO finding for within-allowance `furthermore`), whole-word boundaries (`delved`/`harnessed`/`showcased` never fire their stems), em-dash at budget 4 → silent (0 too), the empty AND whitespace-phrase trust-boundary pin (#6 audit: the `— —` body is space-phrase bait — a plain body passes vacuously; submit's validation trims, so a whitespace phrase would kill the whole submit), the config story (Home override wins when it exists AND decodes, malformed override falls back to the bundled default, `home: nil` → bundled, `bundledConfig()` decodes the two tiers + budget 4 + the mapped replacements), and the store-level emit loop over `PostStore.writeNew` (cards land emitter `lint`/open/pass 1/valid anchors, re-emit dedups against OPEN cards, a `.skipped` close re-emits its still-present finding).
    -- `SessionScopeTests.swift` (owner ruling 2026-11-07 — scoped mentor hosting) — the pure seam pin: `SessionRoster.hostedSessionId(forOpenPieceTitle:in:)` = the NEWEST exact `pieceTitle` match over the newest-first roster; near-misses, no open piece, or an empty roster → nil (the pane's honest empty presentation). The pane/model rails (`MentorPaneView.scopeToOpenPiece`, `scopeHostedSession` + the stream-end deferral) are engine-path behavior — the seam is what's pinned here.
    +- `SessionScopeTests.swift` (owner ruling 2026-11-07 — scoped mentor hosting) — the pure seam pin: `SessionRoster.hostedSessionId(forOpenPieceTitle:in:)` = the NEWEST exact `pieceTitle` match over the newest-first roster; near-misses, no open piece, or an empty roster → nil (the pane's honest empty presentation). The pane/model rails (`MentorPaneView.scopeToOpenPiece`, `scopeHostedSession` + the stream-end deferral) are engine-path behavior — the seam is what's pinned here. Finish-audit (2026-11-07) added the deferral's model-level pin over the REAL client path: `loadReplayHold` (the fake parks session/load after a `hold-load` stderr line) parks a replay of piece A while B's session is active; `scopeHostedSession` to A then DEFERS — no `Resume refused` row in `model.rows`, `activeEntry` unchanged (flip-verified) — the parked child dies with teardown, the resume task is never awaited. Same audit: `WordBoundaryTruncationTests` gained degenerate passthrough pins (whitespace-only, space-free CJK one-word, single long word); `PolishSeamTests.swift` (new) pins `ProsePresenter.firstContentLocation` (leading-blank skip / nil on all-blank) and `ElidedPathText.candidates`/`elide` (both `nonisolated` statics since 2026-11-07 — a MainActor-isolated static called off-actor through stdlib `first(where:)` traps the host app at runtime, the compile is clean).
     - `WordBoundaryTruncationTests.swift` (round-5 ui-polish → round-6 glyph-measured → round-7 middle-eliding → round-8 head-biased ~60/40 split, sol#3 — the roster title's pure truncation seam in SessionsPaneView.swift: NSFont serif-13 semibold measured against the 192pt two-line width) — short-string passthrough, the native mid-word cut ("Markdo…") landing at a word edge ("Markdown…"), and the exact strings for the two live Handoff roster titles ("Pass N · Museion Handoff — … apex) vs. Hand-rolled TextKit") — the head keeps the pass label + leading words into ~60% of the glyph budget (`headShare`), the longest fitting suffix the rest. The round-6 warning-row headline/detail split (`SessionTranscriptView.warningParts`) + the round-8 calm-copy seam (`SessionTranscriptView.calmDetail` — the engine's "waiting for model response (X elapsed)" renders "waiting on the model — X", everything else verbatim) are pinned in ACPClientTests beside the other transcript seams.
     - `SessionLifecycleTests.swift` (#28, S2.3) — the session-lifecycle scenarios over the real client + fake ACP path (`loadReplay` mode, injectable `rosterDirectory` temp dirs): pass streams into a TRANSIENT unrostered transcript (#137 flip — roster unchanged, the transient entry owns the active surface, entry name "Pass 1 · \<title\>"), freeform new (pieceTitle nil = free-floating; non-nil carries the name), resume replays engine-owned history in wire order WITH user turns rendered (the live-echo ignore does not apply on replay), engine-unknown resume → `false` + honest row + entry stays rostered (never a fabricated empty session), fork ("<name> (fork)", pieceTitle carried, original untouched, empty-string wire id refused), compact (the `/compress` label turn, raw command never renders), and roster persistence round-trip (a fresh model instance over the same directory restores entries — never transcripts); plus `new-session choice reads Posts' open piece` (the pane's `openPiece(in:)` — nil posts / nothing open / open piece). **#30:** the draft-candidate pins over hand-built rows (no engine — the pure `draftCandidateText(in:)` seam): the LAST "Mentor: " text row wins across user/thought/card/research/raw lanes, empty and user-only transcripts yield nil, a trailing blank mentor row doesn't blank the prefill while an earlier real reply exists, and the refusal/connection-shaped rows sharing the display prefix never prefill (an error is not the draft). **#30 audit pins:** `brainstorm opens a rostered session with the labeled opener` (roster head "Brainstorm", piece-associated, the labeled opener renders and the raw prompt never does, the reply streams into ITS transcript) and `resume accepts the legacy top-level sessionId shape` (the `loadReplayLegacy` knob; the dual-shape resume read's second branch — flip-verified: removing the provenance fallback fails the provenance-shape pins, this pin guards the other). `ResearchCandidateTests.swift` (#29, own file — SessionLifecycleTests crossed its type-body ceiling; MCPToolsPromoteTests precedent) holds the research-candidate pins over the same shared fake: the fake's `loadReplay` mode streams one `submit_research_notes` `tool_call` (base64 payload; the research line reuses the fix-card line's exact quoting), and a `strayResearchOnPrompt` mode (ACPClientTests) streams a research batch carrying stray `pattern`/`problem` keys; pins — `ResearchCandidate.batch` (two notes → two candidates with `""` defaults; no piece_path / empty notes / note missing url / whitespace-only title or url → []), resume re-materializes the candidates from the replay (the AC pin — engine-owned cargo), `setResearchDisposition` flips the active session's rows and no-ops unknown ids, `isWritingRow` keeps `.researchNote` in the writing voice, and the stray-key payload renders CANDIDATES, never a card (routing is by the notes-array shape, before the fix-card parse — titles are display text, not a routing key).
     - `EngineLifecycleTests.swift` (#137, Profiles S4 — scenario headers at file top) — the per-surface engine lifecycle over the shared helpers via a local rig (`makeModelHome` + `makeFakeACP` keeping the fake's DIR — the spawn log beside the fake is the which-engine-ran observable): **A1** a pass run lives on its own engine end-to-end (spawn log carries `acp -p museion-pass1` beside the chat engine's `acp -p museion`, roster count UNCHANGED, `isPassEngineRunning` false after the verdict, the pass child pid reaped via `kill(pid, 0)`, the chat child still alive, snapshot + Pass-1 Done + label row + streamed verdict on the active surface), cancel of a held pass (hangOnPrompt — pid captured mid-run, Cancel rail ends the turn, state stays First Draft with the snapshot landed, child reaped, roster unchanged), **A2** idle `requestRestart` respawns in place (old pid reaped, new alive, phase back to .ready, the PRE-restart active rostered session resumed + replayed) and the deferred-ordering pin (requestRestart mid-turn holds — same pid while streaming — and the pid swap fires only AFTER `stopStreaming` ends the turn). pid capture rides Task + bounded poll (the pid is only observable while the pass engine runs); reaped checks are bounded polls. **B1 (#137 acceptance 3, scenario header mid-file):** readiness pins over the shared `RecordingWriter` injected as `passReadinessWriter` (keyed provider → `.ready`, unkeyed z.ai → `.missingKey("z.ai")`, a canned key landing re-enables on the next refresh — the pane-re-entry path — unreadable surfaces → `.unknown`), plus the PostsModel guard pin: an OPEN piece + `.missingKey` → `lastError` names z.ai and `passes/pass-1.md` never lands (the guard fires before the snapshot; the test #requires the piece open so the open-piece guard can't pass it vacuously); the guard's `readiness(for:)` reads `.unknown` as never-blocking). **#137 finish-audit pins:** `a resume completing mid-pass does not steal the pass surface` — `loadReplayHold` parks a session/load, the mode file flips to `hangOnPrompt` BEFORE the pass engine spawns (each child reads the mode at startup) so the pass holds deterministically, `load-go` completes the load mid-hold → the model's ONE post-await `claimActive` gate refuses (resume false, honest row, activeEntry stays the pass key, roster intact) and Cancel still routes to the pass engine; model-side audit fixes it pins against: activation writers (create/resume/fork) route through `claimActive` (post-await ownership re-check), `ensureDefaultSession` early-outs `phase = .ready` when a turn streams, the pass-profile map guards instead of force-unwrapping, and PostsModel's vanish-kill is `watchedHome`-gated (a scan that outlived a Home repoint never kills a session under the new home).
    diff --git a/MuseionTests/PolishSeamTests.swift b/MuseionTests/PolishSeamTests.swift
    new file mode 100644
    index 0000000..2a58a08
    --- /dev/null
    +++ b/MuseionTests/PolishSeamTests.swift
    @@ -0,0 +1,47 @@
    +//
    +//  PolishSeamTests.swift
    +//  MuseionTests
    +//
    +//  Finish-audit pins for the ui-polish loop's pure seams that shipped
    +//  "so a test can pin" them but no pin landed: the editor's
    +//  first-content walker (title detection + the caret hop ride it) and
    +//  the settings path elision ladder.
    +//
    +
    +import Foundation
    +@testable import Museion
    +import Testing
    +
    +@Suite("PolishSeamTests")
    +struct PolishSeamTests {
    +	/// Leading blank lines are skipped to the first CONTENT line; a
    +	/// whitespace-only buffer has none (nil); a buffer with no leading
    +	/// blanks returns 0. The same walker styles the title line and hops
    +	/// programmatic carets past the invisible blank fragment.
    +	@Test func `firstContentLocation skips leading blanks`() {
    +		let plain = "Title\n\nbody" as NSString
    +		#expect(ProsePresenter.firstContentLocation(plain) == 0)
    +		let blankLead = "\n\n  \nTitle\nbody" as NSString
    +		let loc = ProsePresenter.firstContentLocation(blankLead)
    +		#expect(loc == 5) // three leading blank lines (5 UTF-16 units incl. newline) before "Title"
    +		#expect(ProsePresenter.firstContentLocation("" as NSString) == nil)
    +		#expect(ProsePresenter.firstContentLocation("\n \n\t\n" as NSString) == nil)
    +	}
    +
    +	/// The ladder keeps the full path, then each shorter variant with one
    +	/// more leading component kept whole; ≤2 components has nothing to
    +	/// elide. `elide` picks the longest candidate that fits.
    +	@Test func `ElidedPathText candidate ladder and elision`() {
    +		let path = "/Users/alex/Library/Mobile Documents/com~apple~CloudDocs/Museion"
    +		let ladder = ElidedPathText.candidates(path)
    +		#expect(ladder.first == path)
    +		#expect(ladder.last == "/Users/…/Museion")
    +		#expect(ladder.count == path.split(separator: "/").count - 1)
    +		// Short paths never elide.
    +		#expect(ElidedPathText.candidates("/a/b") == ["/a/b"])
    +		// A wide-enough field keeps the full path; a narrow one falls to
    +		// the shortest rung.
    +		#expect(ElidedPathText.elide(path, into: 5000) == path)
    +		#expect(ElidedPathText.elide(path, into: 10) == "/Users/…/Museion")
    +	}
    +}
    diff --git a/MuseionTests/SessionScopeTests.swift b/MuseionTests/SessionScopeTests.swift
    index 9084127..f3e4387 100644
    --- a/MuseionTests/SessionScopeTests.swift
    +++ b/MuseionTests/SessionScopeTests.swift
    @@ -38,4 +38,55 @@ struct SessionScopeTests {
     		// A title with no roster behind it hosts nothing.
     		#expect(SessionRoster.hostedSessionId(forOpenPieceTitle: "Essay X", in: []) == nil)
     	}
    +
    +	/// Finish-audit: the scope rail is an AUTOMATIC action — when the one
    +	/// replay slot is busy (another session's session/load in flight), the
    +	/// switch DEFERS like a stream (old behavior: resumeSession refused and
    +	/// appended a user-visible "Resume refused" row for an action the writer
    +	/// never took). Pinned over the real client path with the fake's
    +	/// `loadReplayHold` mode parking the replay; teardown kills the parked
    +	/// child, so the resume task is deliberately never awaited.
    +	@MainActor
    +	@Test func `scope switch defers behind an in-flight replay without refusing`() async throws {
    +		let dir = acpTempDir("scope-defer")
    +		let fake = makeFakeACP(at: dir, mode: "loadReplayHold")
    +		let model = MentorSessionModel(binaryPath: fake, rosterDirectory: dir)
    +		defer { model.shutdown() }
    +		await model.openSession() // empty roster — creates the default session, completes
    +		guard case .ready = model.phase else {
    +			Issue.record("expected ready, got \(model.phase)")
    +			return
    +		}
    +		// Two rostered pieces through the real flow; B's session is active.
    +		guard await model.newSession(name: "On A", pieceTitle: "Piece A") != nil,
    +		      await model.newSession(name: "On B", pieceTitle: "Piece B") != nil
    +		else {
    +			Issue.record("session creation refused")
    +			return
    +		}
    +		let entryA = try #require(model.roster.first { $0.pieceTitle == "Piece A" })
    +		let activeBefore = model.activeEntry?.sessionId
    +		// Park A's replay behind the hold — the load sits in flight, the
    +		// slot stays taken, and B remains the pane's surface.
    +		_ = Task { await model.resumeSession(entryA) }
    +		var held = false
    +		for _ in 0 ..< 250 where !held {
    +			held = model.stderrTail.contains { $0.contains("hold-load") }
    +			if !held {
    +				try await Task.sleep(nanoseconds: 20_000_000)
    +			}
    +		}
    +		#expect(held)
    +		await model.scopeHostedSession(toOpenPieceTitle: "Piece A")
    +		let refused = model.rows.contains { row in
    +			if case let .text(text) = row.content {
    +				return text.contains("Resume refused")
    +			}
    +			return false
    +		}
    +		#expect(!refused)
    +		// The switch applied nowhere yet — deferred, not refused and not
    +		// swapped behind the replay.
    +		#expect(model.activeEntry?.sessionId == activeBefore)
    +	}
     }
    diff --git a/MuseionTests/WordBoundaryTruncationTests.swift b/MuseionTests/WordBoundaryTruncationTests.swift
    index 003c698..15fe715 100644
    --- a/MuseionTests/WordBoundaryTruncationTests.swift
    +++ b/MuseionTests/WordBoundaryTruncationTests.swift
    @@ -1,6 +1,6 @@
     //
     //  WordBoundaryTruncationTests.swift
    -//  Museion
    +//  MuseionTests
     //
     //  Round-5 (mercury#4/sol#8/argon#16) → Round-6 glyph-measured
     //  (mercury#4/sol#9) → Round-7 middle-eliding (argon#14/sol#32/47) →
    @@ -53,4 +53,17 @@ struct WordBoundaryTruncationTests {
     		#expect(WordBoundaryTruncation.fit(pass1, maxWidth: 192, lines: 2)
     			== "Pass 1 · Museion Handoff — … apex) vs. Hand-rolled TextKit")
     	}
    +
    +	/// Finish-audit edge pins: the seam passes degenerate shapes through
    +	/// untouched — whitespace-only splits to no words, a space-free CJK
    +	/// title is ONE word, and a single word wider than the line keeps its
    +	/// own line (lineLimit(2) renders it). None may crash or mangle.
    +	@Test func `degenerate shapes pass through unchanged`() {
    +		let whitespace = "   "
    +		#expect(WordBoundaryTruncation.fit(whitespace, maxWidth: 192, lines: 2) == whitespace)
    +		let cjk = "静かなウェブの再考" // no spaces — ONE word, wider than the line
    +		#expect(WordBoundaryTruncation.fit(cjk, maxWidth: 40, lines: 2) == cjk)
    +		let singleLongWord = "Supercalifragilisticexpialidocious"
    +		#expect(WordBoundaryTruncation.fit(singleLongWord, maxWidth: 50, lines: 2) == singleLongWord)
    +	}
     }