Merge pull request 'UI polish overhaul' (#176) from agent/ui-polish-overhaul into main
CI / ci (push) Canceled after 0s

This commit was merged in pull request #176.
This commit is contained in:
AlexKucera committed 2026-11-07 21:14:05 +01:00
commit efbde25cdd
22 files changed
+2382 -513

No files matched your search

+1 -1
View File
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
<!-- gitnexus:start --> <!-- gitnexus:start -->
# GitNexus — Code Intelligence # GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (6377 symbols, 27886 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. This project is indexed by GitNexus as **museion** (6415 symbols, 28172 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
+6 -6
View File
@@ -21,28 +21,28 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Workspace shell (M1, #17 + #18 / S1.1) ## 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). - `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` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: 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 + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` 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); 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<Bool>?` (nil = no toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisoLine truncated - `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 \<title\>" 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 sLine truncated
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · 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`). - `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/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#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). - `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/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#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/<project>/` — 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>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) 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 iLine truncated - `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/<project>/` — 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>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) 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 iLine truncated
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`). **#161:** internal `words(in:)` (`tokens(in:).count`) is the one word-count rail — Cold Turkey net-words counts with it, so text metrics can never drift. - `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`). **#161:** internal `words(in:)` (`tokens(in:).count`) is the one word-count rail — Cold Turkey net-words counts with it, so text metrics can never drift.
- `WritingGoal.swift` — #161 (Cold Turkey S1, map #158) the pure goal engine the writing lock consumes (nonisolated, no UI, no clock): `WritingGoal` (`words(Int)` | `minutes(Int)`, one goal per block, fixed at arm) + `WritingGoalRun` (the armed block: goal + `armedAt` + baseline/current word counts via `DraftStats.words`). `update(text:)` takes whole-document text — typing/deleting/pasting/undo all land the same way, `netNewWords` falls out of the delta (deleting costs; a big paste counts). `now` is INJECTED (`isMet(now:)`, `secondsRemaining(now:)`, `progress(now:)` 0…1 clamped) — the countdown cannot pause by construction; minutes deadline is arm+minutes, inclusive boundary; `isMet` is live truth, unlatched (delete below target un-mets — the lock completes on the first true tick). S2's `WritingLockState` owns the ticker and calls this. - `WritingGoal.swift` — #161 (Cold Turkey S1, map #158) the pure goal engine the writing lock consumes (nonisolated, no UI, no clock): `WritingGoal` (`words(Int)` | `minutes(Int)`, one goal per block, fixed at arm) + `WritingGoalRun` (the armed block: goal + `armedAt` + baseline/current word counts via `DraftStats.words`). `update(text:)` takes whole-document text — typing/deleting/pasting/undo all land the same way, `netNewWords` falls out of the delta (deleting costs; a big paste counts). `now` is INJECTED (`isMet(now:)`, `secondsRemaining(now:)`, `progress(now:)` 0…1 clamped) — the countdown cannot pause by construction; minutes deadline is arm+minutes, inclusive boundary; `isMet` is live truth, unlatched (delete below target un-mets — the lock completes on the first true tick). S2's `WritingLockState` owns the ticker and calls this.
- `WritingLockState.swift` — #162 (Cold Turkey S2, map #158) the writing lock machine + kiosk: `WritingLockState` (@Observable, app-scoped as `gate.writingLock`; `static weak active` is the app-delegate's quit-refusal handle) — `start(goal:body:at:)` arms (refuses a second block while locked), a 1 s ticker + the per-keystroke `feed(text:)` (ProseTextView.onTextChange, both editor modes) drive `WritingGoalRun`, `tick(at:)` completes on the first met tick (internal seam — tests inject the decisive moments), `complete()` exits the kiosk and leaves `completionNote` fading ~6 s. `WritingLockKiosk` — the #159 recipe verbatim (6-option combo + `.disableScreenCornerInteractions`), enter = activate→options→toggle (returns whether WE toggled fullscreen — an already-fullscreen window is entered in place; exit replays only what entry toggled), exit = options-clear-FIRST then toggle (never churn mid-transition); ⌘W + ⌃⌘F + ⌘N refusals = a local keyDown monitor (matched by KEY CODE with the exact modifier set plus a lowercased character net — audit 2026-11-04: charactersIgnoringModifiers is layout- and Caps-Lock-dependent, a Cyrillic/caps ⌘W slipped past while the stock Close still fired; ⌘N covers the stock New Window item SwiftUI owns, which stays enabled mid-lock) swallowing all three while locked (⌃⌘F added 2026-11-04: the kiosk holds even windowed, so a user-initiated fullscreen exit mid-block left a windowed kiosk — menu bar gone, quit refused — the dogfood trap; fullscreen now leaves only via completion) (SwiftUI owns the stock window delegate and `.closeItem` has no CommandGroupPlacement — the OutlineDrag monitor pattern, installed/removed with the lock); hosted-test guard = full no-op (never kiosk the test machine). `WritingLockAppDelegate` (`@NSApplicationDelegateAdaptor` in MuseionApp) — `applicationShouldTerminate` while locked asks ONCE (#163 ruling 2026-11-04: "Walk away from the block?" — Walk Away clears the kiosk and quits, the block dying quietly with the process; Keep Writing cancels; unlocked quits pass straight through, all quit paths route here). Nothing persists — the block dies with the session. - `WritingLockState.swift` — #162 (Cold Turkey S2, map #158) the writing lock machine + kiosk: `WritingLockState` (@Observable, app-scoped as `gate.writingLock`; `static weak active` is the app-delegate's quit-refusal handle) — `start(goal:body:at:)` arms (refuses a second block while locked), a 1 s ticker + the per-keystroke `feed(text:)` (ProseTextView.onTextChange, both editor modes) drive `WritingGoalRun`, `tick(at:)` completes on the first met tick (internal seam — tests inject the decisive moments), `complete()` exits the kiosk and leaves `completionNote` fading ~6 s. `WritingLockKiosk` — the #159 recipe verbatim (6-option combo + `.disableScreenCornerInteractions`), enter = activate→options→toggle (returns whether WE toggled fullscreen — an already-fullscreen window is entered in place; exit replays only what entry toggled), exit = options-clear-FIRST then toggle (never churn mid-transition); ⌘W + ⌃⌘F + ⌘N refusals = a local keyDown monitor (matched by KEY CODE with the exact modifier set plus a lowercased character net — audit 2026-11-04: charactersIgnoringModifiers is layout- and Caps-Lock-dependent, a Cyrillic/caps ⌘W slipped past while the stock Close still fired; ⌘N covers the stock New Window item SwiftUI owns, which stays enabled mid-lock) swallowing all three while locked (⌃⌘F added 2026-11-04: the kiosk holds even windowed, so a user-initiated fullscreen exit mid-block left a windowed kiosk — menu bar gone, quit refused — the dogfood trap; fullscreen now leaves only via completion) (SwiftUI owns the stock window delegate and `.closeItem` has no CommandGroupPlacement — the OutlineDrag monitor pattern, installed/removed with the lock); hosted-test guard = full no-op (never kiosk the test machine). `WritingLockAppDelegate` (`@NSApplicationDelegateAdaptor` in MuseionApp) — `applicationShouldTerminate` while locked asks ONCE (#163 ruling 2026-11-04: "Walk away from the block?" — Walk Away clears the kiosk and quits, the block dying quietly with the process; Keep Writing cancels; unlocked quits pass straight through, all quit paths route here). Nothing persists — the block dies with the session.
- `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft). - `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, symmetric 2×2 equal-cell grid — top-aligned rows, fixed two-line explain frames; **ui-polish r2:** y-value labels OUTSIDE the plot in a dedicated trailing axis gutter, vertically centered on their gridlines — one tick convention everywhere = domain bounds + midpoint (the zero line reads on 0…1 cards); x labels capture-aligned, one centered "Oct 5" (POSIX `MMM d`) under each capture date, never weekly ticks that miss the points). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` in neutral foreground ink (r2: no arrow glyph, no per-verdict tint — polarity rides the card-header badge (↑/↓ better) alone; the old orange slipping died with the ui-polish round, the arrows with r2); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`. - `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent). - `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
- `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue. - `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue.
- `Micropub.swift` + `MicropubMedia.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) + #34 (S6.2) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped, except #34's asset illustration refs which REWRITE to their uploaded URLs on the WIRE — position and alt stay the writer's; the piece on disk never changes], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; #34: uploaded illustrations ride INLINE inside `content` — the rail rewrites each asset ref to its uploaded URL exactly where it stands; NO `photo` property (a property renders wherever the theme decides — live-verified 2026-11-01: bottom of the post, position lost)); `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable; `decodeFailure` is internal (the one failure decode — MicropubMedia's media steps share it rather than fork it) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubMedia.swift`** — #34 (S6.2, G12) illustrations travel with it (a `nonisolated extension Micropub`): `illustrations(in:)` parses the body's `![alt](assets/…)` refs — the ONLY images Museion uploads (remote http(s) refs ride as prose; ceiling (ponytail): plain paren form, no fence scan, no space-bearing destinations); `rewritingIllustrations(_:uploaded:)` builds the wire content (each UPLOADED ref swaps exactly where it stands — position and alt are the writer's, a quoted title drops, foreign images and unuploaded refs ride byte-identical, and a URL carrying markdown-active characters (`)`/`(`/`<>`/space) rides the ANGLE form `![alt](<url>)` — a plain-paren dest would close at the first `)` and smuggle a live attacker link; trustworthyURL was built for line-bounded frontmatter, not this sink — parse and rewrite share ONE regex (a `let`) so they can never drift); `mimeType(forDestination:)` = exactly the endpoint's formats (png/jpg/jpeg/gif/webp/svg — anything else refuses, no guessed content type ships); `mediaEndpoint(token:transport:)` = `GET ?q=config` decode of `media-endpoint` behind the trustworthyURL gate (the writer's PNG and token POST to the discovered endpoint); `makeMediaUploadRequest`/`uploadMedia` = the multipart `file` POST (boundary per request; the filename is sanitized — a quote/control char can't break the Content-Disposition) decoding exactly like the create (Location → body `url` → trust gate → requestFailed; 401/403 → authFailed); `Illustration`/`MediaResult` are the shared shapes (`Photo` died with the property path); the alt group in the shared regex is SINGLE-LINE by design — a ref whose alt spans lines doesn't parse at all (rides as prose, never uploads, never rewrites — a parsed-but-unrewritten ref would ship a broken relative link). The publish FLOOR lives in ONE gate (#6: where all callers route — a parsed body ref is the ONLY way an image ships, and every send routes through it): the model rail — `uploadIllustrations` (private PostsModel helper beside `micropubSendDraft` in Micropub.swift) — refuses BEFORE any wire traffic (the refusal names the destination — the parse itself never hides a ref), pre-flights every payload read and CONTAINS it in the piece — a `../` ref OR a symlinked asset refuses (`resolvingSymlinksInPath` both sides, the cards/learnings posture; the payload list is one entry per FILE — duplicate refs share it and upload once) — before the first upload, uploads are all-or-nothing (a failed upload never sends a half-illustrated piece), and the engine is consulted for nothing — style judgment stays with the author (G12). ponytail: a re-send re-uploadsLine truncated - `Micropub.swift` + `MicropubMedia.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) + #34 (S6.2) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped, except #34's asset illustration refs which REWRITE to their uploaded URLs on the WIRE — position and alt stay the writer's; the piece on disk never changes], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; #34: uploaded illustrations ride INLINE inside `content` — the rail rewrites each asset ref to its uploaded URL exactly where it stands; NO `photo` property (a property renders wherever the theme decides — live-verified 2026-11-01: bottom of the post, position lost)); `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable; `decodeFailure` is internal (the one failure decode — MicropubMedia's media steps share it rather than fork it) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubMedia.swift`** — #34 (S6.2, G12) illustrations travel with it (a `nonisolated extension Micropub`): `illustrations(in:)` parses the body's `![alt](assets/…)` refs — the ONLY images Museion uploads (remote http(s) refs ride as prose; ceiling (ponytail): plain paren form, no fence scan, no space-bearing destinations); `rewritingIllustrations(_:uploaded:)` builds the wire content (each UPLOADED ref swaps exactly where it stands — position and alt are the writer's, a quoted title drops, foreign images and unuploaded refs ride byte-identical, and a URL carrying markdown-active characters (`)`/`(`/`<>`/space) rides the ANGLE form `![alt](<url>)` — a plain-paren dest would close at the first `)` and smuggle a live attacker link; trustworthyURL was built for line-bounded frontmatter, not this sink — parse and rewrite share ONE regex (a `let`) so they can never drift); `mimeType(forDestination:)` = exactly the endpoint's formats (png/jpg/jpeg/gif/webp/svg — anything else refuses, no guessed content type ships); `mediaEndpoint(token:transport:)` = `GET ?q=config` decode of `media-endpoint` behind the trustworthyURL gate (the writer's PNG and token POST to the discovered endpoint); `makeMediaUploadRequest`/`uploadMedia` = the multipart `file` POST (boundary per request; the filename is sanitized — a quote/control char can't break the Content-Disposition) decoding exactly like the create (Location → body `url` → trust gate → requestFailed; 401/403 → authFailed); `Illustration`/`MediaResult` are the shared shapes (`Photo` died with the property path); the alt group in the shared regex is SINGLE-LINE by design — a ref whose alt spans lines doesn't parse at all (rides as prose, never uploads, never rewrites — a parsed-but-unrewritten ref would ship a broken relative link). The publish FLOOR lives in ONE gate (#6: where all callers route — a parsed body ref is the ONLY way an image ships, and every send routes through it): the model rail — `uploadIllustrations` (private PostsModel helper beside `micropubSendDraft` in Micropub.swift) — refuses BEFORE any wire traffic (the refusal names the destination — the parse itself never hides a ref), pre-flights every payload read and CONTAINS it in the piece — a `../` ref OR a symlinked asset refuses (`resolvingSymlinksInPath` both sides, the cards/learnings posture; the payload list is one entry per FILE — duplicate refs share it and upload once) — before the first upload, uploads are all-or-nothing (a failed upload never sends a half-illustrated piece), and the engine is consulted for nothing — style judgment stays with the author (G12). ponytail: a re-send re-uploadsLine truncated
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): **#146: the domain extensions live in their own files — outline guard + Convert (`PostsModelOutline.swift`), pass + Blind Read (`PostsModelPasses.swift`), fix cards ×3 (`PostsModelCards.swift`) — and `startWatching` + `rescan` sit in a file-scope watcher extension (type-body ceiling); members the moves straddle are internal and the two wrapped guards unwrapped (#142 posture) — nothing else changed.** posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text; **#143 (OPT-F3):** the rescan threads one app-scoped `PostScanCache` through the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips the `posts` assignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observing `posts` would regroup on the app's own autosave echoes); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in `extension PostsModel` in PostsModelOutline.swift (#146). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opeLine truncated - `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): **#146: the domain extensions live in their own files — outline guard + Convert (`PostsModelOutline.swift`), pass + Blind Read (`PostsModelPasses.swift`), fix cards ×3 (`PostsModelCards.swift`) — and `startWatching` + `rescan` sit in a file-scope watcher extension (type-body ceiling); members the moves straddle are internal and the two wrapped guards unwrapped (#142 posture) — nothing else changed.** posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text; **#143 (OPT-F3):** the rescan threads one app-scoped `PostScanCache` through the detached scan — a watcher burst re-reads only changed post.md files, not the library — and skips the `posts` assignment when the scan equals the current list, since @Observable invalidates on assignment regardless of equality and panes observing `posts` would regroup on the app's own autosave echoes); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in `extension PostsModel` in PostsModelOutline.swift (#146). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opeLine truncated
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here. - `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions. - `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (#ui-r2: marker by DEPTH — every top-level row the same 10pt filled disc, every nested level the single 7pt dot, parent-vs-leaf never changes the glyph, ink foreground-0.8 not muted; fold toggle stays on child-bearing rows; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box) (ui-polish r1: outline bullet glyphs render at ONE size — parent-vs-leaf stays the fill distinction, never size), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam). - `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `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. - `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/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#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). - Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#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 dLine truncated - 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 dLine truncated
- Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current; **#136:** the pane 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 unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship; **#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 paLine truncated - 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 wrLine truncated
- 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. - 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 `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView` (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) `<CloudDocs>/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). - `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) `<CloudDocs>/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).
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column. - `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
+87 -23
View File
@@ -130,7 +130,11 @@ struct LearningsPaneView: View {
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
// No New button — learnings arrive by promotion, not creation. // No New button — learnings arrive by promotion, not creation.
PaneHeader(title: "Learnings") // One shared leading edge (26): pane title, group headings, and
// entry text all start at the same x.
// r8 (argon#9, mercury#18/19): the hairline is bounded to the
// SAME 720pt reading column the entries sit in — one framed block.
PaneHeader(title: "Learnings", titleInset: 26, hairlineMaxWidth: 720)
if let lastError { if let lastError {
Text(lastError) Text(lastError)
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
@@ -146,12 +150,22 @@ struct LearningsPaneView: View {
} else { } else {
ScrollView { ScrollView {
LazyVStack(alignment: .leading, spacing: 4) { LazyVStack(alignment: .leading, spacing: 4) {
ForEach(groups, id: \.type) { group in // r6 (argon#17, mercury#26 — rhythm): the FIRST
LearningSection(group: group) { entry in // group sits 10pt under the pane header; every
// later group breaks with a column-bounded
// hairline above its head (~22pt above the
// rule, ~18pt below — LearningSection).
ForEach(Array(groups.enumerated()), id: \.element.type) { index, group in
LearningSection(group: group, isFirst: index == 0) { entry in
dismiss(entry, in: group.type) dismiss(entry, in: group.type)
} }
} }
} }
// ui-polish r2: bounded reading column (~720pt, the
// transcript's measure language), left-anchored — entries
// never stretch across the whole canvas.
.frame(maxWidth: 720, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 12) .padding(.bottom, 12)
} }
} }
@@ -223,28 +237,59 @@ struct LearningsPaneView: View {
/// One content-type section: the head + its rows. A child view so the /// One content-type section: the head + its rows. A child view so the
/// lazy stack sees one view per group (its inner ForEach is the view's /// lazy stack sees one view per group (its inner ForEach is the view's
/// own body, not uneven outer-row content). /// own body, not uneven outer-row content). r5 (argon#17, mercury#26):
/// `isFirst` picks the rhythm — 10pt under the pane header (no rule; the
/// header's own hairline is right above), or a 32pt break with a
/// column-bounded hairline above the head.
private struct LearningSection: View { private struct LearningSection: View {
let group: LearningsIndex.Group let group: LearningsIndex.Group
let isFirst: Bool
let onDismiss: (LearningsIndex.Entry) -> Void let onDismiss: (LearningsIndex.Entry) -> Void
var body: some View { var body: some View {
SectionHeadView(type: group.type, count: group.entries.count) VStack(alignment: .leading, spacing: 4) {
.padding(.top, 16) if !isFirst {
.padding(.horizontal, 14) // r6 (argon#16, mercury#26): the break hairline is BOUNDED
.padding(.bottom, 6) // to the content column — same leading x as the entry text
// Foreign (unclocked) dirs never offer Dismiss — their clock // (26), same right edge as the 720 column (it used to start
// reads 0 forever, a dismiss there would hide permanently (the // 27px LEFT of the text and end mid-window).
// store refuses too; #27 audit). Rectangle()
let dismissable = LearningDecay.isClocked(group.type) .fill(DesignTokens.border)
ForEach(group.entries) { entry in .frame(height: 1)
LearningRow(entry: entry, onDismiss: dismissable ? { onDismiss(entry) } : nil) .padding(.leading, 26)
}
SectionHeadView(type: group.type, count: group.entries.count)
// r7 (argon#15, mercury#49): the FIRST category label
// sits 24pt under the header hairline (the r6 10 clung
// to the rule); later groups keep their break rhythm.
.padding(.top, isFirst ? 24 : 14)
.padding(.horizontal, 26)
.padding(.bottom, 2)
// Foreign (unclocked) dirs never offer Dismiss — their clock
// reads 0 forever, a dismiss there would hide permanently (the
// store refuses too; #27 audit).
let dismissable = LearningDecay.isClocked(group.type)
ForEach(group.entries) { entry in
LearningRow(entry: entry, onDismiss: dismissable ? { onDismiss(entry) } : nil)
}
} }
// r6 rhythm (sol#36, mercury#54): above the rule = last row's
// bottom 10 + stack spacing 4 + this 8 ≈ 22pt (was ~36); below
// the rule = spacing 4 + head top 14 ≈ 18pt (was ~7) — balanced
// per the 20-24/16-20 ruling; label → first entry = head bottom
// 2 + spacing 4 + row top 10 ≈ 16 (was ~25, tighter).
.padding(.top, isFirst ? 0 : 8)
} }
} }
/// The library's section-head voice: serif-15 semibold name /// The section-head voice, DEMOTED below the pane title (serif-15):
/// (display-lowercased) + mono-11 `· N` count. /// ui-polish r2 — the library's pass-state voice (tracked UPPERCASE
/// mono micro-label) + mono-11 `· N` count. r4 (sol#4, argon#49): 11pt
/// medium — a touch MORE weight than the filenames beneath, which
/// step down (LearningRow) so the category always wins the hierarchy.
/// r6: full muted ink (contrast final). The category break (22/18pt
/// margins + a column-bounded hairline) lives in LearningSection.
/// Shares the pane's single leading edge (26).
private struct SectionHeadView: View { private struct SectionHeadView: View {
let type: String let type: String
let count: Int let count: Int
@@ -252,8 +297,13 @@ private struct SectionHeadView: View {
var body: some View { var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 8) { HStack(alignment: .firstTextBaseline, spacing: 8) {
Text(type) Text(type)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
.textCase(.lowercase) // display-only — the dir name keeps its case .kerning(0.6)
.textCase(.uppercase) // display-only — the dir name keeps its case
// r6 (sol#6/21 — contrast final): full muted ink; the r4
// 0.9 wash died here (the weight step below still wins the
// hierarchy).
.foregroundStyle(DesignTokens.muted)
.lineLimit(1) .lineLimit(1)
.truncationMode(.tail) .truncationMode(.tail)
Text("· \(count)") Text("· \(count)")
@@ -276,25 +326,35 @@ private struct LearningRow: View {
var body: some View { var body: some View {
HStack(alignment: .top) { HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 5) { VStack(alignment: .leading, spacing: 5) {
// r7 (mercury#49, argon#15): serif-13 semibold — the
// pane title keeps the serif-15 rung; hierarchy rides
// the rung gap (r6's sans-14 sat too close to it).
Text(entry.pattern) Text(entry.pattern)
.font(.callout.weight(.semibold)) .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(1) .lineLimit(1)
.truncationMode(.tail) .truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
if let problem = entry.problem { if let problem = entry.problem {
// r7 (sol#34): descriptions at an explicit 13pt.
Text(problem) Text(problem)
.font(.callout) .font(.system(size: 13))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.lineLimit(2) .lineLimit(2)
.truncationMode(.tail) .truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
// r7 (sol#34): description → filename gap +5 (spacing 5
// + this 5 = 10) — the meta line reads as the entry's
// footnote, not a third body line.
Text(metaLine) Text(metaLine)
.font(.system(size: 11, design: DesignTokens.mono)) // r4 (mercury#59 tail): the filename/meta line recedes one
// more step — 10.5, beneath the 11pt medium category labels.
.font(.system(size: 10.5, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.lineLimit(1) .lineLimit(1)
.truncationMode(.tail) .truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.padding(.top, 5)
} }
if entry.resurfacesIn == nil, let onDismiss { if entry.resurfacesIn == nil, let onDismiss {
Button("Dismiss", action: onDismiss) Button("Dismiss", action: onDismiss)
@@ -305,8 +365,12 @@ private struct LearningRow: View {
.accessibilityLabel("Dismiss \(entry.pattern)") .accessibilityLabel("Dismiss \(entry.pattern)")
} }
} }
.padding(10) // One leading edge with the pane title and group headings (26).
.opacity(entry.resurfacesIn == nil ? 1 : 0.45) .padding(EdgeInsets(top: 10, leading: 26, bottom: 10, trailing: 14))
// Dismissed rows dim to the 0.85 floor (r6 contrast final —
// deliberately-receding chrome never sits below 0.85; the r2
// 0.6 dim died) — visible as dimmed, never washed out.
.opacity(entry.resurfacesIn == nil ? 1 : 0.85)
} }
private var metaLine: String { private var metaLine: String {
+130 -15
View File
@@ -110,14 +110,21 @@ struct MentorPaneView: View {
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 14) .padding(.horizontal, 16)
.padding(.top, 10) .padding(.top, 10)
} }
// #28: the transcript rendering is shared — the Sessions pane // #28: the transcript rendering is shared — the Sessions pane
// reads the same surface in the writing voice. #30: the // reads the same surface in the writing voice. #30: the
// freeform input + liveness ride the shared surface too. // freeform input + liveness ride the shared surface too.
// #155: the debug toggle's seat is the composer's edge. // #155: the debug toggle's seat is the composer's edge.
SessionTranscriptView(model: model, showsDebugRows: debugRows, debugBinding: $debugRows, home: home) // Owner ruling (2026-11-07): no roster session for the open
// piece → the honest empty presentation below (pass controls
// above stay); a foreign transcript never renders.
if model.activeEntry == nil {
scopedEmptyPresentation
} else {
SessionTranscriptView(model: model, showsDebugRows: debugRows, debugBinding: $debugRows, home: home)
}
case let .crashed(lastPrompt): case let .crashed(lastPrompt):
crashCard(lastPrompt: lastPrompt) crashCard(lastPrompt: lastPrompt)
} }
@@ -145,8 +152,75 @@ struct MentorPaneView: View {
// missing-engine states own the no-binary interim. // missing-engine states own the no-binary interim.
if binaryPath != nil { if binaryPath != nil {
await model.openSession() await model.openSession()
// Owner ruling (2026-11-07): the pane hosts the open piece's
// session — launch, first open, and every remount scope
// exactly like a piece switch (the restoring open piece, if
// any).
await scopeToOpenPiece()
} }
} }
// Owner ruling (2026-11-07): a piece switch re-hosts — the model's
// scope rail resumes the matching roster session or clears to the
// empty presentation; an in-flight turn or pass defers the switch
// to stream end (never torn down mid-stream).
.onChange(of: openPieceTitle) {
Task { await scopeToOpenPiece() }
}
}
// MARK: Piece-scoped hosting (owner ruling 2026-11-07)
/// The open piece in Posts — the hosting scope target. Reuses the
/// Sessions pane's pinned open-piece rail (the same association
/// "New Session on <title>" stamps); nil = unsaved draft, external
/// guest, or nothing open.
private var openPieceTitle: String? {
SessionsPaneView.openPiece(in: posts)?.title
}
private func scopeToOpenPiece() async {
await model.scopeHostedSession(toOpenPieceTitle: openPieceTitle)
}
/// The honest empty presentation: the open piece has no roster session
/// (or nothing is open). The pass bar above stays.
/// Round-7 (sol#30): TWO elements — the caption line + the wired
/// action; the serif heading and the separate Sessions-navigation
/// footnote line died (the caption already names the piece).
/// Round-7 (mercury#5): the block TOP-anchors ~48pt below the pass
/// bar — the centered block split the pane with a ~290px dead zone.
/// Round-8 (sol#2 + mercury#10/13 — FINAL RULING: left-align): the
/// caption + button align to the column's 16pt leading edge, one
/// axis with the pass controls above (centered text read as a second
/// glued region; re-centering stays outvoted — it produced r6's
/// dead zone).
private var scopedEmptyPresentation: some View {
VStack(alignment: .leading, spacing: 8) {
Text(emptyPresentationBody)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
if model.canStartSession, let openPieceTitle {
Button("New session for this piece") {
Task { _ = await model.newSession(name: "New Session", pieceTitle: openPieceTitle) }
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.padding(.top, 4)
.help("Start a session on “\(openPieceTitle)” — it hosts right here.")
}
}
.padding(.horizontal, 16)
.padding(.top, 48)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
}
private var emptyPresentationBody: String {
if let openPieceTitle {
return "The mentor pane follows “\(openPieceTitle)” — start one below, or from the Sessions pane."
}
return "The mentor pane follows the open piece — open one to see its session here."
} }
// MARK: Header // MARK: Header
@@ -167,16 +241,17 @@ struct MentorPaneView: View {
// layout priority. // layout priority.
if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId, sessionId != MentorSessionModel.passTranscriptKey { if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId, sessionId != MentorSessionModel.passTranscriptKey {
Text("session \(sessionId.prefix(8))") Text("session \(sessionId.prefix(8))")
.font(.system(size: 10, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.opacity(0.75) .opacity(0.75)
.textSelection(.enabled) .textSelection(.enabled)
} }
} }
.padding(.horizontal, 14) .padding(.horizontal, 16)
// #90: pane heads align at the export's 52px — same height as the // #90: pane heads align at the export's 52px — same height as the
// Posts header and the editor toolbar, so the three hairlines read // Posts header and the editor toolbar, so the three hairlines read
// as one line. // as one line. Round-2 polish: 16 — the ONE leading edge the
// transcript, pass bar, and composer all share.
.frame(minHeight: 52) .frame(minHeight: 52)
} }
} }
@@ -217,7 +292,9 @@ private extension MentorPaneView {
DisclosureGroup("Technical details") { DisclosureGroup("Technical details") {
Text(model.stderrTail.joined(separator: "\n")) Text(model.stderrTail.joined(separator: "\n"))
.font(.system(size: 10, design: .monospaced)) .font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary) // Round-2 sweep: muted at full ink (0.75 floor) —
// .secondary read fainter than the palette allows.
.foregroundStyle(DesignTokens.muted)
.textSelection(.enabled) .textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
@@ -258,13 +335,21 @@ private struct MonoButton: View {
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.disabled(disabled) .disabled(disabled)
.opacity(disabled ? 0.45 : 1) // Round-4 contrast (sol#4/39 + argon#11 + mercury#52): a disabled
// SECONDARY no longer dims the whole button — the ink carries the
// state (see `ink`); solid/outline keep the 0.75 dim.
.opacity(disabled && style != .secondary ? 0.75 : 1)
} }
private var ink: Color { private var ink: Color {
switch style { switch style {
case .solid: DesignTokens.surface case .solid: DesignTokens.surface
case .secondary: DesignTokens.foreground // Round-7 (argon#37/45 + mercury#45) → Round-8 (sol#1/argon#5 —
// FOURTH round, final): BOTH secondary states render muted #6B6964
// over the same clearly-visible border — full ink when enabled,
// ~65% when disabled. The r7 50% dim read as a ghost, not a
// control; the disabled state explains itself via `help`.
case .secondary: DesignTokens.muted.opacity(disabled ? 0.65 : 1)
case .outline: DesignTokens.accent case .outline: DesignTokens.accent
} }
} }
@@ -280,7 +365,12 @@ private struct MonoButton: View {
private var stroke: Color { private var stroke: Color {
switch style { switch style {
case .solid: .clear case .solid: .clear
case .secondary: DesignTokens.border // Round-7 (final ruling, with `ink`): the SAME clearly-visible
// border in BOTH secondary states — the r5 one-step-stronger
// darkening of border #E8E5DF via foreground opacity (no new
// hex). Ink opacity alone separates enabled from disabled;
// both states stay unmistakably controls.
case .secondary: DesignTokens.foreground.opacity(0.17)
case .outline: DesignTokens.accent case .outline: DesignTokens.accent
} }
} }
@@ -303,24 +393,45 @@ private struct PassBarView: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 0) { VStack(alignment: .leading, spacing: 0) {
selector selector
.padding(.bottom, 9) .padding(.horizontal, 16)
// Round-6 (argon#44): the tab row sits DIRECTLY on the divider
// — the r5 9pt gap left the active underline floating ~10px
// above the strip's bottom edge. The tab's internal 5pt bottom
// padding keeps text off the underline; the underline itself
// lands flush (zero gap).
Divider()
statusLine statusLine
.padding(.horizontal, 16)
.padding(.top, 8)
.padding(.bottom, 5) .padding(.bottom, 5)
Text(description) Text(description)
.font(.system(size: 11)) .font(.system(size: 11))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.fixedSize(horizontal: false, vertical: true) .fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 16)
.padding(.bottom, 10) .padding(.bottom, 10)
actions actions
.padding(.horizontal, 16)
// #137: the pass profile's provider has no key — name it and // #137: the pass profile's provider has no key — name it and
// offer the way out. A readable-but-keyed profile shows nothing. // offer the way out. A readable-but-keyed profile shows nothing.
if let label = missingKeyLabel { if let label = missingKeyLabel {
missingKeyLine(label: label) missingKeyLine(label: label)
.padding(.horizontal, 16)
.padding(.top, 8) .padding(.top, 8)
} }
} }
.padding(.horizontal, 14)
.padding(.vertical, 12) .padding(.vertical, 12)
// Round-2 polish (all three council seats): ONE leading edge — 16,
// the same inset as the header, the transcript's measure pads, and
// the composer below (the tabs/description/actions sat visibly
// deeper in the round-2 shots).
// Round-4 (argon#1/sol#6/mercury#25 — THIRD round on this): the
// padding above was always 16 — but the pane's outer VStack
// centers by default and this bar hugs its content, so the whole
// block rode ~56px in (centered in the 356pt column) while the
// header sits at 16. Claim the full width at leading; the
// declared 16 is now the REAL left edge.
.frame(maxWidth: .infinity, alignment: .leading)
} }
/// Contract `.selector`: text tabs — mono 10, uppercase, tracked; the /// Contract `.selector`: text tabs — mono 10, uppercase, tracked; the
@@ -357,10 +468,11 @@ private struct PassBarView: View {
} }
/// Contract `.status-line`: `PASS N · STATE` — the open piece's Pass /// Contract `.status-line`: `PASS N · STATE` — the open piece's Pass
/// State in the library's post-meta voice. /// State in the library's post-meta voice. Round-4: 11 — informational
/// micro-labels ride the 11pt legibility floor (mercury#52).
private var statusLine: some View { private var statusLine: some View {
Text("\(kind.rawValue) · \(stateLabel)") Text("\(kind.rawValue) · \(stateLabel)")
.font(.system(size: 10, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.tracking(0.8) .tracking(0.8)
.textCase(.uppercase) .textCase(.uppercase)
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
@@ -457,10 +569,13 @@ private struct PassBarView: View {
) )
} }
/// #122: why the Blind Read can't fire right now (nil = it can). /// #122: why the Blind Read can't fire right now (nil = it can). The
/// text names the actual gating condition — the snapshot one mirrors
/// `openPieceHasSnapshot` (latestPassSnapshot: no pass ever ran over
/// the open piece).
private var blindReadBlocked: String? { private var blindReadBlocked: String? {
guard let posts, posts.session?.postID != nil else { return "Open a post to run a Blind Read." } guard let posts, posts.session?.postID != nil else { return "Open a post to run a Blind Read." }
guard posts.openPieceHasSnapshot else { return "No Pass snapshot yet — run a Pass first." } guard posts.openPieceHasSnapshot else { return "Needs a pass snapshot — run Pass 1 first." }
guard model.phase.isReady, !model.isStreaming else { return "The mentor engine can't take the turn right now." } guard model.phase.isReady, !model.isStreaming else { return "The mentor engine can't take the turn right now." }
return nil return nil
} }
+73
View File
@@ -131,6 +131,19 @@ nonisolated enum SessionRoster {
} }
} }
/// Owner ruling (2026-11-07): the Mentor pane hosts the OPEN PIECE's
/// session — this is the pure seam the pane's scoping rides. The roster is
/// newest-first, so the FIRST exact `pieceTitle` match is the newest
/// session for the piece; nil (no open piece, or no match) hosts nothing —
/// the pane's honest empty presentation, never a foreign transcript.
/// Pinned in SessionScopeTests.
nonisolated extension SessionRoster {
static func hostedSessionId(forOpenPieceTitle title: String?, in entries: [SessionEntry]) -> String? {
guard let title else { return nil }
return entries.first { $0.pieceTitle == title }?.sessionId
}
}
/// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the /// Pane + bridge state machine. Lazy lifecycle: the engine spawns when the
/// pane opens its first session and stays alive for the app's life (map /// pane opens its first session and stays alive for the app's life (map
/// decision: child lifecycle). The engine bridge is session-agnostic — /// decision: child lifecycle). The engine bridge is session-agnostic —
@@ -222,6 +235,11 @@ final class MentorSessionModel {
/// #137: a model-change restart requested mid-turn — fires at turn end /// #137: a model-change restart requested mid-turn — fires at turn end
/// (firePendingRestartIfRequested), whichever engine streamed. /// (firePendingRestartIfRequested), whichever engine streamed.
private var pendingRestart = false private var pendingRestart = false
/// Owner ruling (2026-11-07): an open-piece switch that arrived while a
/// turn or pass streamed — fires at turn end
/// (firePendingScopeIfRequested); an in-flight transcript is never
/// torn down mid-stream.
private var pendingScopePieceTitle: String?
/// #137: per-pass readiness (refreshPassReadiness, same-file #137 /// #137: per-pass readiness (refreshPassReadiness, same-file #137
/// extension) + the injectable read seam (tests). Stored in the class /// extension) + the injectable read seam (tests). Stored in the class
/// body — extensions carry no stored state. /// body — extensions carry no stored state.
@@ -533,6 +551,9 @@ final class MentorSessionModel {
timeout: Self.promptTimeout, timeout: Self.promptTimeout,
) )
replayingSessionId = nil 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 // The real adapter (0.21.5, live-verified #30 dogfood) answers
// session/load WITHOUT a top-level sessionId — the id rides // session/load WITHOUT a top-level sessionId — the id rides
// `_meta.hermes.sessionProvenance.acpSessionId`. The fake's // `_meta.hermes.sessionProvenance.acpSessionId`. The fake's
@@ -567,6 +588,7 @@ final class MentorSessionModel {
return true return true
} catch { } catch {
replayingSessionId = nil replayingSessionId = nil
firePendingScopeIfRequested()
// Partial replay rows (if any) + the failure row stay in the // Partial replay rows (if any) + the failure row stay in the
// ENTRY's store — attributed, visible on its next row click. // ENTRY's store — attributed, visible on its next row click.
appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId) appendRow(.text("Resume failed — \(error.localizedDescription)"), to: entry.sessionId)
@@ -574,6 +596,41 @@ final class MentorSessionModel {
} }
} }
/// Owner ruling (2026-11-07): the Mentor pane hosts the OPEN PIECE's
/// session, never the engine's latest unconditionally — editing one
/// piece must not show a conversation about another. The target is the
/// pure seam's answer over the roster (`hostedSessionId` — exact
/// pieceTitle match, newest first); the switch rides `resumeSession`.
/// No match (or nothing open) hosts NOTHING — `activeEntry` clears and
/// the pane renders its honest empty presentation; the roster is
/// untouched (the Sessions pane stays the unscoped archive). Guards: a
/// streaming turn or in-flight pass transcript is never interrupted —
/// the switch defers to turn end; not-ready is a no-op (the pane's
/// engine states own that path).
func scopeHostedSession(toOpenPieceTitle pieceTitle: String?) async {
guard phase.isReady else { return }
guard !isStreaming else {
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 }
guard let entry = roster.first(where: { $0.sessionId == target }) else {
activeEntry = nil
return
}
_ = await resumeSession(entry)
}
/// Fork the active session (#28): the engine copies its history to a NEW /// Fork the active session (#28): the engine copies its history to a NEW
/// sessionId (session/fork); Museion rosters '<name> (fork)' with the /// sessionId (session/fork); Museion rosters '<name> (fork)' with the
/// same pieceTitle and activates it with a FRESH transcript — the /// same pieceTitle and activates it with a FRESH transcript — the
@@ -783,6 +840,9 @@ extension MentorSessionModel {
isStreaming = false isStreaming = false
// #137: a model-change restart requested mid-turn fires now. // #137: a model-change restart requested mid-turn fires now.
firePendingRestartIfRequested() firePendingRestartIfRequested()
// Owner ruling (2026-11-07): a piece switch deferred behind the
// turn fires now too.
firePendingScopeIfRequested()
} }
return await turnCore( return await turnCore(
client: client, client: client,
@@ -918,6 +978,10 @@ extension MentorSessionModel {
isStreaming = false isStreaming = false
teardownPassEngine() teardownPassEngine()
firePendingRestartIfRequested() firePendingRestartIfRequested()
// Owner ruling (2026-11-07): a piece switch deferred behind the
// pass fires at the verdict — the in-flight transcript was never
// interrupted.
firePendingScopeIfRequested()
} }
let pass = ACPEngineClient(binaryPath: binaryPath, profile: profile) let pass = ACPEngineClient(binaryPath: binaryPath, profile: profile)
passClient = pass passClient = pass
@@ -1053,6 +1117,15 @@ extension MentorSessionModel {
Task { await respawn() } Task { await respawn() }
} }
/// Owner ruling (2026-11-07): a deferred open-piece switch fires at turn
/// end — from BOTH turn-end defers (chat sendPrompt and the pass run),
/// after `isStreaming` cleared, so the scope rail re-evaluates for real.
private func firePendingScopeIfRequested() {
guard let title = pendingScopePieceTitle else { return }
pendingScopePieceTitle = nil
Task { await scopeHostedSession(toOpenPieceTitle: title) }
}
/// Base version of a version string — the part before `+` build metadata /// Base version of a version string — the part before `+` build metadata
/// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`. /// (PEP 440 local version segment). `0.21.5+2177.g735e426` → `0.21.5`.
nonisolated static func baseVersion(of version: String) -> String { nonisolated static func baseVersion(of version: String) -> String {
+67
View File
@@ -0,0 +1,67 @@
//
// NewPostFromSessionSheet.swift
// Museion
//
// #30 (S2.7): the New Post from Session ask — extracted from
// SessionsPaneView (Round-1 polish: the pane file rides its 400-line
// lint ceiling). Behavior unchanged.
//
import SwiftUI
/// #30 (S2.7): the New Post from Session ask — the draft candidate
/// (the session's last mentor reply) prefills and stays editable.
/// Confirm materializes the piece stamped `origin: ai` — never
/// stats-eligible — and opens it in Posts; Cancel writes nothing.
/// The error line is SHEET-LOCAL state: it dies with the presentation,
/// so a re-opened ask never shows a stale refusal.
struct NewPostFromSessionSheet: View {
@Binding var draft: String
/// The confirm's failure reason — a failed write keeps the sheet up,
/// draft intact; dismissal itself is the cancel.
@State private var createError: String?
let create: () -> String?
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("New Post from Session")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text(
"The draft starts from the session's last mentor reply. It lands in your library stamped origin: ai — never counted as your writing.",
)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
TextEditor(text: $draft)
.font(.system(size: 13, design: DesignTokens.serif))
.frame(width: 380, height: 160)
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.border),
)
if let createError {
Text(createError)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(.orange)
}
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// sessionDraft = nil) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Create Post", action: confirm)
.keyboardShortcut(.defaultAction)
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(20)
.frame(width: 420)
}
/// No dismiss() here — success closes the sheet via the pane's
/// `sessionDraft = nil` (the binding); failure keeps it up with the
/// inline reason and the edited draft intact.
private func confirm() {
createError = create()
}
}
+125 -24
View File
@@ -92,6 +92,26 @@ nonisolated enum OutlinePresenter {
nodes.reduce(0) { $0 + 1 + countTree($1.children) } nodes.reduce(0) { $0 + 1 + countTree($1.children) }
} }
/// Top padding per visible row id — the branch rhythm
/// (`ProseTypography.outlineBranchSpacing`) before a row that opens a
/// top-level parent group (#ui-r5 argon#14) or FOLLOWS A DEEPER row:
/// a nested block just closed, and its transition back to the parent
/// level reads the SAME gap whatever follows — parent or leaf, any
/// depth (#ui-r8 argon#7: the gap after one nested sublist read ~38px,
/// after another ~28px, because only a parent follower carried the
/// padding). Pure over the projection; zoom's re-based depths included.
static func spacingBefore(rows: [Row]) -> [UUID: CGFloat] {
var out: [UUID: CGFloat] = [:]
for (index, row) in rows.enumerated() {
let opensBranch = row.depth == 0 && row.childCount > 0
let closesNested = index > 0 && rows[index - 1].depth > row.depth
if opensBranch || closesNested {
out[row.id] = ProseTypography.outlineBranchSpacing
}
}
return out
}
/// The visible-row ids from `from` to `to`, inclusive, in visible /// The visible-row ids from `from` to `to`, inclusive, in visible
/// order; nil when either id isn't visible. Block-selection range /// order; nil when either id isn't visible. Block-selection range
/// math (⇧↑/⇧↓ anchor↔focus). #112: zoom-aware — ids outside the /// math (⇧↑/⇧↓ anchor↔focus). #112: zoom-aware — ids outside the
@@ -190,6 +210,27 @@ nonisolated enum OutlinePresenter {
// MARK: - The surface // MARK: - The surface
/// #ui-r4 (mercury#28): nesting geometry — 30px per level (r3's 18px
/// read flat; judges asked 28–32). #ui-r5 (argon#1): guide rails sit on
/// the PARENT bullet's center column, the drop seam on the child bullet
/// column. DropGeometry (OutlineDrag.swift) still owns the 20pt grip
/// margin; its 18-based rail constants are no longer read by this chrome.
private enum NestGeometry {
static let unit: CGFloat = 30
/// The bullet cell's width (bullet() frames its glyph 22×27).
static let bulletCell: CGFloat = 22
/// A depth-d row's TEXT column, from the row's leading edge.
static func textColumn(depth: Int) -> CGFloat {
DropGeometry.gripWidth + CGFloat(depth) * unit + bulletCell
}
/// The bullet CENTER column — the drop seam's left edge.
static func bulletColumn(depth: Int) -> CGFloat {
textColumn(depth: depth) - DropGeometry.bulletCenter
}
}
/// The outline editing surface (#109): rows of chrome (guide rails, /// The outline editing surface (#109): rows of chrome (guide rails,
/// bullets, fold counts) around one live caret row. Session mode re-parses /// bullets, fold counts) around one live caret row. Session mode re-parses
/// on `loadGeneration` bumps (open / Yes-reload); draft mode seeds from /// on `loadGeneration` bumps (open / Yes-reload); draft mode seeds from
@@ -227,6 +268,7 @@ struct OutlineEditorView: View {
var body: some View { var body: some View {
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last) let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
let rowSpacing = OutlinePresenter.spacingBefore(rows: rows)
VStack(alignment: .leading, spacing: 0) { VStack(alignment: .leading, spacing: 0) {
if !zoomStack.isEmpty { if !zoomStack.isEmpty {
breadcrumb breadcrumb
@@ -248,8 +290,15 @@ struct OutlineEditorView: View {
} else { } else {
ScrollView { ScrollView {
LazyVStack(alignment: .leading, spacing: 0) { LazyVStack(alignment: .leading, spacing: 0) {
outlineTitleHeader
ForEach(rows) { row in ForEach(rows) { row in
rowView(row) rowView(row)
// #ui-r5 (argon#14) + #ui-r8 (argon#7): the
// branch rhythm — a top-level parent group
// separates from siblings, and every nested
// block's close reads the SAME gap whatever
// follows (parent or leaf, any depth).
.padding(.top, rowSpacing[row.id] ?? 0)
} }
} }
.padding(.top, 24) .padding(.top, 24)
@@ -338,20 +387,13 @@ struct OutlineEditorView: View {
private func rowView(_ row: OutlinePresenter.Row) -> some View { private func rowView(_ row: OutlinePresenter.Row) -> some View {
HStack(alignment: .top, spacing: 0) { HStack(alignment: .top, spacing: 0) {
gripCell(row) gripCell(row)
// Per-depth guide rails (prototype variant B: 1px hairline per // #ui-r4 (mercury#28): the per-level indent is a plain spacer —
// ancestor level, at DropGeometry's bulletCenter + level·railUnit // the guide rails moved to the row background (rails(depth:)),
// — same constants the drop seam uses, so rails and seam // where a stroke can sit on the CHILD text column, right of the
// cannot drift apart). // child bullet; the old in-stack canvas could never reach past
Canvas { context, size in // the indent region.
for level in 0 ..< row.depth { Color.clear
let railX = DropGeometry.bulletCenter + CGFloat(level) * DropGeometry.railUnit .frame(width: CGFloat(row.depth) * NestGeometry.unit)
context.fill(
Path(CGRect(x: railX, y: 0, width: 1, height: size.height)),
with: .color(DesignTokens.border),
)
}
}
.frame(width: CGFloat(row.depth) * DropGeometry.railUnit)
bullet(row) bullet(row)
if row.id == focusedID { if row.id == focusedID {
OutlineRowTextView( OutlineRowTextView(
@@ -384,6 +426,8 @@ struct OutlineEditorView: View {
} }
} }
.padding(.trailing, 20) .padding(.trailing, 20)
// #ui-r4 (mercury#28): guide rails behind the selection wash.
.background { rails(depth: row.depth) }
// Block-selection highlight (⇧↑/⇧↓ / ⇧click range, anchor↔focus). // Block-selection highlight (⇧↑/⇧↓ / ⇧click range, anchor↔focus).
.background(rowSelected(row) ? DesignTokens.accent.opacity(0.08) : Color.clear) .background(rowSelected(row) ? DesignTokens.accent.opacity(0.08) : Color.clear)
// #112: the moving run lifts (prototype .lifted) while a drag runs. // #112: the moving run lifts (prototype .lifted) while a drag runs.
@@ -429,15 +473,15 @@ struct OutlineEditorView: View {
} }
/// The seam line: left edge at the dropped block's future bullet /// The seam line: left edge at the dropped block's future bullet
/// column (11 + d·18 + the 20pt margin), running to the row's end. /// column (bulletCenter + d·30 + the 20pt margin), running to the
/// The spacer is height-pinned to 2 — a flexible one expands the /// row's end. The spacer is height-pinned to 2 — a flexible one expands the
/// HStack to the row height and CENTERS the bar, drawing every seam /// HStack to the row height and CENTERS the bar, drawing every seam
/// half a row off (the row's own frame alignment then has nothing /// half a row off (the row's own frame alignment then has nothing
/// to align). /// to align).
private func seamLine(depth: Int, valid: Bool) -> some View { private func seamLine(depth: Int, valid: Bool) -> some View {
HStack(spacing: 0) { HStack(spacing: 0) {
Color.clear Color.clear
.frame(width: DropGeometry.bulletColumn(depth: depth), height: 2) .frame(width: NestGeometry.bulletColumn(depth: depth), height: 2)
Group { Group {
if valid { if valid {
Rectangle().fill(DesignTokens.accent) Rectangle().fill(DesignTokens.accent)
@@ -453,30 +497,37 @@ struct OutlineEditorView: View {
.allowsHitTesting(false) .allowsHitTesting(false)
} }
/// The bullet cell (22×27): fold toggle when the node has children /// The bullet cell (22×27): marker by DEPTH (#ui-r2, sol#12/argon#20/
/// ("●" ~7pt, folded → accent), leaf "◦" ~10pt; tapping a leaf focuses. /// mercury#32) — every top-level row the SAME filled 10pt disc, every
/// nested level the single smaller 7pt dot. Parent-vs-leaf no longer
/// changes the glyph (the r1 ring-vs-dot pair still read as
/// inconsistent same-rank markers); hierarchy reads from indentation
/// + children presence. Ink one step darker (#ui-r2, sol#45):
/// foreground at 0.8, not muted — markers belong to their text.
/// The fold toggle stays on rows with children ("●" button, folded =
/// accent + "⋯ N" count); tapping a leaf focuses.
/// #112: double-click any bullet zooms in. The two clicks of the /// #112: double-click any bullet zooms in. The two clicks of the
/// double-click round-trip the fold toggle (fold→unfold), so the /// double-click round-trip the fold toggle (fold→unfold), so the
/// zoomed-in projection opens with the node's fold state unchanged. /// zoomed-in projection opens with the node's fold state unchanged.
@ViewBuilder @ViewBuilder
private func bullet(_ row: OutlinePresenter.Row) -> some View { private func bullet(_ row: OutlinePresenter.Row) -> some View {
let foldable = row.childCount > 0 let foldable = row.childCount > 0
let glyph = Text(foldable ? "●" : "◦") let glyph = Text("●")
.font(.system(size: foldable ? 7 : 10)) .font(.system(size: row.depth == 0 ? 10 : 7))
.foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.muted) .foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.foreground.opacity(0.8))
Group { Group {
if foldable { if foldable {
Button { Button {
toggleFold(row.id) toggleFold(row.id)
} label: { } label: {
glyph.frame(width: 22, height: 27) glyph.frame(width: NestGeometry.bulletCell, height: 27)
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.help("fold/unfold (⌘↑ / ⌘↓) · double-click: zoom in") .help("fold/unfold (⌘↑ / ⌘↓) · double-click: zoom in")
.accessibilityLabel(row.isFolded ? "Unfold \(row.text)" : "Fold \(row.text)") .accessibilityLabel(row.isFolded ? "Unfold \(row.text)" : "Fold \(row.text)")
} else { } else {
glyph glyph
.frame(width: 22, height: 27) .frame(width: NestGeometry.bulletCell, height: 27)
.contentShape(Rectangle()) .contentShape(Rectangle())
.onTapGesture { focus(row.id) } .onTapGesture { focus(row.id) }
.help("double-click: zoom in") .help("double-click: zoom in")
@@ -842,4 +893,54 @@ extension OutlineEditorView {
onDraftEdit?(md) onDraftEdit?(md)
} }
} }
/// #ui-r5 (argon#14): the piece's title at the prose editor's title
/// rung (serif, 22) — the outline opens as a page, not a bare bullet
/// list. The title text comes from `outlineTitle` below.
@ViewBuilder
private var outlineTitleHeader: some View {
if let title = outlineTitle {
Text(title)
.font(Font(ProseTypography.titleFont))
.foregroundStyle(DesignTokens.foreground)
.padding(.leading, DropGeometry.gripWidth)
.padding(.bottom, 14)
}
}
/// #ui-r5 (argon#14): the piece's title — the first non-blank preamble
/// line with heading markers stripped (Post.scan's title rule; the same
/// line the library row shows). Rendered above the tree; the remaining
/// preamble lines stay byte-preserved in the document but unshown, as
/// before. Lives here, not in the struct body — the type sits at
/// swiftlint's type_body_length ceiling.
private var outlineTitle: String? {
guard let raw = preamble.first(where: { !$0.trimmingCharacters(in: .whitespaces).isEmpty }) else {
return nil
}
let stripped = raw.drop(while: { $0 == "#" }).trimmingCharacters(in: .whitespaces)
return stripped.isEmpty ? nil : stripped
}
/// #ui-r5 (argon#1/sol#7 — r4 REGRESSION): one hairline rail per
/// ancestor level, at the PARENT bullet's CENTER column — directly
/// under the parent's bullet dot, LEFT of the child's marker, in the
/// indentation gutter. r4 put the stroke on the child TEXT column
/// (`textColumn(depth: level + 1)`), where it read as a stray caret
/// flush to the child's first letter. Full-row background so
/// consecutive siblings' segments join. Lives in this extension like
/// the other chrome helpers — the struct body sits at swiftlint's
/// type_body_length ceiling.
private func rails(depth: Int) -> some View {
Canvas { context, size in
for level in 0 ..< depth {
let railX = NestGeometry.bulletColumn(depth: level)
context.fill(
Path(CGRect(x: railX, y: 0, width: 1, height: size.height)),
with: .color(DesignTokens.border),
)
}
}
.allowsHitTesting(false)
}
} }
+43 -7
View File
@@ -239,9 +239,20 @@ struct PostEditorView: View {
// MARK: Toolbar // MARK: Toolbar
private var toolbar: some View { private var toolbar: some View {
HStack { // #ui-r6 (mercury#51): one 10pt rhythm across the fixed pairs —
// Read→crumb read ~7 (default stack spacing) against Publish→
// Saved's ~18 (spacing + the old trailing padding); the spacer
// stays the only flexible gap.
HStack(spacing: 10) {
// #68: labeled toggle, far left, before the crumb. // #68: labeled toggle, far left, before the crumb.
// #ui-r5 (mercury#22): same geometry family as Publish —
// BorderedSecondaryButtonStyle(28): one height (28) and one
// corner radius (8) across the editor toolbar; content is the
// only difference. (Run Pass lives in MentorPaneView —
// cross-file, intentionally untouched; its 28pt height now
// matches, its accent fill marks the primary action.)
Button(reading ? "Edit" : "Read") { toggleReading() } Button(reading ? "Edit" : "Read") { toggleReading() }
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.help(reading ? "Return to editing (⌘R)" : "Render this post (⌘R)") .help(reading ? "Return to editing (⌘R)" : "Render this post (⌘R)")
Text(crumb) Text(crumb)
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
@@ -251,12 +262,13 @@ struct PostEditorView: View {
Spacer() Spacer()
// #33 (S6.1): the publish entry — draft first, then publish. // #33 (S6.1): the publish entry — draft first, then publish.
if let publish { if let publish {
// #ui-r4 (argon#46): the bordered mono-11 pill — the action
// reads distinct from the passive "Saved" status beside it.
// #ui-r6: no trailing padding — the stack's 10pt spacing is
// the whole Publish→Saved gap (was 10+8 ≈ 18).
Button("Publish") { publish() } Button("Publish") { publish() }
.buttonStyle(.plain) .buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.help("Send to Micro.blog — draft first, then publish") .help("Send to Micro.blog — draft first, then publish")
.padding(.trailing, 10)
} }
if let session { if let session {
SaveStateDot(state: session.saveState) SaveStateDot(state: session.saveState)
@@ -404,6 +416,17 @@ struct ProseTextView: NSViewRepresentable {
return state return state
} }
/// #ui-r1 (sol#14/argon#28): a document may open with leading blank
/// lines (Post.scan's title rule skips them) — a programmatic caret at
/// location 0 then rests inside the invisible 9pt blank fragment ABOVE
/// the title, rendering as a detached terracotta stroke at the canvas
/// top. Programmatic landings (cursor restore, reading flip-back) hop
/// 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 {
max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location)
}
func makeNSView(context: Context) -> NSScrollView { func makeNSView(context: Context) -> NSScrollView {
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests) tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests)
@@ -435,7 +458,13 @@ struct ProseTextView: NSViewRepresentable {
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude) tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
tv.textContainer?.widthTracksTextView = true tv.textContainer?.widthTracksTextView = true
tv.textContainer?.lineFragmentPadding = 24 tv.textContainer?.lineFragmentPadding = 24
tv.textContainerInset = NSSize(width: 0, height: 20) // #ui-r2 (sol#10/argon#19): top padding so the title anchors the
// page instead of floating against the chrome (r1: 20, r2: 40;
// #ui-r4 mercury#24: 46 — ~6pt more clearance from the toolbar
// hairline). The typewriter inset machinery overwrites this on
// its own syncs — that stays untouched; this is the open-state
// anchor.
tv.textContainerInset = NSSize(width: 0, height: 46)
let scroll = NSScrollView() let scroll = NSScrollView()
scroll.documentView = tv scroll.documentView = tv
scroll.hasVerticalScroller = true scroll.hasVerticalScroller = true
@@ -482,6 +511,11 @@ struct ProseTextView: NSViewRepresentable {
var cursor = session.restoreCursor ?? PostStore.CursorState() var cursor = session.restoreCursor ?? PostStore.CursorState()
cursor.selectionLocation = min(max(0, cursor.selectionLocation), length) cursor.selectionLocation = min(max(0, cursor.selectionLocation), length)
cursor.selectionLength = min(max(0, cursor.selectionLength), length - cursor.selectionLocation) cursor.selectionLength = min(max(0, cursor.selectionLength), length - cursor.selectionLocation)
// #ui-r1: a caret restored into leading blanks renders as the
// detached stroke above the title — hop to the first content line.
if cursor.selectionLength == 0 {
cursor.selectionLocation = Self.caretPastLeadingBlanks(cursor.selectionLocation, in: tv.string)
}
tv.setSelectedRange(NSRange(location: cursor.selectionLocation, length: cursor.selectionLength)) tv.setSelectedRange(NSRange(location: cursor.selectionLocation, length: cursor.selectionLength))
// ponytail: TextKit lays out async — a sync scroll on a fresh mount // ponytail: TextKit lays out async — a sync scroll on a fresh mount
// lands short of the target (clamps to what's laid out). One runloop // lands short of the target (clamps to what's laid out). One runloop
@@ -502,7 +536,9 @@ struct ProseTextView: NSViewRepresentable {
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token { if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
context.coordinator.appliedCaretToken = hint.token context.coordinator.appliedCaretToken = hint.token
let length = (tv.string as NSString).length let length = (tv.string as NSString).length
let loc = min(max(0, hint.location), length) // #ui-r1: same leading-blank hop as the load restore — a reading
// flip-back must never park the caret above the first content line.
let loc = min(Self.caretPastLeadingBlanks(max(0, hint.location), in: tv.string), length)
tv.setSelectedRange(NSRange(location: loc, length: 0)) tv.setSelectedRange(NSRange(location: loc, length: 0))
// ponytail: same layout race as the cursor-restore scroll above — // ponytail: same layout race as the cursor-restore scroll above —
// this was the click-to-edit "always lands at top" defect: the sync // this was the click-to-edit "always lands at top" defect: the sync
+194 -66
View File
@@ -11,6 +11,7 @@
// 2px accent edge bar on the selected row. // 2px accent edge bar on the selected row.
// //
import AppKit
import SwiftUI import SwiftUI
/// The Posts destination: the workspace's full four-column layout /// The Posts destination: the workspace's full four-column layout
@@ -201,6 +202,14 @@ struct PostsLibraryColumn: View {
/// non-archived pieces. nil = not searching (sections render). /// non-archived pieces. nil = not searching (sections render).
@State private var query = "" @State private var query = ""
@State private var matches: [Post]? @State private var matches: [Post]?
/// r5 (argon#44, mercury#52, sol#37): focus state for the field's
/// accent ring. r8 (argon#6, mercury#12 — root cause found): the r6/r7
/// onAppear-unfocus could never work — the launch focus is AppKit
/// assigning the window's INITIAL first responder to its first text
/// input (this field), at window-become-key, AFTER onAppear. FocusState
/// merely mirrors that back as true. LaunchFocusReset (below) resigns
/// it at the first become-key; from then on only the user drives this.
@FocusState private var searchFocused: Bool
private var trimmedQuery: String { private var trimmedQuery: String {
query.trimmingCharacters(in: .whitespacesAndNewlines) query.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -261,9 +270,18 @@ struct PostsLibraryColumn: View {
} }
} }
} label: { } label: {
HStack(alignment: .firstTextBaseline, spacing: 8) { // r7 (mercury#18, argon#12 — TWO-AXIS ladder,
// the r6 four-step collapse undone): the
// head ROW leads at the column's PRIMARY
// inset (x14) — chevron glyph in a 14pt slot
// — and every nested CONTENT shares the one
// indent step (x28): head text, group
// labels, and the rows' inner text. No third
// or fourth x-axis exists in the column.
HStack(alignment: .firstTextBaseline, spacing: 0) {
Image(systemName: "chevron.down") Image(systemName: "chevron.down")
.font(.system(size: 9, weight: .semibold)) .font(.system(size: 10, weight: .semibold))
.frame(width: 14, alignment: .leading)
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
Text(project) Text(project)
@@ -294,6 +312,9 @@ struct PostsLibraryColumn: View {
} }
} }
.frame(width: DesignTokens.libraryWidth) .frame(width: DesignTokens.libraryWidth)
// r8 (argon#6, mercury#12): the focus-rider replaces the r6/r7
// onAppear-unfocus — see LaunchFocusReset below for the mechanism.
.background(LaunchFocusReset())
.sheet(item: $renamingPost) { post in .sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home) model.rename(post, to: title, home: home)
@@ -320,7 +341,7 @@ struct PostsLibraryColumn: View {
} }
try? await Task.sleep(for: .milliseconds(250)) try? await Task.sleep(for: .milliseconds(250))
guard !Task.isCancelled else { return } guard !Task.isCancelled else { return }
let found = await Self.search( let found = await librarySearch(
candidates: model.posts.filter { !$0.isArchived }, candidates: model.posts.filter { !$0.isArchived },
matching: trimmedQuery, matching: trimmedQuery,
home: home, home: home,
@@ -330,28 +351,6 @@ struct PostsLibraryColumn: View {
} }
} }
/// #144: the title+body scan — a thin mount for the pure
/// `LibrarySearch` seam (title matches first, stable partition, both
/// halves keep the scan's Finder order; body via readBody — frontmatter
/// never searched), pinned by MuseionTests/LibrarySearchTests.swift.
/// The reader's per-piece cancellation check stops a superseded sweep's
/// body reads between files; the in-memory title walk itself completes
/// cheaply and the caller's guard discards its result.
///
/// ponytail: full-body re-read per sweep (folder(of:) re-walked per
/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex
/// posture); a PostScanCache-style body memo if it ever measures hot.
private nonisolated static func search(
candidates: [Post],
matching trimmed: String,
home: URL,
) async -> [Post] {
LibrarySearch.results(for: trimmed, in: candidates) { post in
guard !Task.isCancelled else { return nil }
return PostStore.readBody(id: post.id, home: home)
}
}
/// One piece row + its context menu — sections and search results /// One piece row + its context menu — sections and search results
/// render the same row (#144: results carry the full menu too). /// render the same row (#144: results carry the full menu too).
private func postRow(_ post: Post) -> some View { private func postRow(_ post: Post) -> some View {
@@ -378,18 +377,29 @@ struct PostsLibraryColumn: View {
} }
/// Pass-State groups inside one project (`.vB .group-label`: smaller, /// Pass-State groups inside one project (`.vB .group-label`: smaller,
/// softer, indented under the section head). /// softer, indented under the section head). r2: the label binds to
/// its FIRST row (bottom 1 + stack 4) — it floated closer to the
/// preceding row than to its own children.
private func passStateGroups(_ pieces: [Post]) -> some View { private func passStateGroups(_ pieces: [Post]) -> some View {
ForEach(Post.PassState.allCases, id: \.self) { state in ForEach(Post.PassState.allCases, id: \.self) { state in
let grouped = pieces.filter { $0.passState == state } let grouped = pieces.filter { $0.passState == state }
if !grouped.isEmpty { if !grouped.isEmpty {
Text(state.rawValue.uppercased()) // mercury#53 (r5): display-only normalization — the stored
.font(.system(size: 10, design: DesignTokens.mono)) // rawValues keep their hyphen ("Pass-1 Done"); the rendered
// label uses the space form so it matches the Pass 1 / Pass 2
// vocabulary everywhere else.
Text(state.rawValue.uppercased().replacingOccurrences(of: "-", with: " "))
.font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
.kerning(0.6) .kerning(0.6)
.foregroundStyle(DesignTokens.muted.opacity(0.8)) // r6 (sol#6/21 — contrast final): group labels are
.padding(.horizontal, 22) // informational meta — FULL muted ink, no wash.
.padding(.top, 8) .foregroundStyle(DesignTokens.muted)
.padding(.bottom, 5) // r6 ladder: full muted ink. r7 two-axis: x28 — the ONE
// indent step, shared with the head text and the row
// cards' inner content.
.padding(.leading, 28)
.padding(.top, 10)
.padding(.bottom, 1)
ForEach(grouped) { post in ForEach(grouped) { post in
postRow(post) postRow(post)
} }
@@ -397,15 +407,25 @@ struct PostsLibraryColumn: View {
} }
} }
/// #144: the field row + bottom hairline (the pane-head voice). /// #144 + mercury#54 (r4): a real field surface — surface fill + hairline
/// border on the column's chrome, taller than a text row; the placeholder
/// 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 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 { private var searchField: some View {
HStack(spacing: 6) { HStack(spacing: 6) {
Image(systemName: "magnifyingglass") Image(systemName: "magnifyingglass")
.font(.system(size: 11)) .font(.system(size: 11))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
TextField("Search posts", text: $query) TextField("Search posts", text: $query, prompt: Text("Search posts").foregroundStyle(DesignTokens.muted))
.textFieldStyle(.plain) .textFieldStyle(.plain)
.font(.system(size: 12)) .font(.system(size: 12))
.focused($searchFocused)
.tint(DesignTokens.accent)
if isSearching { if isSearching {
Button { Button {
query = "" query = ""
@@ -417,11 +437,27 @@ struct PostsLibraryColumn: View {
.accessibilityLabel("Clear search") .accessibilityLabel("Clear search")
} }
} }
.padding(.horizontal, 12) .padding(.horizontal, 10)
.padding(.vertical, 7) .padding(.vertical, 8)
.overlay(alignment: .bottom) { .background(
Rectangle().fill(DesignTokens.border).frame(height: 1) RoundedRectangle(cornerRadius: 8)
} .fill(DesignTokens.surface)
.overlay(
// r8 (argon#6, mercury#12): quiet focus — accent at 0.6,
// one step down from full strength.
RoundedRectangle(cornerRadius: 8)
.strokeBorder(
searchFocused ? DesignTokens.accent.opacity(0.6) : DesignTokens.border,
lineWidth: 1,
),
),
)
// r7 (mercury#18, argon#12 — two-axis ladder): the box spans the
// FULL padded column width at the PRIMARY inset — leading 14
// (aligned with the 'Posts' header text) to trailing 14 — the
// same edges the row cards lead at.
.padding(.horizontal, 14)
.padding(.vertical, 8)
} }
/// Flat results, title matches first (stable partition — both halves /// Flat results, title matches first (stable partition — both halves
@@ -430,12 +466,15 @@ struct PostsLibraryColumn: View {
ScrollView { ScrollView {
LazyVStack(alignment: .leading, spacing: 4) { LazyVStack(alignment: .leading, spacing: 4) {
Text("\(found.count) \(found.count == 1 ? "match" : "matches")") Text("\(found.count) \(found.count == 1 ? "match" : "matches")")
.font(.system(size: 10, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.kerning(0.6) .kerning(0.6)
.foregroundStyle(DesignTokens.muted.opacity(0.8)) // r6: full muted ink; r7 two-axis: x28 — the indent
.padding(.horizontal, 14) // step, heading the flat result list exactly where
// group labels head their sections.
.foregroundStyle(DesignTokens.muted)
.padding(.leading, 28)
.padding(.top, 12) .padding(.top, 12)
.padding(.bottom, 5) .padding(.bottom, 1)
ForEach(found) { post in ForEach(found) { post in
postRow(post) postRow(post)
} }
@@ -471,6 +510,80 @@ struct PostsLibraryColumn: View {
} }
} }
/// #144: the title+body scan — a thin mount for the pure
/// `LibrarySearch` seam (title matches first, stable partition, both
/// halves keep the scan's Finder order; body via readBody — frontmatter
/// never searched), pinned by MuseionTests/LibrarySearchTests.swift.
/// The reader's per-piece cancellation check stops a superseded sweep's
/// body reads between files; the in-memory title walk itself completes
/// cheaply and the caller's guard discards its result. File scope since
/// r6 (PostsLibraryColumn hit its type-body ceiling).
///
/// ponytail: full-body re-read per sweep (folder(of:) re-walked per
/// piece — same unbounded-read ceiling as Post.scan, LearningsIndex
/// posture); a PostScanCache-style body memo if it ever measures hot.
private nonisolated func librarySearch(
candidates: [Post],
matching trimmed: String,
home: URL,
) async -> [Post] {
LibrarySearch.results(for: trimmed, in: candidates) { post in
guard !Task.isCancelled else { return nil }
return PostStore.readBody(id: post.id, home: home)
}
}
/// r8 (argon#6, mercury#12 — the launch auto-focus ROOT CAUSE, killed at
/// the source): the search field is the window's first — and at launch,
/// only — text input, and AppKit assigns the window's initial first
/// responder to it when the window becomes key. That happens AFTER
/// onAppear, so the r6/r7 `searchFocused = false` writes were always
/// overridden (FocusState mirrors the assignment back as true: terracotta
/// ring + caret, the strongest element on screen). This invisible rider
/// rides the library column and, at the window's FIRST become-key,
/// resigns focus back to the window itself (`makeFirstResponder(nil)` —
/// the neutral state; nothing gains focus instead). ONCE per process: a
/// pane-switch remount must never steal a focus the user set on return.
/// The second, next-runloop resign covers an assignment that lands after
/// the notification (the PostEditorView layout-race precedent).
private struct LaunchFocusReset: NSViewRepresentable {
/// Process-wide once-flag — launch is a once-per-process event.
private static var hasRun = false
final class RiderView: NSView {
private var keyObserver: NSObjectProtocol?
override func viewDidMoveToWindow() {
if let keyObserver {
NotificationCenter.default.removeObserver(keyObserver)
}
keyObserver = nil
guard let window else { return }
keyObserver = NotificationCenter.default.addObserver(
forName: NSWindow.didBecomeKeyNotification,
object: window,
queue: .main,
) { _ in
MainActor.assumeIsolated {
// The observer is scoped to `window` (object:), so the
// notification carries nothing we don't already hold —
// reading `note` here would cross a Sendable boundary.
guard !LaunchFocusReset.hasRun else { return }
LaunchFocusReset.hasRun = true
window.makeFirstResponder(nil)
DispatchQueue.main.async { window.makeFirstResponder(nil) }
}
}
}
}
func makeNSView(context _: Context) -> RiderView {
RiderView()
}
func updateNSView(_: RiderView, context _: Context) {}
}
/// #108: Move to Project ask — radio list of the non-archived projects, /// #108: Move to Project ask — radio list of the non-archived projects,
/// default = the piece's current project. Matches RenamePostSheet's shape. /// default = the piece's current project. Matches RenamePostSheet's shape.
struct MoveToProjectSheet: View { struct MoveToProjectSheet: View {
@@ -559,7 +672,8 @@ struct RenamePostSheet: View {
} }
} }
/// One post row per the export: title, Pass State + Origin in mono 11. /// One post row per the export: title + origin-only mono-11 meta (the Pass
/// State rides the uppercase group label above; it stays in the a11y label).
/// #108 (variant B): 2px accent edge bar on the leading side when selected /// #108 (variant B): 2px accent edge bar on the leading side when selected
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`, /// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the /// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the
@@ -573,17 +687,18 @@ struct LibraryPostRow: View {
var body: some View { var body: some View {
// `.vB .post-row { border-left: 2px solid transparent; // `.vB .post-row { border-left: 2px solid transparent;
// border-radius: 0 8px 8px 0 }` — every row: leading corners square // border-radius: 0 8px 8px 0 }` — every row: leading corners square
// (the 2px strip below), trailing rounded 8. Only the strip's COLOR // (the 2px strip below), trailing rounded 8. Only the strip's
// changes on selection. // VISIBILITY changes on selection.
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8)) let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
return Button(action: select) { return Button(action: select) {
HStack(spacing: 0) { HStack(spacing: 0) {
// `.vB .post-row { border-left: 2px solid transparent }` — // The leading strip is always 2px wide so hover/selection
// the leading strip is always 2px wide so hover/selection // never shifts the title. r6 (mercury#49/52, argon#13):
// never shifts the title. // the shared SelectedRowStrip capsule — accent, radius-1
Rectangle() // ends, vertically inset 6pt (was 3) so it sits INSIDE
.fill(selected ? DesignTokens.accent : .clear) // the card, never pasted on its square leading edge.
.frame(width: 2) SelectedRowStrip()
.opacity(selected ? 1 : 0)
VStack(alignment: .leading, spacing: 5) { VStack(alignment: .leading, spacing: 5) {
HStack(alignment: .firstTextBaseline, spacing: 0) { HStack(alignment: .firstTextBaseline, spacing: 0) {
Text(post.title) Text(post.title)
@@ -592,19 +707,24 @@ struct LibraryPostRow: View {
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
} }
} }
.font(.callout.weight(.semibold)) // ui-polish r8: serif-13 per the row contract — `.callout`
// was the system sans design (the r6/r7 councils pixel-
// verified sans glyphs on the Archive rows).
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(1) .lineLimit(1)
.truncationMode(.tail) .truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
HStack { // Origin only — the Pass State already rides the uppercase
Text(post.passState.rawValue) // group label above (it stays in the accessibility label).
Text(post.origin.rawValue) // r7: the status micro-label sits INSIDE the row's content
} // padding — same x as the title, never flush with the edge.
.font(.system(size: 11, design: DesignTokens.mono)) Text(post.origin.rawValue)
.foregroundStyle(DesignTokens.muted) .font(.system(size: 11, design: DesignTokens.mono))
.frame(maxWidth: .infinity, alignment: .leading) .foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
} }
.padding(10) .padding(.horizontal, 12)
.padding(.vertical, 10)
} }
.clipShape(shape) .clipShape(shape)
} }
@@ -612,14 +732,22 @@ struct LibraryPostRow: View {
.foregroundStyle(DesignTokens.foreground) .foregroundStyle(DesignTokens.foreground)
.background { .background {
if selected || hover { if selected || hover {
// r8 (mercury#11): the selected row DROPS its gray outline —
// fill + accent capsule read as ONE shape; stacking fill +
// outline + capsule competed. Hover keeps its borderless
// 0.06 wash exactly as before.
shape shape
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06)) .fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
.overlay(
shape.strokeBorder(selected ? DesignTokens.border : .clear),
)
} }
} }
.padding(.horizontal, 8) // r7 (mercury#18, argon#12 — two-axis ladder): the row CARD
// leads at the PRIMARY inset (x14, the 'Posts' header text's
// edge); its INNER content (title + status micro-label, strip
// 2 + padding 12) lands at x28 — the ONE indent step, shared
// with the head text and the group labels. No other x-axis
// exists in the column. Vertical padding stays the content
// VStack's constant 10 whether or not the row shows its strip.
.padding(.horizontal, 14)
.onHover { hover = $0 } .onHover { hover = $0 }
// help sits on the row — the ✳ span isn't individually hoverable in // help sits on the row — the ✳ span isn't individually hoverable in
// SwiftUI (prototype: `title="outline"` on the star). // SwiftUI (prototype: `title="outline"` on the star).
+57 -4
View File
@@ -118,12 +118,20 @@ nonisolated enum ProsePresenter {
if range.location > 0, out.string.contains("```") || out.string.contains("~~~") { if range.location > 0, out.string.contains("```") || out.string.contains("~~~") {
inFence = fenceState(nsText, upTo: range.location) inFence = fenceState(nsText, upTo: range.location)
} }
// Title detection (#ui-r1): the title is the document's FIRST
// non-blank line (Post.scan's rule — blank lines above it are
// skipped, so paragraph edits anchor past 0 and a location-0 test
// would miss them). Absolute position match: whichever range is
// styled, the line sitting at the title location takes the title
// step; lines outside the range keep what the full pass gave them.
let titleLocation = firstContentLocation(nsText)
for line in contentLines(nsText, in: range) { for line in contentLines(nsText, in: range) {
let kind = classify(line.text, inFence: inFence) let kind = classify(line.text, inFence: inFence)
if kind == .fence { if kind == .fence {
inFence.toggle() inFence.toggle()
} }
styleLine(out, line: line, kind: kind) let isTitle = titleLocation == line.content.location && kind == .body
styleLine(out, line: line, kind: kind, isTitle: isTitle)
} }
} }
@@ -171,9 +179,9 @@ nonisolated enum ProsePresenter {
return inFence return inFence
} }
private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind) { private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind, isTitle: Bool = false) {
guard line.full.length > 0 else { return } guard line.full.length > 0 else { return }
out.setAttributes(attributes(for: kind), range: line.full) out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full)
let dim = ProseTypography.codeAttributes // codeFont + syntaxColor let dim = ProseTypography.codeAttributes // codeFont + syntaxColor
switch kind { switch kind {
case .heading1, .heading2, .heading3, .heading4Plus: case .heading1, .heading2, .heading3, .heading4Plus:
@@ -189,7 +197,31 @@ nonisolated enum ProsePresenter {
} }
case .listMarker: case .listMarker:
if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 { if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 {
out.addAttributes(dim, range: shifted(marker, into: line.content)) out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content))
// Hanging indent (#ui-r1, sol#13; #ui-r2 argon#53 flush
// fix): wrapped list lines align with the item's text, not
// the paragraph margin — the marker prefix (leading
// whitespace + "- "/"1. ") sets headIndent, mirroring
// reading.css's hanging lists (padding-left + outside
// markers). Nested items hang at their own prefix width.
// The prefix is measured in the EXACT attributes it
// renders in (listMarkerAttributes — the line's face and
// size), so the continuation lands flush; a different
// measuring face drifts per-glyph (~4pt left in r1).
// ponytail: a tab in the prefix measures at the default tab
// stop; the corpus uses spaces — widen if tabbed lists drift.
let prefix = String(line.text.prefix(NSMaxRange(marker)))
let indent = NSAttributedString(
string: prefix,
attributes: ProseTypography.listMarkerAttributes,
).size().width
let hanging = NSMutableParagraphStyle()
hanging.setParagraphStyle(paragraph(.body))
hanging.headIndent = indent
// #ui-r7 sol#29: inter-item rhythm (reading.css list margins)
// — before-space only, the CSS block has no bottom margin.
hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore
out.addAttribute(.paragraphStyle, value: hanging, range: line.full)
} }
case .syntaxOnly: case .syntaxOnly:
if line.content.length > 0 { if line.content.length > 0 {
@@ -442,3 +474,24 @@ nonisolated extension Range<String.Index> {
return lo ..< hi return lo ..< hi
} }
} }
// MARK: - Title detection (#ui-r1 — file scope: the enum body sits at its ceiling)
nonisolated extension ProsePresenter {
/// UTF-16 start of the first non-blank line, or nil when the whole
/// buffer is blank. Walks only the leading blank lines. Post.scan
/// skips leading blanks to find the title; the editor styles the same
/// line the library shows.
static func firstContentLocation(_ nsText: NSString) -> Int? {
var lineStart = 0
while lineStart < nsText.length {
let line = nsText.lineRange(for: NSRange(location: lineStart, length: 0))
let lineText = nsText.substring(with: line)
if !lineText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return line.location
}
lineStart = NSMaxRange(line)
}
return nil
}
}
+83 -1
View File
@@ -48,8 +48,20 @@ nonisolated enum ProseTypography {
/// h4+ floors at bold body (CSS h4–h6). /// h4+ floors at bold body (CSS h4–h6).
nonisolated(unsafe) static let headingBoldFont: NSFont = NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask) nonisolated(unsafe) static let headingBoldFont: NSFont = NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask)
/// Document title face (#ui-r2, sol#10/argon#19): the SERIF body face
/// at the existing title rung — FACE change only, the 22pt step stays.
/// The sans heading face read as chrome disconnected from the serif
/// document; the title speaks the document's own voice now (the
/// workspace contract's --font-display is serif).
nonisolated(unsafe) static let titleFont: NSFont = NSFontManager.shared.convert(
bodyFont,
toSize: heading2Size,
)
/// Code slot (inline code, fenced blocks, editing syntax dim). /// Code slot (inline code, fenced blocks, editing syntax dim).
nonisolated(unsafe) static let codeFont: NSFont = .init(name: "UbuntuMonoNFM", size: codeSize) ?? NSFont.monospacedSystemFont(ofSize: codeSize, weight: .regular) nonisolated(unsafe) static let codeFont: NSFont =
.init(name: "UbuntuMonoNFM", size: codeSize)
?? NSFont.monospacedSystemFont(ofSize: codeSize, weight: .regular)
/// Blank source lines at 9pt (#77 half-height separators). /// Blank source lines at 9pt (#77 half-height separators).
nonisolated(unsafe) static let blankFont: NSFont = NSFontManager.shared.convert(bodyFont, toSize: blankSize) nonisolated(unsafe) static let blankFont: NSFont = NSFontManager.shared.convert(bodyFont, toSize: blankSize)
@@ -111,6 +123,33 @@ nonisolated enum ProseTypography {
] ]
} }
/// Document title (#ui-r1, sol#12/argon#30; #ui-r2 sol#10/argon#19): the
/// open document's first non-blank body line (Post.scan's title rule)
/// takes the 22pt title rung in the SERIF body face — face change only,
/// the rung size is an EXISTING scale step, never a new size. #ui-r2
/// spacing: after-space measured (NSLayoutManager ink bounds) so the
/// title→body ink gap over the canonical `Title\n\nbody` shape lands
/// 24–28pt — r1's heading after-space (30) plus the blank separator
/// read as a ~65pt void. No before-space at document start.
static var titleAttributes: [NSAttributedString.Key: Any] {
let style = NSMutableParagraphStyle()
style.setParagraphStyle(ProsePresenter.paragraph(.heading2))
style.paragraphSpacingBefore = 0 // no before-space at document start
style.paragraphSpacing = titleSpacing
return [
.font: titleFont, // the 22pt rung, serif body face
.foregroundColor: foregroundColor, // explicit ink — no black default
.paragraphStyle: style,
]
}
/// #ui-r4 (mercury#24/sol#40): 0 — the blank separator's own ~16pt
/// box carries the title→body gap. r4 probe (r4_title_gap_probe.swift):
/// ink 15.9pt / visual ≈30px at 0, vs r2's 25.9/~40 at 10 — judges
/// read the line boxes, not the ink. Floors at 0; the owner-calibrated
/// 9pt blank separator is the only further lever.
static let titleSpacing: CGFloat = 0
/// Outline rows (#109): the body face at its NATURAL line box — no CSS /// Outline rows (#109): the body face at its NATURAL line box — no CSS
/// 1.8 lineHeightMultiple. The outliner chrome (27pt bullet cells) assumes /// 1.8 lineHeightMultiple. The outliner chrome (27pt bullet cells) assumes
/// one row height; a live-row fragment inflated by the prose multiple /// one row height; a live-row fragment inflated by the prose multiple
@@ -130,6 +169,49 @@ nonisolated enum ProseTypography {
] ]
} }
/// List marker glyph (#ui-r5, argon#11): the raw ASCII hyphen renders
/// MUTED-SMALL. The judge's ideal — substituting a typographic en-dash
/// or bullet glyph — cannot ride TextKit attributes: any glyph swap
/// means swapping STRING bytes, and the plain store IS the document
/// (`storage.string` is what saves, ADR-0010 mode B). Muted-small is
/// the sanctioned fallback: the marker reads as chrome, not body text.
/// The hanging indent still measures the prefix in THESE attributes,
/// so wrapped continuations stay flush (r5_list_check.swift pins it).
static let listMarkerSize: CGFloat = 13
nonisolated(unsafe) static let listMarkerFont: NSFont = NSFontManager.shared.convert(
bodyFont,
toSize: listMarkerSize,
)
/// List markers render in a SMALLER cut of the LINE's own face
/// (#ui-r2 argon#53 → #ui-r5 argon#11 muted-small): the hanging indent
/// is measured in the EXACT attributes the prefix renders in, so
/// wrapped continuations align flush with the first line's text —
/// change the font here and the measurement follows automatically.
/// Heading hashes and quote markers stay syntax-dim; only list markers
/// take this stack.
static var listMarkerAttributes: [NSAttributedString.Key: Any] {
[
.font: listMarkerFont,
.foregroundColor: mutedColor,
]
}
/// #ui-r7 (sol#29): inter-item rhythm — reading.css gives the list
/// BLOCK a top margin (--para-space) and li margin 0; the editor's
/// tight lists borrow that as before-space on every list paragraph
/// (item-above-item reads one gap, no after-space — CSS margin-bottom
/// is 0). Judge band 4–6pt; 5 is the midpoint.
static let listSpacingBefore: CGFloat = 5
/// #ui-r8 (argon#7): the outliner's branch rhythm — the ONE separation
/// a branch start and a nested block's close share. Derived from the
/// r7 machinery (×2 = r5's branch separation, 10): both surfaces ride
/// one paragraph-spacing ladder, no per-view literals — recalibrating
/// listSpacingBefore moves the outline with it.
static let outlineBranchSpacing: CGFloat = listSpacingBefore * 2
/// #115: fold-hidden lines. The buffer keeps every byte (mode B — folding /// #115: fold-hidden lines. The buffer keeps every byte (mode B — folding
/// is rendering, never a text edit); hidden scopes style to near-zero /// is rendering, never a text edit); hidden scopes style to near-zero
/// height so the lines vanish (spike-verified: 14pt line → ~0). The text /// height so the lines vanish (spike-verified: 14pt line → ~0). The text
+388 -90
View File
@@ -11,11 +11,13 @@
// remapped onto the two-color palette per the locked contract // remapped onto the two-color palette per the locked contract
// (ref/prototypes/wf154-mentor-pane-prototype.html). Speaker-act rows // (ref/prototypes/wf154-mentor-pane-prototype.html). Speaker-act rows
// render as speech (right-aligned terracotta capsule / full-width serif // render as speech (right-aligned terracotta capsule / full-width serif
// prose, markdown parsed at flush, verbatim while streaming — the Vivarium // markdown parsed at flush, verbatim while streaming — the Vivarium
// #97 pattern); every other text row is the system's quiet mono voice on // #97 pattern); every other text row is the system's quiet mono voice on
// the fg-wash 6% card. Composer: surface input, accent Send flipping to a // the fg-wash 6% card. Round-2 polish: interruption/error status rows
// terracotta-outlined Stop, floating liveness chip (streaming only), the // carry a restrained terracotta accent. Composer: surface input, accent
// debug toggle at the trailing edge. // Send flipping to a terracotta-outlined Stop, floating liveness chip
// (streaming only), the debug toggle hover-revealed at the trailing
// edge — zero visible footprint at rest.
// //
import SwiftUI import SwiftUI
@@ -44,12 +46,25 @@ struct SessionTranscriptView: View {
@State private var pendingKeep: PendingKeep? @State private var pendingKeep: PendingKeep?
/// The freeform draft (#30: shared input rail). /// The freeform draft (#30: shared input rail).
@State private var draft = "" @State private var draft = ""
/// Round-2 polish (argon#21/sol#43/mercury#58): the debug toggle is
/// hover-revealed — true while the pointer is over the composer row.
@State private var composerHover = false
/// #155: the pane's live width — the user capsule caps at 85% of the /// #155: the pane's live width — the user capsule caps at 85% of the
/// CONTENT column (width − 2×16 transcript pads). Seeded to the mentor /// MEASURE column (width − 2×16 transcript pads). Seeded to the mentor
/// column so the first frame is right there; the Sessions pane's wider /// column so the first frame is right there; the Sessions pane's wider
/// column corrects it on the first geometry pass. /// column corrects it on the first geometry pass.
@State private var paneWidth: CGFloat = 356 @State private var paneWidth: CGFloat = 356
/// Round-1 polish (argon#4/mercury#43): the reading measure —
/// conversational content caps at a comfortable ~720pt, centered in the
/// (possibly ~830pt+) Sessions column. The mentor column (356) caps
/// naturally. Scroll anchoring untouched (#24 bottom-anchor contract).
private static let measureCap: CGFloat = 720
private var measureWidth: CGFloat {
min(paneWidth, Self.measureCap)
}
private struct PendingKeep: Identifiable { private struct PendingKeep: Identifiable {
let rowID: UUID let rowID: UUID
let candidate: ResearchCandidate let candidate: ResearchCandidate
@@ -58,9 +73,10 @@ struct SessionTranscriptView: View {
} }
} }
/// The user capsule's cap — 85% of the visible column (contract ruling). /// The user capsule's cap — 85% of the visible MEASURE column
/// (contract ruling, pads included).
private var capsuleCap: CGFloat { private var capsuleCap: CGFloat {
max(0, (paneWidth - 32) * 0.85) max(0, (measureWidth - 32) * 0.85)
} }
var body: some View { var body: some View {
@@ -107,11 +123,15 @@ struct SessionTranscriptView: View {
} }
private var transcript: some View { private var transcript: some View {
ScrollView { let visible = model.rows.filter { showsDebugRows || Self.isWritingRow($0) }
return ScrollView {
// Contract turn rhythm: 18px between turns; pads 18/16/12. // Contract turn rhythm: 18px between turns; pads 18/16/12.
// Round-7 (mercury#21/argon#39): rows render with their
// PREDECESSOR in reach — the warning-styling and gap rules
// below are pairwise, not per-row.
LazyVStack(alignment: .leading, spacing: 18) { LazyVStack(alignment: .leading, spacing: 18) {
ForEach(model.rows.filter { showsDebugRows || Self.isWritingRow($0) }) { row in ForEach(Array(visible.enumerated()), id: \.element.id) { pair in
rowView(row) rowView(pair.element, previous: pair.offset > 0 ? visible[pair.offset - 1] : nil)
} }
if showsDebugRows, !model.streamingThought.isEmpty { if showsDebugRows, !model.streamingThought.isEmpty {
// Live thinking: open while it runs (spinner toggle), // Live thinking: open while it runs (spinner toggle),
@@ -124,12 +144,19 @@ struct SessionTranscriptView: View {
agentProse(Text(verbatim: model.streamingText)) agentProse(Text(verbatim: model.streamingText))
} }
} }
.padding(EdgeInsets(top: 18, leading: 16, bottom: 12, trailing: 16)) .padding(EdgeInsets(top: 18, leading: 16, bottom: 16, trailing: 16))
.frame(maxWidth: .infinity, alignment: .leading) // Round-1 polish: the reading measure — content centers in a
// ≤720pt column (argon#4/mercury#43); anchor untouched (#24).
.frame(maxWidth: measureWidth)
.frame(maxWidth: .infinity, alignment: .center)
} }
// #24 fix: programmatic scrollTo raced the growing lazy rows and // #24 fix: programmatic scrollTo raced the growing lazy rows and
// mislanded at the TOP; the native bottom anchor needs no scroll code. // mislanded at the TOP; the native bottom anchor needs no scroll code.
.defaultScrollAnchor(.bottom) .defaultScrollAnchor(.bottom)
// Round-1 polish (argon#27/mercury#61): viewport clearance — a row
// sliced mid-scroll never rides the header divider (the content pad
// above only shows at full scroll-up).
.padding(.top, 14)
} }
/// The writing-session filter: prose + card events stay; raw rows and /// The writing-session filter: prose + card events stay; raw rows and
@@ -147,16 +174,56 @@ struct SessionTranscriptView: View {
/// onto the contract's three voices. Everything else (refusals, pass /// onto the contract's three voices. Everything else (refusals, pass
/// kick-off labels, reveals) is the system's mono voice. Static, /// kick-off labels, reveals) is the system's mono voice. Static,
/// nonisolated — pure, testable from any context. /// nonisolated — pure, testable from any context.
/// Round-1 polish: engine-emitted operational notices (interruptions)
/// and replayed pass kick-offs are STATUS, not conversation — they map
/// to the system voice too (never serif prose, never a user capsule).
nonisolated static func speaker(of text: String) -> Speaker { nonisolated static func speaker(of text: String) -> Speaker {
if text.hasPrefix("Mentor: ") { if text.hasPrefix("Mentor: ") {
return .agent let body = String(text.dropFirst("Mentor: ".count))
return body.hasPrefix("Operation interrupted:") ? .system : .agent
} }
if text.hasPrefix("You: ") { if text.hasPrefix("You: ") {
return .user return isPassKickoff(String(text.dropFirst("You: ".count))) ? .system : .user
} }
return .system return .system
} }
/// Round-1 polish: a replayed pass kick-off — the engine replays the
/// pass prompt as a user turn whose body opens with PassContext's fixed
/// "Pass Pass N — <level>." line. Static, nonisolated — pure.
nonisolated static func isPassKickoff(_ body: String) -> Bool {
body.hasPrefix("Pass Pass ")
}
/// Round-1 polish: the system row's display text — a replayed pass
/// kick-off shows its FIRST LINE only (the full engine prompt stays out
/// of the UI); every other status row renders verbatim. Static,
/// nonisolated — pure, testable from any context.
///
/// Round-2 polish (r1 regression): PassContext's first line already
/// carries "Pass " + the pass name, so the raw line reads "Pass Pass
/// 2 — …" — collapse the doubled leading "Pass Pass N" to "Pass N".
nonisolated static func statusDisplayText(_ text: String) -> String {
guard text.hasPrefix("You: ") else { return text }
let body = text.dropFirst("You: ".count)
guard isPassKickoff(String(body)) else { return text }
let line = String(body.prefix(while: { $0 != "\n" }))
guard line.hasPrefix("Pass Pass ") else { return line }
return "Pass " + line.dropFirst("Pass Pass ".count)
}
/// Round-2 polish (argon#24/mercury#60/sol#9): operational warnings —
/// engine-emitted interruptions, connection losses, and the model's
/// failure rows — get the restrained terracotta accent in the status
/// voice. Refusals and cancellations stay neutral (they are outcomes,
/// not failures). Static, nonisolated — pure, test-pinnable.
nonisolated static func isWarningStatus(_ text: String) -> Bool {
let body = text.hasPrefix("Mentor: ") ? String(text.dropFirst("Mentor: ".count)) : text
return body.hasPrefix("Operation interrupted")
|| body.hasPrefix("connection lost")
|| body.contains(" failed — ")
}
/// The three contract voices for a text row. /// The three contract voices for a text row.
nonisolated enum Speaker { nonisolated enum Speaker {
case agent case agent
@@ -186,7 +253,7 @@ struct SessionTranscriptView: View {
} }
@ViewBuilder @ViewBuilder
private func rowView(_ row: SessionRow) -> some View { private func rowView(_ row: SessionRow, previous: SessionRow?) -> some View {
switch row.content { switch row.content {
case let .text(text): case let .text(text):
switch Self.speaker(of: text) { switch Self.speaker(of: text) {
@@ -195,7 +262,20 @@ struct SessionTranscriptView: View {
case .user: case .user:
userCapsule(String(text.dropFirst("You: ".count))) userCapsule(String(text.dropFirst("You: ".count)))
case .system: case .system:
statusBox(text) // Round-7 (mercury#21): the full warning treatment (tinted
// fill + border) renders ONLY while this row is the
// transcript's last meaningful row — an older interruption
// above a completed reply is history.
// Round-8 (argon#8): a historical warning keeps the
// terracotta ink + glyph (see `statusBox`) — distinct,
// just not shouting.
let current = Self.isWarningStatus(text) && isLastMeaningfulRow(row)
statusBox(Self.statusDisplayText(text), current: current)
// Round-7 (argon#39): 8pt of air when the warning
// banner directly follows the pass kick-off pill —
// at the stack's uniform 18pt the pair read as one
// fused block.
.padding(.top, current && Self.isKickoffPill(previous) ? 8 : 0)
} }
case let .thought(text): case let .thought(text):
// #24 dogfood fix: collapsed — a pass's thought stream runs to // #24 dogfood fix: collapsed — a pass's thought stream runs to
@@ -230,13 +310,15 @@ struct SessionTranscriptView: View {
} }
/// User turns: the right-aligned capsule — terracotta wash 14% fill, /// User turns: the right-aligned capsule — terracotta wash 14% fill,
/// fg ink, sans 13/1.5, pads 16/12, radius 12/12/2/12 (the 2pt tail /// fg ink, sans 14/1.5 (Round-2, mercury#62 partial: one point up;
/// bottom-trailing), capped at 85% of the visible column. /// lineSpacing re-derived from the same CSS 1.5 math — pads 16/12
/// untouched), radius 12/12/2/12 (the 2pt tail bottom-trailing),
/// capped at 85% of the visible column.
private func userCapsule(_ text: String) -> some View { private func userCapsule(_ text: String) -> some View {
Text(text) Text(text)
.font(DesignTokens.concourse(13)) .font(DesignTokens.concourse(14))
.foregroundStyle(DesignTokens.foreground) .foregroundStyle(DesignTokens.foreground)
.lineSpacing(3.7) // CSS 1.5 (19.5 − Concourse's natural 15.8) .lineSpacing(4) // CSS 1.5 (21 − Concourse's scaled natural ≈ 17)
.textSelection(.enabled) .textSelection(.enabled)
.padding(.horizontal, 16) .padding(.horizontal, 16)
.padding(.vertical, 12) .padding(.vertical, 12)
@@ -257,16 +339,36 @@ struct SessionTranscriptView: View {
} }
/// The quiet system voice: mono 11/1.5 muted on the fg-wash card — /// The quiet system voice: mono 11/1.5 muted on the fg-wash card —
/// refusals, pass kick-off labels, reveals. Fit-content width. /// refusals, pass kick-off labels, reveals.
private func statusBox(_ text: String) -> some View { /// Round-6 (mercury#5/sol#10/argon#15): warning rows are their own
Text(text) /// component — warning glyph, structured headline + muted detail.
.font(DesignTokens.ubuntuMono(11)) /// Round-7 (mercury#21): the full treatment (fill + border) renders
.foregroundStyle(DesignTokens.muted) /// only when the caller passes `current` (last meaningful row).
.lineSpacing(5.5) // CSS 1.5 /// Round-8 (argon#8/mercury#16): a warning row ALWAYS carries the
.textSelection(.enabled) /// terracotta ink + glyph — historical ones on the plain wash pill —
.padding(.horizontal, 12) /// and ALL status rows share one width treatment: the transcript
.padding(.vertical, 10) /// column's full width, leading edge aligned (fit-content pills and
.background(washCard) /// full-width banners read as two glued regions).
@ViewBuilder
private func statusBox(_ text: String, current: Bool = false) -> some View {
if Self.isWarningStatus(text) {
let parts = Self.warningParts(text)
WarningStatusRow(
headline: parts.headline,
detail: parts.detail.map(Self.calmDetail),
emphasized: current,
)
} else {
Text(text)
.font(DesignTokens.ubuntuMono(11))
.foregroundStyle(DesignTokens.muted)
.lineSpacing(5.5) // CSS 1.5
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(washCard)
}
} }
/// The card-fill ruling (owner, 2026-11-03): thinking cards, status /// The card-fill ruling (owner, 2026-11-03): thinking cards, status
@@ -356,7 +458,9 @@ struct SessionTranscriptView: View {
} }
private var dimmed: Double { private var dimmed: Double {
candidate.disposition == .pending ? 1 : 0.45 // Round-2 sweep: 0.45 broke the 0.75 informational floor —
// 0.75 still reads closed against the 1.0 pending card.
candidate.disposition == .pending ? 1 : 0.75
} }
private var washCard: some View { private var washCard: some View {
@@ -443,13 +547,133 @@ struct SessionTranscriptView: View {
} label: { } label: {
Text(kind) Text(kind)
.font(DesignTokens.ubuntuMono(11)) .font(DesignTokens.ubuntuMono(11))
.foregroundStyle(.secondary) .foregroundStyle(DesignTokens.muted)
} }
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
} }
} }
// MARK: Warning status row (round-6 — file-scope, type_body_length
// posture; MonoButton/ResearchNoteContent precedent)
/// Round-6 (mercury#5/sol#10/argon#15 — all seats): the operational
/// warning row as a real component — the 11pt warning glyph, mono 12,
/// structured headline over a muted detail line; wrapping allowed. No
/// new hues — the accent over its own wash.
/// Round-8 (argon#8/mercury#16): `emphasized` (the transcript's last
/// meaningful row) carries the full treatment — accent wash fill (~9%)
/// + 1pt accent border; a historical warning keeps the terracotta glyph
/// + headline on the same plain wash pill the neutral status rows use —
/// distinct, never shouting.
private struct WarningStatusRow: View {
let headline: String
let detail: String?
var emphasized = true
var body: some View {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "exclamationmark.triangle")
.font(.system(size: 11))
.foregroundStyle(DesignTokens.accent)
VStack(alignment: .leading, spacing: 3) {
Text(headline)
.font(DesignTokens.ubuntuMono(12).weight(.semibold))
.foregroundStyle(DesignTokens.accent)
if let detail {
Text(detail)
.font(DesignTokens.ubuntuMono(12))
.foregroundStyle(DesignTokens.muted)
.fixedSize(horizontal: false, vertical: true)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(washFill)
.overlay(emphasized ? borderOverlay : nil)
.textSelection(.enabled)
.accessibilityElement(children: .combine)
}
private var washFill: some View {
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(emphasized ? DesignTokens.accent.opacity(0.09) : DesignTokens.foreground.opacity(0.06))
}
private var borderOverlay: some View {
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.accent, lineWidth: 1)
}
}
// MARK: Warning display seams (round-6 split + round-8 calm copy —
// file-scope extension, type_body_length posture; pure + test-pinned.
// NOT private: ACPClientTests pins both seams via @testable.)
extension SessionTranscriptView {
/// Round-6 (all seats): the warning row's headline/detail split — drop
/// the speaker prefix, then cut at the first ": " ("Operation
/// interrupted: waiting for model response (61.6s elapsed)." → headline
/// "Operation interrupted", detail the rest). No ": " → the whole line
/// is the headline ("connection lost"). Static, nonisolated — pure.
nonisolated static func warningParts(_ text: String) -> (headline: String, detail: String?) {
var body = text
if body.hasPrefix("Mentor: ") {
body = String(body.dropFirst("Mentor: ".count))
}
if body.hasPrefix("You: ") {
body = String(body.dropFirst("You: ".count))
}
guard let separator = body.range(of: ": ") else { return (body, nil) }
return (String(body[..<separator.lowerBound]), String(body[separator.upperBound...]))
}
/// Round-8 (argon#8 — calm copy): the engine's own interruption detail,
/// rephrased without inventing states — "waiting for model response
/// (61.6s elapsed)" renders as "waiting on the model — 61.6s". Only
/// the engine's known phrasing is rewritten (plain prefix/suffix
/// match, trailing period tolerated); anything else passes through
/// verbatim. Static, nonisolated — pure.
nonisolated static func calmDetail(_ detail: String) -> String {
let trimmed = detail.hasSuffix(".") ? String(detail.dropLast()) : detail
let prefix = "waiting for model response ("
let suffix = " elapsed)"
guard trimmed.hasPrefix(prefix), trimmed.hasSuffix(suffix),
trimmed.count > prefix.count + suffix.count
else { return detail }
let elapsed = trimmed.dropFirst(prefix.count).dropLast(suffix.count)
return "waiting on the model — \(elapsed)"
}
}
// MARK: Round-7 row rules (file-scope extension — type_body_length
// posture, the composer extension's precedent)
private extension SessionTranscriptView {
/// Round-7 (mercury#21): this row is the transcript's last MEANINGFUL
/// row — nothing rendered or streaming sits below it. A warning row
/// keeps its warning styling only in this position; once a reply (or a
/// live stream) follows, it is history. Pure display — the model keeps
/// every row either way.
func isLastMeaningfulRow(_ row: SessionRow) -> Bool {
guard !model.isStreaming else { return false }
return model.rows.last(where: { showsDebugRows || Self.isWritingRow($0) })?.id == row.id
}
/// Round-7 (argon#39): a replayed pass kick-off row — the status pill
/// a warning banner must not hug (the 8pt-air rule). Static,
/// nonisolated — pure.
nonisolated static func isKickoffPill(_ row: SessionRow?) -> Bool {
guard let row, case let .text(text) = row.content, text.hasPrefix("You: ") else { return false }
return isPassKickoff(String(text.dropFirst("You: ".count)))
}
}
// MARK: Composer (#155 contract restyle; file-scope extension — // MARK: Composer (#155 contract restyle; file-scope extension —
// type_body_length posture, MentorPaneView precedent) // type_body_length posture, MentorPaneView precedent)
@@ -457,56 +681,83 @@ struct SessionTranscriptView: View {
private extension SessionTranscriptView { private extension SessionTranscriptView {
/// The composer: surface-fill input (radius 10, border), the ONE action /// The composer: surface-fill input (radius 10, border), the ONE action
/// button — accent Send idle, terracotta-outlined Stop mid-stream — and /// button — accent Send idle, terracotta-outlined Stop mid-stream — and
/// the debug toggle at the trailing edge. The liveness chip floats /// the hover-revealed debug toggle at the row's trailing edge. The
/// ABOVE the composer while streaming (contract ruling: the composer /// liveness chip floats ABOVE the composer while streaming (contract
/// row stays flat). /// ruling: the composer row stays flat).
/// Round-1 polish: field and Send match heights (36 — both edges align,
/// argon#33/mercury#38); the debug toggle rides IN the row after Send,
/// not on a strip below it (mercury#64/sol#50).
/// Round-2 polish: the row centers inside the SAME ≤720pt measure the
/// transcript reads in (argon#22/sol#48) with the transcript's 16pt
/// edge — input and conversation share one column; the toggle renders
/// only while the pointer is over the composer (argon#21/sol#43/
/// mercury#58) — its slot stays reserved so nothing shifts on hover.
private var inputBar: some View { private var inputBar: some View {
VStack(alignment: .leading, spacing: 8) { HStack(alignment: .bottom, spacing: 8) {
HStack(alignment: .bottom, spacing: 8) { TextField(
TextField("Ask the mentor…", text: $draft, axis: .vertical) "Ask the mentor…",
.textFieldStyle(.plain) text: $draft,
.font(DesignTokens.concourse(13)) // Round-1 polish (mercury#70/sol#51): placeholder at muted
.lineLimit(1 ... 4) // ink — legible at a glance, not tertiary-faint.
.padding(.horizontal, 10) prompt: Text("Ask the mentor…").foregroundStyle(DesignTokens.muted),
.padding(.vertical, 8) axis: .vertical,
.frame(minHeight: 36) )
.background(RoundedRectangle(cornerRadius: DesignTokens.radius).fill(DesignTokens.surface)) .textFieldStyle(.plain)
.overlay( .font(DesignTokens.concourse(13))
RoundedRectangle(cornerRadius: DesignTokens.radius) .lineLimit(1 ... 4)
.strokeBorder(DesignTokens.border, lineWidth: 1), .padding(.horizontal, 10)
) .padding(.vertical, 8)
.onSubmit { send() } // ⌅/fallback submit — send() no-ops on the double fire .frame(minHeight: 36)
.onKeyPress(phases: .down) { press in .background(RoundedRectangle(cornerRadius: DesignTokens.radius).fill(DesignTokens.surface))
guard press.key == .return else { return .ignored } .overlay(
// Plain Return sends, Shift+Return breaks the line, RoundedRectangle(cornerRadius: DesignTokens.radius)
// every other chord keeps its native newline (⌥↩ above .strokeBorder(DesignTokens.border, lineWidth: 1),
// all). macOS routes Return — ANY modifiers — to the )
// field's submit action otherwise (Vivarium owner .onSubmit { send() } // ⌅/fallback submit — send() no-ops on the double fire
// report 2026-10-26). Caps Lock is masked inside .onKeyPress(phases: .down) { press in
// returnIntent — an exact `==` sent the draft under it. guard press.key == .return else { return .ignored }
// ponytail: the newline appends at the END, not the // Plain Return sends, Shift+Return breaks the line,
// caret — caret-aware insertion needs NSTextView // every other chord keeps its native newline (⌥↩ above
// access; revisit if mid-draft edits ever matter. // all). macOS routes Return — ANY modifiers — to the
switch Self.returnIntent(for: press.modifiers) { // field's submit action otherwise (Vivarium owner
case .send: // report 2026-10-26). Caps Lock is masked inside
send() // returnIntent — an exact `==` sent the draft under it.
return .handled // ponytail: the newline appends at the END, not the
case .lineBreak: // caret — caret-aware insertion needs NSTextView
draft += "\n" // access; revisit if mid-draft edits ever matter.
return .handled switch Self.returnIntent(for: press.modifiers) {
case .passthrough: case .send:
return .ignored send()
} return .handled
} case .lineBreak:
sendButton draft += "\n"
return .handled
case .passthrough:
return .ignored
}
} }
sendButton
if let debugBinding { if let debugBinding {
debugToggle(debugBinding) // Hover reveal: the view is ABSENT at rest (no hit target,
// no focus stop, no a11y node) — the fixed slot keeps Send
// from shifting when the pointer enters the row.
ZStack {
if composerHover {
debugToggle(debugBinding)
}
}
.frame(width: 40)
} }
} }
.padding(.horizontal, 14) .padding(.horizontal, 16)
.padding(.top, 12) // Round-5 (argon#47 tail): symmetric vertical padding — top ==
.padding(.bottom, 10) // bottom at 14 (r4's 12/10 read heavier above the divider's
// edge than below the input).
.padding(.vertical, 14)
// One column with the transcript: cap at the measure, center.
.frame(maxWidth: measureWidth)
.frame(maxWidth: .infinity, alignment: .center)
.onHover { composerHover = $0 }
.overlay(alignment: .top) { .overlay(alignment: .top) {
// #23 dogfood: a pass legitimately runs minutes of silent tool // #23 dogfood: a pass legitimately runs minutes of silent tool
// work — without the chip the pane reads as dead. Contract // work — without the chip the pane reads as dead. Contract
@@ -516,12 +767,40 @@ private extension SessionTranscriptView {
.offset(y: -40) .offset(y: -40)
} }
} }
.disabled(model.phase.isReady == false) // Owner ruling (2026-11-07): the scoped Mentor pane can be ready
// with NO hosted session (empty presentation) — the Sessions pane
// then shows this surface with nothing active, and the composer
// must refuse honestly (disabled), never eat a typed prompt into
// a silently-failed sendPrompt.
.disabled(!model.phase.isReady || model.activeEntry == nil)
} }
/// ONE action button (Vivarium): Send idle / Stop mid-stream. The /// ONE action button (Vivarium): Send idle / Stop mid-stream. The
/// default-action shortcut rides the Send state ONLY — Stop must never /// default-action shortcut rides the Send state ONLY — Stop must never
/// catch a plain Return. /// catch a plain Return.
/// Round-1 polish: 36pt to match the input (both edges align,
/// argon#33). Round-4 contrast (sol#39/argon#11/mercury#52/56): the
/// disabled Send is no longer a 0.75-dimmed accent pill (near-invisible)
/// — #6B6964 ink on the #E8E5DF-hinted fill at full opacity, the
/// council's disabled language.
private var canSend: Bool {
model.isStreaming || !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private var sendFill: Color {
if model.isStreaming {
return .clear
}
return canSend ? DesignTokens.accent : DesignTokens.border
}
private var sendInk: Color {
if model.isStreaming {
return DesignTokens.accent
}
return canSend ? DesignTokens.surface : DesignTokens.muted
}
private var sendButton: some View { private var sendButton: some View {
Button { Button {
if model.isStreaming { if model.isStreaming {
@@ -532,20 +811,20 @@ private extension SessionTranscriptView {
} label: { } label: {
Text(model.isStreaming ? "Stop" : "Send") Text(model.isStreaming ? "Stop" : "Send")
.font(DesignTokens.ubuntuMono(11)) .font(DesignTokens.ubuntuMono(11))
.foregroundStyle(model.isStreaming ? DesignTokens.accent : DesignTokens.surface) .foregroundStyle(sendInk)
.padding(.horizontal, 14) .padding(.horizontal, 14)
.frame(minHeight: 30) .frame(minHeight: 36)
.background( .background(
RoundedRectangle(cornerRadius: 6) RoundedRectangle(cornerRadius: 6)
.fill(model.isStreaming ? Color.clear : DesignTokens.accent), .fill(sendFill),
) )
.overlay( .overlay(
RoundedRectangle(cornerRadius: 6) RoundedRectangle(cornerRadius: 6)
.strokeBorder(model.isStreaming ? DesignTokens.accent : Color.clear, lineWidth: 1), .strokeBorder(sendStroke, lineWidth: 1),
) )
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.disabled(!model.isStreaming && draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) .disabled(!canSend)
.keyboardShortcut(model.isStreaming ? nil : .defaultAction) .keyboardShortcut(model.isStreaming ? nil : .defaultAction)
.help( .help(
model.isStreaming model.isStreaming
@@ -554,6 +833,18 @@ private extension SessionTranscriptView {
) )
} }
/// Round-5 (sol#36/argon#45): the disabled Send keeps its r4 ink
/// treatment and gains the one-step-stronger border — the #D8D4CC-
/// equivalent darkening of border #E8E5DF via foreground opacity
/// (no new hex), same as the disabled Blind Read. Enabled states
/// untouched (Send's fill carries it; Stop keeps its accent outline).
private var sendStroke: Color {
if model.isStreaming {
return DesignTokens.accent
}
return canSend ? .clear : DesignTokens.foreground.opacity(0.17)
}
/// The liveness chip — a hint, not a control (Stop lives in the Send /// The liveness chip — a hint, not a control (Stop lives in the Send
/// slot). thinMaterial is the contract's translucent-surface+blur /// slot). thinMaterial is the contract's translucent-surface+blur
/// approximation (#154 deviation note). /// approximation (#154 deviation note).
@@ -561,8 +852,12 @@ private extension SessionTranscriptView {
HStack(spacing: 8) { HStack(spacing: 8) {
ProgressView().controlSize(.small) ProgressView().controlSize(.small)
Text("Mentor is working — Stop to interrupt.") Text("Mentor is working — Stop to interrupt.")
.font(DesignTokens.ubuntuMono(10)) // Round-4: 11 — informational micro-labels ride the 11pt
.foregroundStyle(.secondary) // legibility floor (mercury#52).
.font(DesignTokens.ubuntuMono(11))
// Round-2 sweep: muted at full ink — .secondary broke the
// 0.75 contrast floor for informational micro-labels.
.foregroundStyle(DesignTokens.muted)
} }
.padding(.horizontal, 12) .padding(.horizontal, 12)
.padding(.vertical, 5) .padding(.vertical, 5)
@@ -570,8 +865,11 @@ private extension SessionTranscriptView {
.allowsHitTesting(false) .allowsHitTesting(false)
} }
/// Settled #5: the Debug toggle's new seat — mono-10 lowercase text /// Settled #5: the Debug toggle's seat — the composer row's trailing
/// toggle at the composer's trailing edge (muted off, accent on). /// edge (Round-1: mono-10 lowercase, muted, riding IN the row after
/// Send). Round-2 polish: hover-revealed — the toggle mounts only
/// while the pointer is over the composer (see inputBar); muted at
/// FULL opacity when off (the 0.65 dim broke the 0.75 floor).
private func debugToggle(_ binding: Binding<Bool>) -> some View { private func debugToggle(_ binding: Binding<Bool>) -> some View {
Button { Button {
binding.wrappedValue.toggle() binding.wrappedValue.toggle()
@@ -579,10 +877,10 @@ private extension SessionTranscriptView {
Text("debug") Text("debug")
.font(DesignTokens.ubuntuMono(10)) .font(DesignTokens.ubuntuMono(10))
.foregroundStyle(binding.wrappedValue ? DesignTokens.accent : DesignTokens.muted) .foregroundStyle(binding.wrappedValue ? DesignTokens.accent : DesignTokens.muted)
.opacity(binding.wrappedValue ? 1 : 0.65) // Optically centers against the 36pt input at rest.
.padding(.bottom, 11)
} }
.buttonStyle(.plain) .buttonStyle(.plain)
.frame(maxWidth: .infinity, alignment: .trailing)
.help("Show session updates, tool calls, and engine thinking.") .help("Show session updates, tool calls, and engine thinking.")
// Audit #155: the checkbox this replaced announced switch state — // Audit #155: the checkbox this replaced announced switch state —
// a plain Button must say it itself. // a plain Button must say it itself.
+288 -108
View File
@@ -9,6 +9,7 @@
// toggle there). // toggle there).
// //
import AppKit
import SwiftUI import SwiftUI
/// The Sessions rail destination: two-column body like Posts — roster list /// The Sessions rail destination: two-column body like Posts — roster list
@@ -32,19 +33,23 @@ struct SessionsPaneView: View {
@State private var sessionDraft: String? @State private var sessionDraft: String?
var body: some View { var body: some View {
VStack(spacing: 0) { // Round-1 polish (argon#3/sol#19/mercury#41): the pane header —
PaneHeader(title: "Sessions") { // title + New Session + its hairline — confines to the roster
newSessionControl // column (the Posts pane's language), and the roster|transcript
// divider runs full height.
HStack(spacing: 0) {
VStack(spacing: 0) {
PaneHeader(title: "Sessions") {
newSessionControl
}
rosterList
} }
.frame(width: DesignTokens.libraryWidth)
paneBorder
if model.roster.isEmpty { if model.roster.isEmpty {
emptyState emptyState
} else { } else {
HStack(spacing: 0) { sessionDetail
rosterList
.frame(width: DesignTokens.libraryWidth)
paneBorder
sessionDetail
}
} }
} }
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -79,6 +84,21 @@ struct SessionsPaneView: View {
// real engine child there. // real engine child there.
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return } guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
await model.openSession() await model.openSession()
// Round-4 (all seats — Sessions scored 6 everywhere): entering
// the archive with nothing active (the Mentor pane's piece
// scoping clears activeEntry) auto-selects the newest roster
// session — the blank-canvas + bare em-dash entry dies.
// openSession is idempotent once ready, so this is the
// pane-entry selection rail; Sessions stays the unscoped
// archive (the Mentor pane re-scopes at ITS mount).
// (#142 posture: the wrapped condition list's brace lands on
// its own line and trips opening_brace — nested ifs, never
// fight the formatter.)
if model.activeEntry == nil, !model.isStreaming {
if let newest = model.roster.first {
await model.resumeSession(newest)
}
}
} }
} }
@@ -96,6 +116,7 @@ struct SessionsPaneView: View {
} }
} }
} }
.padding(.top, 14) // Round-1 polish: the topmost row clears the header hairline
.padding(.bottom, 12) .padding(.bottom, 12)
} }
} }
@@ -146,55 +167,108 @@ struct SessionsPaneView: View {
} }
} }
/// The active session's name + engine version, Fork/Compact beside them /// The active session's name + Fork/Compact beside them
/// — disabled while a turn streams (canStartSession). /// — disabled while a turn streams (canStartSession).
/// Round-4: the row rides the #90 52pt header height so its hairline
/// runs continuous with the roster header's (argon#14/mercury#29); the
/// pills take the app's bordered secondary language at 28pt with a 16pt
/// window margin (sol#43/argon#48); a no-selection state never renders
/// a bare em-dash, and the session-scoped actions disable until a
/// session is active (all seats, round 3).
/// Round-5 (argon#47): a 'Pass N ·' prefix reads muted beside the ink
/// title (same line).
/// Round-8 (mercury#17 — FINAL RULING): the version badge sits BESIDE
/// the trailing button group — title | spacer | badge | buttons. Its
/// r5-r7 seat beside the title left a dead middle gap; it rides
/// vertically centered with the 28pt pills, 12pt off the group
/// (8 row spacing + the group's 4pt lead).
private var actionsRow: some View { private var actionsRow: some View {
HStack(spacing: 8) { HStack(spacing: 8) {
Text(model.activeEntry?.name ?? "—") if let name = model.activeEntry?.name {
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) passTitle(name)
.lineLimit(1) .lineLimit(1)
.truncationMode(.tail) .truncationMode(.tail)
} else {
Text("No session selected")
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.muted)
.help("Select a session in the roster — or start a new conversation from the + above.")
}
Spacer()
if let version = model.engineVersion { if let version = model.engineVersion {
// Round-1 polish (sol#53/mercury#68): the engine version is its
// own muted mono chunk on the fg-wash card. Round-6 (sol#35):
// fixedSize — the badge never truncates or compresses; the
// TITLE's budget accounts for it and truncates first.
Text(version) Text(version)
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.lineLimit(1) .lineLimit(1)
.fixedSize()
.padding(.horizontal, 7)
.padding(.vertical, 2)
.background(
RoundedRectangle(cornerRadius: 5)
.fill(DesignTokens.foreground.opacity(0.06)),
)
.help(model.versionNote ?? version) .help(model.versionNote ?? version)
} }
Spacer()
// #30 (S2.7): the draft candidate prefills the ask sheet (empty // #30 (S2.7): the draft candidate prefills the ask sheet (empty
// transcript → empty prefill — the sheet still works). Reads // transcript → empty prefill — the sheet still works). Reads
// in-memory transcript rows — engine-free, never gated on // in-memory transcript rows — engine-free, never gated on
// canStartSession (a crashed engine must not strand the draft). // canStartSession (a crashed engine must not strand the draft).
Button("New Post") { HStack(spacing: 8) {
sessionDraft = model.draftCandidateText() ?? "" Button("New Post") {
sessionDraft = model.draftCandidateText() ?? ""
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(model.activeEntry == nil)
.help("Start a Post from this session's draft candidate")
.accessibilityLabel("New Post from Session")
Button("Fork") {
Task { _ = await model.forkActiveSession() }
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(!model.canStartSession || model.activeEntry == nil)
.help("Copy this session's history into a new one")
.accessibilityLabel("Fork session")
Button("Compact") {
Task { await model.compactActiveSession() }
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(!model.canStartSession || model.activeEntry == nil)
.help("Compress the session's history")
.accessibilityLabel("Compact session")
} }
.buttonStyle(.bordered) .padding(.leading, 4)
.controlSize(.small)
.font(.system(size: 11, design: DesignTokens.mono))
.help("Start a Post from this session's draft candidate")
.accessibilityLabel("New Post from Session")
Button("Fork") {
Task { _ = await model.forkActiveSession() }
}
.buttonStyle(.bordered)
.controlSize(.small)
.font(.system(size: 11, design: DesignTokens.mono))
.disabled(!model.canStartSession)
.help("Copy this session's history into a new one")
.accessibilityLabel("Fork session")
Button("Compact") {
Task { await model.compactActiveSession() }
}
.buttonStyle(.bordered)
.controlSize(.small)
.font(.system(size: 11, design: DesignTokens.mono))
.disabled(!model.canStartSession)
.help("Compress the session's history")
.accessibilityLabel("Compact session")
} }
.padding(.horizontal, 12) .padding(.horizontal, 16)
.padding(.vertical, 8) .frame(minHeight: 52)
}
/// Round-5 (argon#47): the conversation title — a 'Pass N ·' prefix
/// renders in muted beside the ink remainder (one line, two tones); any
/// other name renders whole in ink. The serif face applies per piece:
/// a concatenated Text keeps each segment's own styling.
private func passTitle(_ name: String) -> Text {
if let separator = name.range(of: " · "), Self.isPassLabel(String(name[..<separator.lowerBound])) {
return Text(String(name[..<separator.upperBound]))
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.muted)
+ Text(String(name[separator.upperBound...]))
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.foreground)
}
return Text(name)
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.foreground)
}
/// The pass transcripts' label heads — "Pass 1"/"Pass 12" (the model's
/// `runOneShot` names; "Blind Read" keeps its plain-ink title).
private static func isPassLabel(_ head: String) -> Bool {
let digits = head.dropFirst("Pass ".count)
return head.hasPrefix("Pass ") && !digits.isEmpty && digits.allSatisfy(\.isNumber)
} }
/// No second restart flow — the Mentor pane owns Restart (map decision). /// No second restart flow — the Mentor pane owns Restart (map decision).
@@ -202,12 +276,14 @@ struct SessionsPaneView: View {
VStack(spacing: 8) { VStack(spacing: 8) {
Image(systemName: "exclamationmark.triangle.fill") Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 30)) .font(.system(size: 30))
.foregroundStyle(.orange) // Round-2 polish: the #156 danger voice — terracotta, never
// the system orange (two-color world, no stray hues).
.foregroundStyle(DesignTokens.accent)
Text("The mentor engine stopped") Text("The mentor engine stopped")
.font(.title3) .font(.title3)
Text("Restart it in the Mentor pane — nothing is lost.") Text("Restart it in the Mentor pane — nothing is lost.")
.font(.callout) .font(.callout)
.foregroundStyle(.secondary) .foregroundStyle(DesignTokens.muted)
} }
.padding(24) .padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity) .frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -230,11 +306,26 @@ struct SessionsPaneView: View {
Task { _ = await model.beginBrainstormSession(pieceTitle: piece?.title) } Task { _ = await model.beginBrainstormSession(pieceTitle: piece?.title) }
} }
} label: { } label: {
// Round-4 (mercury#57): accent tint + a heavier weight — the
// plus reads as a control, not decoration. Round-7 (argon#39):
// a real 24×24 hit-target container in the header pill family
// (surface fill + hairline, BorderedSecondaryButtonStyle's
// shape) — the bare glyph had no target.
Image(systemName: "plus") Image(systemName: "plus")
.font(.system(size: 13, weight: .medium))
.frame(width: 24, height: 24)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface),
)
.overlay(
RoundedRectangle(cornerRadius: 8)
.strokeBorder(DesignTokens.border, lineWidth: 1),
)
} }
.menuStyle(.button) .menuStyle(.button)
.buttonStyle(.plain) .buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.accent)
.disabled(!model.canStartSession) .disabled(!model.canStartSession)
.help("New Session") .help("New Session")
.accessibilityLabel("New Session") .accessibilityLabel("New Session")
@@ -268,7 +359,9 @@ struct SessionsPaneView: View {
VStack(spacing: 8) { VStack(spacing: 8) {
Text("No sessions yet.") Text("No sessions yet.")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Sessions arrive when a pass runs — or create one with New Session.") // Round-4 (all seats): 'select a session or start a new
// conversation' — the empty canvas names its way out.
Text("Start a new conversation with the + above — sessions also arrive when a pass runs.")
.font(.callout) .font(.callout)
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
@@ -278,28 +371,43 @@ struct SessionsPaneView: View {
} }
} }
/// One roster row: the library's post-row language — always-2px leading /// One roster row: the library's post-row language — selected strip as a
/// strip (accent when selected, no layout shift), surface card + border on /// vertically-inset rounded capsule (round-6: part of the card, not
/// selection, serif name over mono-11 meta (piece · created). /// pasted on), surface card + border on selection, serif name over
/// mono-11 meta (piece · created).
private struct SessionEntryRow: View { private struct SessionEntryRow: View {
let entry: SessionEntry let entry: SessionEntry
let selected: Bool let selected: Bool
let select: () -> Void let select: () -> Void
@State private var hover = false @State private var hover = false
/// Round-6 (mercury#4/sol#9 — verified against the r5 live shot):
/// the title budget is GLYPH-MEASURED. The r5 ~58-char estimate
/// overshot the real two-line capacity of this width (the r5 shot
/// still cut mid-word — "Markd…"); the seam now measures the row's
/// exact serif-13 semibold face, so its output is what renders and
/// lineLimit(2) below is a no-op safety net.
/// libraryWidth 232 − 16 row pads − 14 leading (2 strip + 12 gap) −
/// 10 trailing.
private static let titleWidth = DesignTokens.libraryWidth - 16 - 14 - 10
var body: some View { var body: some View {
// Same shape as LibraryPostRow: leading corners square (the 2px // Same card shape as LibraryPostRow; the selected strip rides as
// strip), trailing rounded 8 — only the strip's COLOR changes. // an inset capsule overlay (below) — only the strip's LANGUAGE
// diverges from LibraryPostRow, by the round-6 ruling.
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8)) let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
return Button(action: select) { return Button(action: select) {
HStack(spacing: 0) { HStack(spacing: 0) {
Rectangle()
.fill(selected ? DesignTokens.accent : .clear)
.frame(width: 2)
VStack(alignment: .leading, spacing: 5) { VStack(alignment: .leading, spacing: 5) {
Text(entry.name) // Round-4 (sol#7/argon#15 tail/mercury#30): two lines
// — titles stop dying mid-word; meta stays below.
// Round-5 (mercury#4/sol#8/argon#16): word-boundary
// truncation replaces the native mid-word tail cut.
// Round-6: glyph-measured (see titleWidth) — the seam
// decides, lineLimit(2) is the safety net.
Text(WordBoundaryTruncation.fit(entry.name, maxWidth: Self.titleWidth))
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(1) .lineLimit(2)
.truncationMode(.tail) .truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
Text(metaLine) Text(metaLine)
@@ -309,7 +417,12 @@ private struct SessionEntryRow: View {
.truncationMode(.tail) .truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
} }
.padding(10) // Round-5 (sol#38/mercury#54) kept 10-12pt between the
// strip and the text; the overlay strip (2pt) + 12pt
// internal leading = 14 off the card edge — same seat.
.padding(.leading, 14)
.padding(.trailing, 10)
.padding(.vertical, 10)
} }
.clipShape(shape) .clipShape(shape)
} }
@@ -320,10 +433,28 @@ private struct SessionEntryRow: View {
shape shape
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06)) .fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06))
.overlay( .overlay(
shape.strokeBorder(selected ? DesignTokens.border : .clear), // Round-5 (sol#38/mercury#54): the selected border one
// step stronger than the hairline — the #D8D4CC-equivalent
// darkening of border #E8E5DF via foreground opacity
// (no new hex) — so selection reads at a glance.
shape.strokeBorder(
selected ? DesignTokens.foreground.opacity(0.17) : .clear,
),
) )
} }
} }
// Round-6 (mercury#25/49, argon#13): the selected strip is a
// vertically-inset rounded capsule — 7pt off the card's top and
// bottom, 2pt wide, radius 1 — reading as part of the card, not
// a full-height strip pasted beside it.
.overlay(alignment: .leading) {
if selected {
RoundedRectangle(cornerRadius: 1)
.fill(DesignTokens.accent)
.frame(width: 2)
.padding(.vertical, 7)
}
}
.padding(.horizontal, 8) .padding(.horizontal, 8)
.onHover { hover = $0 } .onHover { hover = $0 }
.help(entry.name) .help(entry.name)
@@ -331,8 +462,12 @@ private struct SessionEntryRow: View {
} }
private var metaLine: String { private var metaLine: String {
// Round-2 polish (argon#23/sol#13/mercury#61): display-level dedupe
// — when the session name already carries the piece title, the meta
// line shows the timestamp only. Contract otherwise unchanged
// (pieceTitle · yyyy-MM-dd HH:mm).
var parts: [String] = [] var parts: [String] = []
if let piece = entry.pieceTitle { if let piece = entry.pieceTitle, !entry.name.contains(piece) {
parts.append(piece) parts.append(piece)
} }
parts.append(FixCardStore.formatted(entry.createdAt, "yyyy-MM-dd HH:mm")) parts.append(FixCardStore.formatted(entry.createdAt, "yyyy-MM-dd HH:mm"))
@@ -340,59 +475,104 @@ private struct SessionEntryRow: View {
} }
} }
/// #30 (S2.7): the New Post from Session ask — the draft candidate /// Round-5 (mercury#4/sol#8/argon#16) → Round-6 glyph-measured
/// (the session's last mentor reply) prefills and stays editable. /// (mercury#4/sol#9) → Round-7 middle-eliding (argon#14/sol#32/47) →
/// Confirm materializes the piece stamped `origin: ai` — never /// Round-8 head-biased split (sol#3): pure title truncation —
/// stats-eligible — and opens it in Posts; Cancel writes nothing. /// SwiftUI's tail truncation cuts mid-word ("Markd…") and, worse,
/// The error line is SHEET-LOCAL state: it dies with the presentation, /// killed the roster's shared titles at their common boilerplate. The
/// so a re-opened ask never shows a stale refusal. /// seam measures the row's exact face (system serif 13 semibold,
private struct NewPostFromSessionSheet: View { /// through NSFont) against `maxWidth`; an overflowing title splits
@Binding var draft: String /// HEAD-BIASED (~60/40): the head keeps a leading label ("Pass N ·")
/// The confirm's failure reason — a failed write keeps the sheet up, /// plus as many following words as fit in ~60% of the glyph budget —
/// draft intact; dismissal itself is the cancel. /// the unique topic survives — then the LONGEST word suffix that still
@State private var createError: String? /// fits (r7 kept only the label and maximized the tail; the topic died
let create: () -> String? /// either way). Pinned in WordBoundaryTruncationTests.
nonisolated enum WordBoundaryTruncation {
/// The roster title's exact face — SessionEntryRow's serif-13
/// semibold system design, the same metrics SwiftUI's Text renders.
/// nonisolated(unsafe) — NSFont isn't Sendable (ProseTypography
/// precedent); the descriptor-built font is effectively immutable.
private nonisolated(unsafe) static let titleFont: NSFont = {
let base = NSFont.systemFont(ofSize: 13, weight: .semibold)
return base.fontDescriptor.withDesign(.serif).flatMap { NSFont(descriptor: $0, size: 13) } ?? base
}()
var body: some View { private static let spaceWidth = NSAttributedString(
VStack(alignment: .leading, spacing: 12) { string: " ", attributes: [.font: titleFont],
Text("New Post from Session") ).size().width
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text( /// Round-8 (sol#3): the head's share of the lines × maxWidth glyph
"The draft starts from the session's last mentor reply. It lands in your library stamped origin: ai — never counted as your writing.", /// budget — bias the split toward the unique head, away from the
) /// shared tail.
.font(.callout) private static let headShare: CGFloat = 0.6
.foregroundStyle(DesignTokens.muted)
TextEditor(text: $draft) private static func width(_ text: String) -> CGFloat {
.font(.system(size: 13, design: DesignTokens.serif)) NSAttributedString(string: text, attributes: [.font: titleFont]).size().width
.frame(width: 380, height: 160) }
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius) /// Passthrough when `text` wraps within `lines` × `maxWidth`;
.strokeBorder(DesignTokens.border), /// otherwise (round-8, sol#3) MIDDLE-elide with a head-biased
) /// (~60/40) split — the head keeps a leading "Label ·" trio when the
if let createError { /// name carries one (the roster's "Pass N ·" shape) plus following
Text(createError) /// words up to `headShare` of the budget; the tail keeps the LONGEST
.font(.system(size: 11, design: DesignTokens.mono)) /// word suffix that still fits: more of the unique topic, less of
.foregroundStyle(.orange) /// the shared boilerplate. When no suffix fits beside the head, the
} /// head truncates alone (the r5/r6 shape — the ellipsis binds to its
HStack { /// last word); a word wider than the line keeps its own line
Spacer() /// (lineLimit catches it).
// Dismissal itself is the cancel (binding set(false) → static func fit(_ text: String, maxWidth: CGFloat, lines: Int = 2) -> String {
// sessionDraft = nil) — Esc and ⌘. land here too. let words = text.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
Button("Cancel", role: .cancel) {} guard !words.isEmpty else { return text }
.keyboardShortcut(.cancelAction) // Finish-audit: measure each word ONCE — a pathological title (an
Button("Create Post", action: confirm) // imported post's first line is unbounded) must not turn the
.keyboardShortcut(.defaultAction) // candidate loop into quadratic glyph measurement on the main actor.
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) // 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]]
}
let budget = CGFloat(lines) * maxWidth * headShare
// Grow the head into its budget — always leaving the tail at
// least one word to keep (a head that consumed everything is
// just the r5 prefix cut again).
var index = head.count
while index < words.count - 1, width((head + [words[index]]).joined(separator: " ")) <= budget {
head.append(words[index])
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 candidateWidths = headWidths + [ellipsis] + Array(widths[(words.count - count)...])
if lineCount(candidateWidths, maxWidth) <= lines {
return head.joined(separator: " ") + " … " + tail.suffix(count).joined(separator: " ")
} }
} }
.padding(20) return head.joined(separator: " ") + "…"
.frame(width: 420)
} }
/// No dismiss() here — success closes the sheet via the pane's /// Greedy word wrap (the text system's own algorithm): how many
/// `sessionDraft = nil` (the binding); failure keeps it up with the /// lines `widths` (per-word glyph widths, measured once) need at
/// inline reason and the edited draft intact. /// `maxWidth`.
private func confirm() { private static func lineCount(_ widths: [CGFloat], _ maxWidth: CGFloat) -> Int {
createError = create() var lines = 1
var used: CGFloat = 0
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.
used = tokenWidth
} else if used + spaceWidth + tokenWidth <= maxWidth {
used += spaceWidth + tokenWidth
} else {
lines += 1
used = tokenWidth
}
}
return lines
} }
} }
+98 -64
View File
@@ -13,7 +13,8 @@
import SwiftUI import SwiftUI
/// The quiet field label (prototype `.field-label`, #130 fold-in): mono /// The quiet field label (prototype `.field-label`, #130 fold-in): mono
/// 10.5 uppercase, one line, never a wrapping caption. /// 11 uppercase (r4: 10.5 → 11, the phase-2 micro-label sweep), one line,
/// never a wrapping caption.
struct SettingsFieldLabel: View { struct SettingsFieldLabel: View {
let text: String let text: String
@@ -23,7 +24,7 @@ struct SettingsFieldLabel: View {
var body: some View { var body: some View {
Text(text) Text(text)
.font(.system(size: 10.5, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.lineLimit(1) .lineLimit(1)
.tracking(0.5) .tracking(0.5)
.textCase(.uppercase) .textCase(.uppercase)
@@ -39,11 +40,30 @@ struct SurfaceSettingsPage: View {
let surface: ProfileSurface let surface: ProfileSurface
var body: some View { var body: some View {
// r8 (mercury#20, sol — owner regression): the r6 ScrollView +
// minHeight frame CENTERED the form in the viewport (~320px of
// dead space under the intro) and its +24 bottom padding kept a
// phantom scrollbar alive. Both gone — a plain top-aligned stack
// (the Content page's r7 shape): one control column, every
// control label-above-control at the page title's x, ~24pt under
// the intro, no scrolling (the page fits).
VStack(alignment: .leading, spacing: 24) {
header
form
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 24)
.padding(.top, 17)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
private var header: some View {
let config = model.config(for: surface) let config = model.config(for: surface)
VStack(alignment: .leading, spacing: 4) { return VStack(alignment: .leading, spacing: 4) {
HStack { HStack {
Text(label) Text(label)
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Spacer(minLength: 12) Spacer(minLength: 12)
// macOS convention: Restore Defaults in the page header. // macOS convention: Restore Defaults in the page header.
Button("Restore Defaults") { Button("Restore Defaults") {
@@ -51,6 +71,9 @@ struct SurfaceSettingsPage: View {
} }
.buttonStyle(.bordered) .buttonStyle(.bordered)
.controlSize(.small) .controlSize(.small)
// r6 (sol#6/21 — contrast final): disabled reads muted
// ink + the system border, never washed out.
.foregroundStyle(config == .surfaceDefault ? DesignTokens.muted : DesignTokens.foreground)
.disabled(config == .surfaceDefault) .disabled(config == .surfaceDefault)
} }
// Variant B's stolen headline: the current model reads first. // Variant B's stolen headline: the current model reads first.
@@ -60,63 +83,66 @@ struct SurfaceSettingsPage: View {
Text("profile · \(surface.profileName) — \(note)") Text("profile · \(surface.profileName) — \(note)")
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
VStack(alignment: .leading, spacing: 14) {
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Provider")
Picker("Provider", selection: Binding(
get: { config.provider },
set: { model.setProvider($0, for: surface) },
)) {
ForEach(ModelProvider.allCases, id: \.self) { provider in
Text(provider.label).tag(provider)
}
}
.pickerStyle(.menu)
.frame(width: 200)
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Model")
HStack(spacing: 8) {
ModelComboBox(
value: config.model,
items: model.registry.list(for: config.provider),
) { model.setModel($0, for: surface) }
.frame(width: 240)
if model.isCustom(surface) {
Text("custom (not in registry)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Reasoning Effort")
Picker("Reasoning Effort", selection: Binding(
get: { config.effort },
set: { model.setEffort($0, for: surface) },
)) {
Text("unset · provider default").tag(ReasoningEffort?.none)
// The provider's ladder only — a provider switch
// rebuilds this menu (and resets the choice).
ForEach(config.provider.effortOptions, id: \.self) { effort in
Text(effort.rawValue).tag(ReasoningEffort?.some(effort))
}
}
.pickerStyle(.menu)
.frame(width: 200)
}
Text("Output budget fixed at \(ProfileSurface.outputBudgetTokens / 1000)k tokens — not a setting.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
.padding(.top, 12)
} }
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
.padding(.horizontal, 26)
.padding(.top, 18)
.padding(.bottom, 48)
} }
private var form: some View {
let config = model.config(for: surface)
return VStack(alignment: .leading, spacing: 14) {
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Provider")
Picker("Provider", selection: Binding(
get: { config.provider },
set: { model.setProvider($0, for: surface) },
)) {
ForEach(ModelProvider.allCases, id: \.self) { provider in
Text(provider.label).tag(provider)
}
}
.pickerStyle(.menu)
.frame(width: 200)
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Model")
HStack(spacing: 8) {
ModelComboBox(
value: config.model,
items: model.registry.list(for: config.provider),
) { model.setModel($0, for: surface) }
.frame(width: 240)
if model.isCustom(surface) {
Text("custom (not in registry)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Reasoning Effort")
Picker("Reasoning Effort", selection: Binding(
get: { config.effort },
set: { model.setEffort($0, for: surface) },
)) {
Text("unset · provider default").tag(ReasoningEffort?.none)
// The provider's ladder only — a provider switch
// rebuilds this menu (and resets the choice).
ForEach(config.provider.effortOptions, id: \.self) { effort in
Text(effort.rawValue).tag(ReasoningEffort?.some(effort))
}
}
.pickerStyle(.menu)
.frame(width: 200)
}
Text("Output budget fixed at \(ProfileSurface.outputBudgetTokens / 1000)k tokens — not a setting.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
}
// wf130 `.vC .detail`: left-anchored after the sidebar, never centered
// (r4: horizontal 24 — one leading-text token with the sidebar labels;
// r6: the width/scroll wrappers live in body).
private var label: String { private var label: String {
switch surface { switch surface {
case .pass1: "Pass 1" case .pass1: "Pass 1"
@@ -145,21 +171,26 @@ struct ProviderKeysPage: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
Text("Provider Keys") Text("Provider Keys")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("One key per provider, fanned out to every profile on it. No Keychain.") Text("One key per provider, fanned out to every profile on it. No Keychain.")
.font(.system(size: 12)) .font(.system(size: 12))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
// r8 (mercury#20, sol — owner regression): top-aligned under
// the intro (stack 4 + padding 20 = 24pt), NO ScrollView —
// the blocks fit the viewport whole; the r6 minHeight-center
// + scroll wrapper died with the surface pages' copy.
VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 10) {
ForEach(ModelProvider.allCases, id: \.self) { provider in ForEach(ModelProvider.allCases, id: \.self) { provider in
ProviderKeyBlock(model: model, provider: provider) ProviderKeyBlock(model: model, provider: provider)
} }
} }
.padding(.top, 12) .padding(.top, 20)
.frame(maxWidth: DesignTokens.settingsFormWidth + 60, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
} }
.frame(maxWidth: DesignTokens.settingsFormWidth + 60, alignment: .leading) .padding(.horizontal, 24)
.padding(.horizontal, 26) .padding(.top, 17)
.padding(.top, 18) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.padding(.bottom, 48)
} }
} }
@@ -241,6 +272,9 @@ private struct ProviderKeyBlock: View {
.buttonStyle(.bordered) .buttonStyle(.bordered)
.controlSize(.small) .controlSize(.small)
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
// r6 (sol#6/21 — contrast final): disabled reads muted ink +
// the system border, never washed out.
.foregroundStyle(model.testStates[provider] == .running ? DesignTokens.muted : DesignTokens.foreground)
.disabled(model.testStates[provider] == .running) .disabled(model.testStates[provider] == .running)
switch model.testStates[provider] { switch model.testStates[provider] {
case .running: case .running:
+164 -44
View File
@@ -38,23 +38,25 @@ struct SettingsPaneView: View {
} }
var body: some View { var body: some View {
VStack(spacing: 0) { // r5 (argon#51, mercury#32 — the Sessions r2 pattern): the
PaneHeader(title: "Settings") // 'Settings' header band + its hairline live in the SIDEBAR
if let error = model.lastWriteError { // column alone; the sidebar/detail divider runs the full height
Text(error) // (up to the titlebar) and the detail's content starts under
.font(.system(size: 11, design: DesignTokens.mono)) // the titlebar, not under a pane-wide band.
.foregroundStyle(.orange) HStack(spacing: 0) {
.frame(maxWidth: .infinity, alignment: .leading) VStack(spacing: 0) {
.padding(.horizontal, 14) // r4: title inset 24 — one leading-text token for the whole
.padding(.vertical, 4) // pane (mercury#38 tail): the sidebar column pads 8, its
} // rows 16, so item labels start at x24; the header and the
HStack(spacing: 0) { // detail column's forms share that edge.
PaneHeader(title: "Settings", titleInset: 24)
sidebar sidebar
Rectangle()
.fill(DesignTokens.border)
.frame(width: 1)
detail
} }
.frame(width: DesignTokens.settingsSidebarWidth)
Rectangle()
.fill(DesignTokens.border)
.frame(width: 1)
detail
} }
.background(DesignTokens.background) .background(DesignTokens.background)
.task { await model.hydrate() } .task { await model.hydrate() }
@@ -80,7 +82,22 @@ struct SettingsPaneView: View {
// MARK: Detail (prototype `.vC .detail`) // MARK: Detail (prototype `.vC .detail`)
private var detail: some View { private var detail: some View {
ScrollView { VStack(spacing: 0) {
// Writes happen in the detail pages, so the write-error strip
// rides the detail column's top (r5: no pane-wide band above
// the detail anymore).
if let error = model.lastWriteError {
Text(error)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(.orange)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 24)
.padding(.vertical, 4)
}
// r8 (mercury#20, sol — owner regression): each page pins its
// header (baseline-aligned with the sidebar's 'Settings' title)
// and TOP-ALIGNS its form stack ~24pt under the intro — no
// ScrollView, no vertical centering (the r6 pattern died).
switch page { switch page {
case .content: case .content:
ContentSettingsPage(home: $home) ContentSettingsPage(home: $home)
@@ -123,11 +140,13 @@ enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
/// The prototype's trailing mono annotation: pass chips + the Sessions /// The prototype's trailing mono annotation: pass chips + the Sessions
/// note on Chat (the chat row notes "Sessions rides this engine"). /// note on Chat (the chat row notes "Sessions rides this engine").
/// r2: "SESSIONS" — an uppercase mono badge in the same voice as
/// P1/P2, not a lowercase "· Sessions" aside.
var annotation: String? { var annotation: String? {
switch self { switch self {
case .pass1: "P1" case .pass1: "P1"
case .pass2: "P2" case .pass2: "P2"
case .chat: "· Sessions" case .chat: "SESSIONS"
default: nil default: nil
} }
} }
@@ -151,11 +170,14 @@ private struct SettingsSidebarButton: View {
Spacer(minLength: 0) Spacer(minLength: 0)
if let annotation = page.annotation { if let annotation = page.annotation {
Text(annotation) Text(annotation)
.font(.system(size: 10, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
} }
} }
.padding(.horizontal, 10) // r4: leading 16 — labels land at x24 (the pane's one inset
// token) and the inset accent bar keeps an 8-10pt gap to the
// label text (bar at x12-14), up from the old 4pt sliver.
.padding(.horizontal, 16)
.padding(.vertical, 7) .padding(.vertical, 7)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle()) .contentShape(Rectangle())
@@ -164,16 +186,22 @@ private struct SettingsSidebarButton: View {
.background { .background {
if selected || hover { if selected || hover {
RoundedRectangle(cornerRadius: 8) RoundedRectangle(cornerRadius: 8)
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06)) // r2: one contrast step above the 0.06 hover wash —
// the selected row reads as raised, not identical to
// its background (surface #FFFEFB was invisible on
// the #FAF9F3 chrome).
.fill(selected ? DesignTokens.foreground.opacity(0.10) : DesignTokens.foreground.opacity(0.06))
} }
} }
.overlay(alignment: .leading) { .overlay(alignment: .leading) {
// `.side-button.current` inset accent bar. // `.side-button.current` inset accent bar — inset from the
// highlight's edges (leading 4; r6 mercury#49/52: vertical
// inset 6, the shared SelectedRowStrip capsule — radius-1
// ends, one step deeper-set than r4's 3) so it sits ON the
// fill, never half-off its rounded boundary.
if selected { if selected {
RoundedRectangle(cornerRadius: 1) SelectedRowStrip()
.fill(DesignTokens.accent) .padding(.leading, 4)
.frame(width: 2)
.padding(.vertical, 4)
} }
} }
.onHover { hover = $0 } .onHover { hover = $0 }
@@ -189,35 +217,68 @@ private struct ContentSettingsPage: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 4) { VStack(alignment: .leading, spacing: 4) {
// r6 (sol#12, argon#19, mercury#31): serif-15 — the PaneHeader
// face — with top padding 17: the title box (~18pt) centers in
// the sidebar's 52pt band ((52−18)/2 = 17), so 'Content' and
// 'Settings' baselines align exactly across the divider.
Text("Content") Text("Content")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Where the corpus lives.") Text("Where the corpus lives.")
.font(.system(size: 12)) .font(.system(size: 12))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
VStack(alignment: .leading, spacing: 14) { // r7 (ALL SEATS regression): the form stack is TOP-aligned and the
VStack(alignment: .leading, spacing: 4) { // page carries NO ScrollView — a single setting must fit the
SettingsFieldLabel("Museion Home") // viewport whole. The r6 ScrollView + minHeight proposal is what
HStack(spacing: 8) { // let ElidedPathText's greedy frame stretch the field card to
Text(home.path(percentEncoded: false)) // ~750pt; both are gone.
.font(.system(size: 12, design: DesignTokens.mono)) form
.lineLimit(1) .frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
.truncationMode(.middle) .frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled) }
Spacer(minLength: 12) .padding(.horizontal, 24)
Button("Choose…") { chooseHome() } .padding(.top, 17)
.buttonStyle(.bordered) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
} }
private var form: some View {
VStack(alignment: .leading, spacing: 14) {
// r5 (argon#21): label→field 6pt. r7: field→caption 8pt
// (the r6 6 squeezed the caption into the group).
VStack(alignment: .leading, spacing: 6) {
SettingsFieldLabel("Museion Home")
// r2: ONE bounded field-group row — surface fill + 1pt
// #E8E5DF hairline. r6: the path FILLS the row —
// glyph-measured slash-boundary elision (ElidedPathText)
// replaces character-middle truncation; Choose… stays
// intrinsic at the row's end with a FULL-strength
// hairline. r7 (ALL SEATS regression + mercury#55,
// argon#41): the row HUGS its intrinsic single-row
// height (~48pt) — symmetric inner padding 14 both
// sides, vertical 10 — and no child expands vertically.
HStack(spacing: 8) {
ElidedPathText(path: home.path(percentEncoded: false))
Button("Choose…") { chooseHome() }
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.help("Pick the folder holding your posts")
} }
.padding(.horizontal, 14)
.padding(.vertical, 10)
.background(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.border),
),
)
// r7: caption directly below the group — spacing 6 + 2 = 8pt.
Text("Repoint-only: Museion never moves content.") Text("Repoint-only: Museion never moves content.")
.font(.system(size: 11.5)) .font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.padding(.top, 2)
} }
.padding(.top, 12)
} }
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading) .padding(.top, 12)
.padding(.horizontal, 26)
.padding(.top, 18)
.padding(.bottom, 48)
} }
private func chooseHome() { private func chooseHome() {
@@ -231,3 +292,62 @@ private struct ContentSettingsPage: View {
} }
} }
} }
/// r6 (sol#12, argon#19, mercury#31): the Home path, glyph-measured
/// slash-boundary elision that FILLS the width. Candidates from the full
/// path down to `/first/…/last` (a growing leading run of components kept
/// whole, one `/…/` before the final component) are measured in the row's
/// REAL mono face (NSFont.monospacedSystemFont 12 — the same face
/// `.system(size: 12, design: .monospaced)` resolves to) against the
/// ACTUAL available width; the longest candidate that fits renders.
/// Character-middle truncation is the last resort only — the Text carries
/// `.truncationMode(.middle)` and it engages only when even
/// `/first/…/last` overflows. Internal + pure statics so a test can pin
/// the ladder.
struct ElidedPathText: View {
let path: String
var body: some View {
// r7 (ALL SEATS regression): fixed 16pt height, no maxHeight —
// the r6 greedy `.frame(maxHeight: .infinity)` let the
// GeometryReader swallow whatever the (now-deleted) ScrollView
// proposed and stretched the field card to ~750pt. Width stays
// flexible: the elision ladder needs the real available width.
GeometryReader { geo in
Text(Self.elide(path, into: geo.size.width))
.font(.system(size: 12, design: DesignTokens.mono))
.lineLimit(1)
.truncationMode(.middle)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(height: 16)
.help(path)
.accessibilityLabel(path)
}
/// The candidate ladder, longest first: the full path, then each
/// shorter variant with one more leading component kept whole.
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]
for keep in stride(from: comps.count - 3, through: 0, by: -1) {
ladder.append("/" + comps[0 ... keep].joined(separator: "/") + "/…/" + comps[comps.count - 1])
}
return ladder
}
/// The longest candidate whose glyph-measured width fits `width`.
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
}
let ladder = candidates(path)
// Nothing fitting (even `/first/…/last` overflows) falls through
// to the shortest candidate — the Text's character-middle
// truncation handles it (the documented last resort).
return ladder.first(where: fits) ?? ladder.last ?? path
}
}
+187 -30
View File
@@ -44,16 +44,28 @@ struct TrendsPaneView: View {
if series.isEmpty { if series.isEmpty {
emptyState emptyState
} else { } else {
ScrollView { // r5 (mercury#5/27/28, sol#10): the grid FILLS the pane's height
LazyVGrid( // — charts take the leftover height (≥130 floor), killing the
columns: [GridItem(.adaptive(minimum: 340), spacing: 12)], // bottom-third void; plots read ~3:1, not 5.3:1. The height
spacing: 12, // measurement must sit OUTSIDE the ScrollView (it proposes
) { // unbounded height); scroll engages only when floors overflow.
ForEach(TrendMetric.allCases, id: \.self) { metric in // ponytail: no aspect cap — cap at width/3 if lanky plots annoy.
MetricCard(metric: metric, series: series) GeometryReader { geo in
ScrollView {
LazyVGrid(
columns: [
GridItem(.flexible(), spacing: 12, alignment: .top),
GridItem(.flexible(), spacing: 12, alignment: .top),
],
spacing: 12,
) {
ForEach(TrendMetric.allCases, id: \.self) { metric in
MetricCard(metric: metric, series: series, chartHeight: filledChartHeight(geo.size.height))
}
} }
.padding(14)
.frame(minHeight: geo.size.height, alignment: .top)
} }
.padding(14)
} }
} }
} }
@@ -79,6 +91,22 @@ struct TrendsPaneView: View {
} }
} }
private extension TrendsPaneView {
/// (paneHeight − grid padding 28 − row gap 12) / 2, minus each card's
/// fixed chrome (~136: padding 28 + title + spacings + readout +
/// explain); floored at 130 for short windows. r7 (argon#16/26/27,
/// sol#35, mercury#53): the chrome estimate is deliberately GENEROUS —
/// the r6 120 left the grid at the viewport's exact edge, where a
/// hair of rounding tipped it into a scrollbar. Plot heights yield
/// so all four cards + the symmetric 14pt top/bottom padding fit
/// with slack. r8 (sol#4, mercury#14): ×0.87 — a modest ~13% plot
/// reduction so the thin variance bands sit in less empty frame;
/// y-domains stay FIXED (final).
func filledChartHeight(_ paneHeight: CGFloat) -> CGFloat {
max(130, ((paneHeight - 28 - 12) / 2 - 136) * 0.87)
}
}
/// One metric's display facts: name, value rail, better-direction, and a /// One metric's display facts: name, value rail, better-direction, and a
/// fixed y-domain so single captures stay visible and scales read the /// fixed y-domain so single captures stay visible and scales read the
/// same across sessions. Pure — pinned in TrendViewTests. /// same across sessions. Pure — pinned in TrendViewTests.
@@ -139,6 +167,20 @@ nonisolated enum TrendMetric: CaseIterable {
} }
} }
/// One tick convention across all four cards (ui-polish r2): the
/// domain's two bounds plus its midpoint — the zero line always
/// reads on nonnegative domains (0…1 cards showed only 1.0/0.5),
/// and the symmetric burstiness axis keeps its center. Exactly
/// three labels per card.
func ticks(peak: Double) -> [Double] {
let domain = domain(peak: peak)
return [
domain.lowerBound,
(domain.lowerBound + domain.upperBound) / 2,
domain.upperBound,
]
}
/// First capture vs last: the pane's whole judgment, one honest word /// First capture vs last: the pane's whole judgment, one honest word
/// (#32 AC — the arc, never a draft grade). Deltas inside the noise /// (#32 AC — the arc, never a draft grade). Deltas inside the noise
/// band read steady: ±0.01 at three-decimal grain. /// band read steady: ±0.01 at three-decimal grain.
@@ -155,8 +197,11 @@ nonisolated enum TrendMetric: CaseIterable {
} }
} }
/// The first→last read on one metric. Not a grade — a direction. Raw /// The first→last read on one metric. Not a grade — a direction. The
/// values ARE the display words. /// rawValue IS the display word; polarity (which way reads better)
/// rides the card-header badge alone (↑/↓ better) — never an arrow in
/// the summary line (ui-polish r2: a value arrow there conflated
/// rise/fall with better/worse on ↓-better metrics).
nonisolated enum TrendDirection: String { nonisolated enum TrendDirection: String {
case improving case improving
case steady case steady
@@ -169,6 +214,8 @@ nonisolated enum TrendDirection: String {
private struct MetricCard: View { private struct MetricCard: View {
let metric: TrendMetric let metric: TrendMetric
let series: [Post] let series: [Post]
/// r5: the pane hands each chart the height its grid row has left.
let chartHeight: CGFloat
private struct MetricPoint { private struct MetricPoint {
let captured: Date let captured: Date
@@ -201,62 +248,157 @@ private struct MetricCard: View {
} }
} }
/// The observed peak — feeds the sentence-variation domain + ticks.
private var peak: Double {
points.map(\.value).max() ?? 0
}
/// Distinct capture dates, oldest first — the x-axis ticks. The
/// captures ARE the data points; weekly grid ticks that miss them
/// are noise (ui-polish r2). A same-day pair shares one label
/// instead of overprinting.
private var tickDates: [Date] {
var seen = Set<Date>()
return points.map(\.captured).filter { seen.insert($0).inserted }
}
var body: some View { var body: some View {
// r7 (ALL SEATS regression): the '−1…1 divergent' caption is
// DELETED — it rendered outside the card in the grid gutter (its
// extra height is what made the row gap read ~2.5× the column
// gap and tipped the grid into a scrollbar), and the burstiness
// axis labels already carry the range (1.0 / 0.0 / −1.0).
card
}
private var card: some View {
VStack(alignment: .leading, spacing: 10) { VStack(alignment: .leading, spacing: 10) {
HStack(alignment: .firstTextBaseline) { HStack(alignment: .firstTextBaseline) {
Text(metric.title) Text(metric.title)
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(1)
Spacer() Spacer()
// r6 (sol#38): the badge carries direction ONLY. r7: the
// '−1…1 divergent' note is gone — the axis labels carry it.
Text(metric.higherIsBetter ? "↑ better" : "↓ better") Text(metric.higherIsBetter ? "↑ better" : "↓ better")
.font(.system(size: 10, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
} }
Chart { Chart {
marks marks
} }
.chartYScale(domain: metric.domain(peak: points.map(\.value).max() ?? 0)) .chartYScale(domain: metric.domain(peak: peak))
.chartYAxis { .chartXAxis {
AxisMarks { _ in // One centered label under each actual capture date —
AxisGridLine() // capture-aligned, "Oct 5" (month first, POSIX-locked so a
.foregroundStyle(DesignTokens.border) // European locale never renders "5. Oct"). r4: collisionResolution
AxisValueLabel() // .disabled + centered — the default resolver both nudged labels
.font(.system(size: 10, design: DesignTokens.mono)) // ~4px off their points and DROPPED the compressed
.foregroundStyle(DesignTokens.muted) // final-interval capture's date entirely (mercury#35/36);
// every capture gets its date now. r6 (argon#47) VERIFIED:
// AxisMarks(values:) places each mark at the capture instant
// and `centered: true` centers the label on it — ticks sit
// exactly under their capture dates (same-day twins share
// one label by design, tickDates dedupes).
// ponytail: tightly-spaced captures can overprint — day-only
// labels or hairline leaders if a dense arc ever needs them.
AxisMarks(values: tickDates) { value in
AxisValueLabel(centered: true, collisionResolution: .disabled) {
if let date = value.as(Date.self) {
Text(Self.dateFmt(date))
// r8 (sol#4, mercury#14): axis/summary one
// rung up — 11 → 12.
.font(.system(size: 12, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
} }
} }
.frame(height: 130) .chartYAxis {
// Value labels live OUTSIDE the plot, in a dedicated
// trailing axis gutter, vertically centered on their
// gridlines — in-plot labels collided with the series and
// end markers (Burstiness near 0.0, Sentence Variation
// near 0.5). One tick convention: domain bounds + midpoint.
AxisMarks(position: .trailing, values: metric.ticks(peak: peak)) { value in
AxisGridLine()
// r6 (sol#21, mercury#55): one contrast step up from
// border — quiet, but readable against the surface.
.foregroundStyle(DesignTokens.muted.opacity(0.35))
AxisValueLabel {
if let axisValue = value.as(Double.self) {
// FIXED-width gutter, r4 (sol#8, mercury#34/60).
// r6 (sol#39): the text is RIGHT-aligned — mono
// %.1f keeps the fractional width constant, so
// '−1.0' / '0.0' / '1.0' share one decimal
// column, and the glyphs move AWAY from the plot
// (more marker daylight), not toward it.
Text(Self.axisFmt(axisValue))
// r8 (sol#4, mercury#14): one rung up —
// 11 → 12 (36pt gutter still fits '−1.0').
.font(.system(size: 12, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.frame(width: 36, alignment: .trailing)
}
}
}
}
// r6 (mercury#28/55): 30pt trailing breathing room inside the
// plot — the r5 shots still showed near-touches between the
// last marker and the '0.5' label; one more touch of daylight.
.chartPlotStyle { $0.padding(.trailing, 30) }
.frame(height: chartHeight)
.accessibilityLabel("\(metric.title) across \(points.count) captures") .accessibilityLabel("\(metric.title) across \(points.count) captures")
readout readout
// #32 follow-up: the term's always-visible gloss — prose voice, // #32 follow-up: the term's always-visible gloss — prose voice,
// distinct from the mono data lines above it. // distinct from the mono data lines above it. Fixed two-line
// frame so wrapping never grows the card.
Text(metric.explain) Text(metric.explain)
.font(.system(size: 11)) .font(.system(size: 11))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.lineLimit(2)
.truncationMode(.tail)
.frame(maxWidth: .infinity, minHeight: 28, alignment: .topLeading)
} }
.padding(14) .padding(14)
.background(DesignTokens.surface) .background(DesignTokens.surface)
.overlay( .overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius) RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.border), // r6 (sol#21, mercury#55): one contrast step up from
// border — same step as the gridlines, quiet but present.
.strokeBorder(DesignTokens.muted.opacity(0.35)),
) )
} }
/// mono-11 first→last line; the color carries the direction (accent up, /// mono-12 first→last line, typographically weighted (r5): numbers in
/// orange slipping — the stale-anchor deviation color, muted steady). /// primary ink, the verdict word one weight heavier. Polarity rides the
/// card-header badge (↑/↓ better) alone — an arrow here conflated
/// value direction with quality (ui-polish r2: "0.052 → 0.093 · ↓
/// slipping" on the one metric where rising reads worse).
/// r8 (sol#4, mercury#14): one rung up — 11 → 12.
@ViewBuilder @ViewBuilder
private var readout: some View { private var readout: some View {
let values = points.map(\.value) let values = points.map(\.value)
if values.count >= 2 { if values.count >= 2 {
let verdict = metric.verdict(first: values.first!, last: values.last!) let verdict = metric.verdict(first: values.first!, last: values.last!)
Text("\(Self.fmt(values.first!)) → \(Self.fmt(values.last!)) · \(verdict.rawValue)") // r5 (argon#18): emphasis — numbers primary ink, verdict one
.font(.system(size: 11, design: DesignTokens.mono)) // weight heavier; NO new hues (polarity stays on the badge).
.foregroundStyle( Group {
verdict == .improving ? DesignTokens.accent : verdict == .slipping ? .orange : DesignTokens.muted, Text("\(Self.fmt(values.first!)) → \(Self.fmt(values.last!))")
) .foregroundStyle(DesignTokens.foreground)
+ Text(" · ")
.foregroundStyle(DesignTokens.muted)
+ Text(verdict.rawValue)
.fontWeight(.medium)
.foregroundStyle(DesignTokens.foreground)
}
.font(.system(size: 12, design: DesignTokens.mono))
.lineLimit(1)
} else if let only = values.first { } else if let only = values.first {
Text("\(Self.fmt(only)) · one capture") Text("\(Self.fmt(only)) · one capture")
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 12, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.lineLimit(1)
} }
} }
@@ -264,4 +406,19 @@ private struct MetricCard: View {
private static func fmt(_ value: Double) -> String { private static func fmt(_ value: Double) -> String {
String(format: "%.3f", value) String(format: "%.3f", value)
} }
/// Axis labels at %.1f — the same period-only convention as the readout.
private static func axisFmt(_ value: Double) -> String {
String(format: "%.1f", value)
}
/// "Oct 5" — month first, day without a leading zero. POSIX-locked:
/// the machine's European locale never swaps in "5. Oct" (per-access
/// formatter, the repo's no-static convention).
private static func dateFmt(_ date: Date) -> String {
let fmt = DateFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.dateFormat = "MMM d"
return fmt.string(from: date)
}
} }
+152 -30
View File
@@ -320,7 +320,7 @@ struct WorkspaceView: View {
VStack(spacing: 8) { VStack(spacing: 8) {
RailButton(pane: .posts, selection: $selection, label: "Posts", systemImage: "doc.text") RailButton(pane: .posts, selection: $selection, label: "Posts", systemImage: "doc.text")
RailButton(pane: .sessions, selection: $selection, label: "Sessions", systemImage: "bubble.left") RailButton(pane: .sessions, selection: $selection, label: "Sessions", systemImage: "bubble.left")
RailButton(pane: .learnings, selection: $selection, label: "Learnings", systemImage: "cube") RailButton(pane: .learnings, selection: $selection, label: "Learnings", systemImage: "cube", weight: .light)
// #32: Trends after Learnings — measurement beside memory. // #32: Trends after Learnings — measurement beside memory.
RailButton(pane: .trends, selection: $selection, label: "Trends", systemImage: "chart.xyaxis.line") RailButton(pane: .trends, selection: $selection, label: "Trends", systemImage: "chart.xyaxis.line")
Spacer() Spacer()
@@ -338,7 +338,7 @@ struct WorkspaceView: View {
// #108: Archive at the rail bottom, above Settings (prototype's // #108: Archive at the rail bottom, above Settings (prototype's
// box icon). // box icon).
RailButton(pane: .archive, selection: $selection, label: "Archive", systemImage: "archivebox") RailButton(pane: .archive, selection: $selection, label: "Archive", systemImage: "archivebox")
RailButton(pane: .settings, selection: $selection, label: "Settings", systemImage: "gearshape") RailButton(pane: .settings, selection: $selection, label: "Settings", systemImage: "gearshape", weight: .light)
} }
.padding(.horizontal, 4) .padding(.horizontal, 4)
.padding(.vertical, 8) .padding(.vertical, 8)
@@ -378,7 +378,9 @@ private struct ArchivePaneView: View {
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
// No New button — things arrive here by being moved, not created. // No New button — things arrive here by being moved, not created.
PaneHeader(title: "Archive") // r8 (argon#9, mercury#18/19): the hairline is bounded to the SAME
// fixed 720pt column the rows live in — one framed block.
PaneHeader(title: "Archive", hairlineMaxWidth: 720)
if archivedByProject.isEmpty { if archivedByProject.isEmpty {
emptyState emptyState
} else { } else {
@@ -389,9 +391,23 @@ private struct ArchivePaneView: View {
let pieces = archivedByProject[project] ?? [] let pieces = archivedByProject[project] ?? []
// Same section-head shape as the library (#108 // Same section-head shape as the library (#108
// variant B), plus the project-level way out. // variant B), plus the project-level way out.
HStack(alignment: .firstTextBaseline, spacing: 8) { // r7 (mercury#55, argon#41 — FINAL, supersedes the
// r6 D24 ladder): the content column is a FIXED
// 720pt frame (width, not maxWidth — the r6
// content-hugging bound let the pill define the
// right edge), left-anchored. TWO axes only, the
// library's r7 ladder: the head row leads at x14
// (chevron in a 14pt slot) with its label at x28 —
// the ONE indent, shared with the entry rows'
// inner text via the shared LibraryPostRow (cards
// lead at x14); the 'Unarchive Group' pill rides
// the header row's trailing edge INSIDE the frame
// (14 → 706), and the row hairlines are bounded by
// the same frame. Nothing spans past it.
HStack(alignment: .firstTextBaseline, spacing: 0) {
Image(systemName: "chevron.down") Image(systemName: "chevron.down")
.font(.system(size: 9, weight: .semibold)) .font(.system(size: 10, weight: .semibold))
.frame(width: 14, alignment: .leading)
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0)) .rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
.onTapGesture { .onTapGesture {
@@ -400,8 +416,10 @@ private struct ArchivePaneView: View {
.accessibilityLabel("Toggle \(project)") .accessibilityLabel("Toggle \(project)")
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded") .accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
Text(project) Text(project)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) .font(.system(size: 11, weight: .medium, design: DesignTokens.mono))
.textCase(.lowercase) // #108: display-only — the folder name keeps its case .kerning(0.6)
.textCase(.uppercase) // #108: display-only — the folder name keeps its case
.foregroundStyle(DesignTokens.muted) // r6: full ink — contrast final
.lineLimit(1) .lineLimit(1)
.truncationMode(.tail) .truncationMode(.tail)
.onTapGesture { .onTapGesture {
@@ -410,25 +428,40 @@ private struct ArchivePaneView: View {
Text("· \(pieces.count)") Text("· \(pieces.count)")
.font(.system(size: 11, design: DesignTokens.mono)) .font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted) .foregroundStyle(DesignTokens.muted)
Spacer(minLength: 0) .padding(.leading, 8)
Button("Unarchive") { Spacer(minLength: 8)
// The 'New Post · Fork · Compact' language — a
// bordered mono-11 secondary pill at the
// trailing edge INSIDE the fixed 720pt frame.
// r7 (mercury#55, argon#41): relabeled
// 'Unarchive Group' — it moves the whole
// project, not one piece.
Button("Unarchive Group") {
model.unarchiveProject(project, home: home) model.unarchiveProject(project, home: home)
} }
.buttonStyle(.plain) .buttonStyle(BorderedSecondaryButtonStyle(minHeight: 24))
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.help("Move the whole project back to projects/") .help("Move the whole project back to projects/")
.accessibilityLabel("Unarchive \(project)") .accessibilityLabel("Unarchive \(project)")
} }
.padding(.top, 16) .padding(.top, 12)
.padding(.horizontal, 14) .padding(.horizontal, 14)
.padding(.bottom, 6) .padding(.bottom, 2)
if !collapsed.contains(project) { if !collapsed.contains(project) {
ForEach(pieces) { post in ForEach(pieces) { post in
// r7: the shared LibraryPostRow ladder —
// card leads at x14 (PRIMARY), title text
// at x28 (the one indent). The hairline is
// BOUNDED to the fixed frame: x14 → 706.
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) { LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home) model.select(post.id, home: home)
onOpenPiece() onOpenPiece()
} }
.overlay(alignment: .bottom) {
Rectangle()
.fill(DesignTokens.border)
.frame(height: 1)
.padding(.horizontal, 14)
}
.contextMenu { .contextMenu {
Button("Move Back to \(post.project)") { Button("Move Back to \(post.project)") {
model.restorePost(post, home: home) model.restorePost(post, home: home)
@@ -446,6 +479,15 @@ private struct ArchivePaneView: View {
} }
} }
} }
// r7 (mercury#55, argon#41): the FIXED 720pt reading
// column — width, not maxWidth (the r6 content-hugging
// bound let the pill define the right edge); rows,
// hairlines, and the pill all live inside it.
// ponytail: fixed width clips on panes narrower than
// 720 — a width-floored variant if a small-window
// Archive ever matters.
.frame(width: 720, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 12) .padding(.bottom, 12)
} }
} }
@@ -647,13 +689,36 @@ private struct NewProjectSheet: View {
} }
} }
/// Rail button per the export: 44×44 muted icon, hover wash, and the current /// Rail button: 44×44 muted icon, hover wash, the current pane raised as
/// pane raised as a surface card with a 2px selection bar on the rail's edge. /// a tile. NO visible edge bar — ui-polish r2 re-ruling: the export's
/// `::before` selection bar paints behind the app border in the export's
/// own render, so a visible bar reads as a stray clipped mark;
/// contract-faithful is tile + border + fg-ink icon alone.
/// r5 (sol#40, mercury#54/56 — one final strength step, modest): the
/// selected tile's fill steps from surface (invisible on the chrome
/// background) to a 0.08 foreground wash with a muted-0.4 hairline — the
/// fg-ink glyph reads stronger against it. Icon weight stays constant
/// (sol#45: selection emphasis comes from the tile, never the glyph).
private struct RailButton: View { private struct RailButton: View {
let pane: WorkspaceView.Pane let pane: WorkspaceView.Pane
@Binding var selection: WorkspaceView.Pane @Binding var selection: WorkspaceView.Pane
let label: String let label: String
let systemImage: String let systemImage: String
/// sol#45: one explicit size for all six icons; glyph-dense ones (cube,
/// gearshape) opt down a weight so every icon reads the same apparent
/// mass — selection emphasis comes from the tile, never icon weight.
var weight: Font.Weight = .regular
/// r7 (sol#33): the selected glyph's ONE step up (light→regular,
/// regular→medium) — full-ink color on thin strokes still read
/// near-muted; the step puts the current pane's icon at true ink.
private var selectedWeight: Font.Weight {
switch weight {
case .light: .regular
default: .medium
}
}
@State private var hover = false @State private var hover = false
var body: some View { var body: some View {
@@ -662,6 +727,11 @@ private struct RailButton: View {
selection = pane selection = pane
} label: { } label: {
Image(systemName: systemImage) Image(systemName: systemImage)
// r7 (sol#33): the selected glyph steps ONE weight up —
// full ink on a thin-stroke symbol at .light/.regular
// reads near-muted against the 0.08 wash. Unselected
// icons keep their sol#45 mass exactly.
.font(.system(size: 16, weight: selected ? selectedWeight : weight))
.frame(width: 44, height: 44) .frame(width: 44, height: 44)
} }
.buttonStyle(.plain) .buttonStyle(.plain)
@@ -669,37 +739,86 @@ private struct RailButton: View {
.background { .background {
if selected || hover { if selected || hover {
RoundedRectangle(cornerRadius: DesignTokens.radius) RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06)) // r5 (sol#40, mercury#54/56): selected = a 0.08
// foreground wash + muted-0.4 hairline (surface-on-
// chrome was invisible); hover keeps the 0.06 wash,
// borderless. Modest — the hierarchy holds.
.fill(selected ? DesignTokens.foreground.opacity(0.08) : DesignTokens.foreground.opacity(0.06))
.overlay( .overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius) RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(selected ? DesignTokens.border : .clear), .strokeBorder(selected ? DesignTokens.muted.opacity(0.4) : .clear),
) )
} }
} }
.overlay(alignment: .leading) {
// Selection bar (`.rail-btn[aria-current]::before`); offset to sit
// on the rail's leading edge like the export's negative inset.
if selected {
Rectangle()
.fill(DesignTokens.foreground)
.frame(width: 2, height: 22)
.offset(x: -6)
}
}
.onHover { hover = $0 } .onHover { hover = $0 }
.help(label) .help(label)
.accessibilityLabel(label) .accessibilityLabel(label)
} }
} }
/// r6 (mercury#49/52, argon#13): the shared selected-row strip — a 2pt
/// accent capsule with radius-1 rounded ends, vertically inset 6pt from
/// the row's edges so it sits INSIDE the card/fill (Posts library rows,
/// Settings sidebar rows). Callers toggle it via opacity so the 2pt
/// reservation keeps layout constant.
struct SelectedRowStrip: View {
var body: some View {
RoundedRectangle(cornerRadius: 1)
.fill(DesignTokens.accent)
.frame(width: 2)
.padding(.vertical, 6)
}
}
/// ui-polish r2: the app's bordered secondary button — mono-11 ink on a
/// 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.
struct BorderedSecondaryButtonStyle: ButtonStyle {
var minHeight: CGFloat = 36
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.foreground)
.padding(.horizontal, 12)
.frame(minHeight: minHeight)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: 8)
.strokeBorder(DesignTokens.border),
),
)
.opacity(configuration.isPressed ? 0.7 : 1)
}
}
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border). /// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`). /// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
struct PaneHeader<Trailing: View>: View { struct PaneHeader<Trailing: View>: View {
let title: String let title: String
/// Leading inset of the title row. Export default 14; the Learnings pane
/// passes 26 so its title shares one leading edge with headings + rows.
var titleInset: CGFloat = 14
/// r8 (argon#9, mercury#18/19 — convergent): when set, the bottom
/// hairline is bounded to the same column the pane's content sits in
/// (Archive/Learnings' 720pt reading column) — title, hairline, and
/// content read as one framed block instead of a full-width rule over
/// a bounded column. nil = full width (every other pane's default).
var hairlineMaxWidth: CGFloat?
@ViewBuilder var trailing: () -> Trailing @ViewBuilder var trailing: () -> Trailing
init(title: String, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }) { init(
title: String,
titleInset: CGFloat = 14,
hairlineMaxWidth: CGFloat? = nil,
@ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() },
) {
self.title = title self.title = title
self.titleInset = titleInset
self.hairlineMaxWidth = hairlineMaxWidth
self.trailing = trailing self.trailing = trailing
} }
@@ -711,11 +830,14 @@ struct PaneHeader<Trailing: View>: View {
Spacer() Spacer()
trailing() trailing()
} }
.padding(.horizontal, 14) .padding(.horizontal, titleInset)
.frame(minHeight: 52) .frame(minHeight: 52)
Rectangle() Rectangle()
.fill(DesignTokens.border) .fill(DesignTokens.border)
.frame(height: 1) .frame(height: 1)
// r8: the bound shares the content column's leading edge
// (x0) and width — leading-aligned, never centered.
.frame(maxWidth: hairlineMaxWidth ?? .infinity, alignment: .leading)
} }
} }
} }
+29
View File
@@ -444,6 +444,35 @@ struct ACPClientTests {
#expect(SessionTranscriptView.speaker(of: "A = Pass 1 start snapshot · B = current document") == .system) #expect(SessionTranscriptView.speaker(of: "A = Pass 1 start snapshot · B = current document") == .system)
} }
/// Round-6 ui-polish (all seats): the warning row's headline/detail
/// split — speaker prefix dropped, then the first ": " separates the
/// headline from the muted detail line (no ": " → headline only).
@Test func `warningParts splits headline from detail`() {
let interrupted = SessionTranscriptView.warningParts(
"Mentor: Operation interrupted: waiting for model response (61.6s elapsed).",
)
#expect(interrupted.headline == "Operation interrupted")
#expect(interrupted.detail == "waiting for model response (61.6s elapsed).")
let lost = SessionTranscriptView.warningParts("connection lost")
#expect(lost.headline == "connection lost")
#expect(lost.detail == nil)
}
/// Round-8 ui-polish (argon#8 — calm copy): the engine's own
/// interruption detail, rephrased verbatim-safe — only the known
/// "waiting for model response (X elapsed)" phrasing rewrites; any
/// other detail passes through untouched (no invented states).
@Test func `calmDetail rephrases only the engine's known phrasing`() {
#expect(SessionTranscriptView.calmDetail("waiting for model response (61.6s elapsed).")
== "waiting on the model — 61.6s")
#expect(SessionTranscriptView.calmDetail("waiting for model response (2m 10s elapsed)")
== "waiting on the model — 2m 10s")
#expect(SessionTranscriptView.calmDetail("the engine process exited")
== "the engine process exited")
#expect(SessionTranscriptView.calmDetail("waiting for model response ( elapsed)")
== "waiting for model response ( elapsed)")
}
/// #155 audit (security): the link-open gate — interpreted markdown /// #155 audit (security): the link-open gate — interpreted markdown
/// opens http(s) only; every other scheme (file:, mailto:, custom app /// opens http(s) only; every other scheme (file:, mailto:, custom app
/// schemes) is discarded. Engine prose echoes imported content, so a /// schemes) is discarded. Engine prose echoes imported content, so a
+2
View File
@@ -34,6 +34,8 @@ 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 · <title>" 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. - `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 · <title>" 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. - `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). - `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. 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). - `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). - `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).
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. - `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
+47
View File
@@ -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")
}
}
+92
View File
@@ -0,0 +1,92 @@
//
// SessionScopeTests.swift
// MuseionTests
//
// Owner ruling (2026-11-07): the Mentor pane hosts the OPEN PIECE's
// session — the pure seam over the roster (exact pieceTitle match,
// newest-first) pinned here: match, no-match, and title-with-no-roster.
//
import Foundation
@testable import Museion
import Testing
@Suite("SessionScopeTests")
struct SessionScopeTests {
/// The roster is newest-first (the model's own order), so the FIRST
/// exact pieceTitle match is the newest session for the piece. No
/// match — including near-misses, no open piece, or no roster at all —
/// hosts nothing: nil, the pane's honest empty presentation.
@Test func `hosted session id picks newest exact piece title match`() {
let older = SessionEntry(
sessionId: "s-old", name: "Old", pieceTitle: "Essay X",
createdAt: Date(timeIntervalSinceNow: -600),
)
let newer = SessionEntry(sessionId: "s-new", name: "New", pieceTitle: "Essay X", createdAt: Date())
let other = SessionEntry(sessionId: "s-other", name: "Other", pieceTitle: "Draft Y", createdAt: Date())
let roster = [newer, older, other] // newest-first, as the model keeps it
// Match — the newest session for the piece wins; a different piece
// finds its own.
#expect(SessionRoster.hostedSessionId(forOpenPieceTitle: "Essay X", in: roster) == "s-new")
#expect(SessionRoster.hostedSessionId(forOpenPieceTitle: "Draft Y", in: roster) == "s-other")
// No match — EXACT match only; near-misses never host.
#expect(SessionRoster.hostedSessionId(forOpenPieceTitle: "essay x", in: roster) == nil)
#expect(SessionRoster.hostedSessionId(forOpenPieceTitle: "Unwritten", in: roster) == nil)
// No open piece (draft, external guest, nothing) hosts nothing.
#expect(SessionRoster.hostedSessionId(forOpenPieceTitle: nil, in: roster) == nil)
// 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)
}
}
@@ -0,0 +1,69 @@
//
// WordBoundaryTruncationTests.swift
// 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) →
// Round-8 head-biased split (sol#3): the roster title's truncation
// seam. The r7 split kept only the "Pass N ·" label and maximized the
// suffix — the unique head (the topic) died at the same elision point
// as before; the seam now grows the head into ~60% of the glyph budget
// (label + leading words) and fits the longest suffix in what remains.
// Pins: short-string passthrough, the mid-word head cut landing at a
// word edge, and the exact strings for the two live Handoff roster
// titles.
//
import CoreGraphics
import Foundation
@testable import Museion
import Testing
@Suite("WordBoundaryTruncationTests")
struct WordBoundaryTruncationTests {
@Test func `short string passes through`() {
#expect(WordBoundaryTruncation.fit("Brainstorm", maxWidth: 192) == "Brainstorm")
#expect(WordBoundaryTruncation.fit("Pass 1 · The expected value of showing up", maxWidth: 192)
== "Pass 1 · The expected value of showing up")
#expect(WordBoundaryTruncation.fit("", maxWidth: 192) == "")
}
@Test func `mid word cut lands at word boundary`() {
// The native cut rendered "Markdo…" — with no suffix fitting
// beside the head, the head truncates at its word edge.
let out = WordBoundaryTruncation.fit("Markdown Notes", maxWidth: 80, lines: 1)
#expect(out == "Markdown…")
#expect(!out.hasSuffix("Markdo…"))
}
@Test func `handoff titles split head biased`() {
// Round-7 (argon#14/sol#32/47): the two live Handoff roster
// titles died at the shared "Reading-Mode Pivot:…" boilerplate —
// the distinguishing tail never rendered. Round-8 (sol#3): the
// split biases toward the TOPIC — the head keeps the label plus
// the leading words ("Museion Handoff —", ~60% of the glyph
// budget, measured serif-13 semibold against the roster's 192pt
// two-line width); the shared tail shrinks to the longest suffix
// that still fits ("apex) vs. Hand-rolled TextKit" — r7's was
// the full "→ HTML (+ apex) vs. Hand-rolled TextKit").
let pass2 = "Pass 2 · Museion Handoff — Reading-Mode Pivot: Markdown → HTML (+ apex) vs. Hand-rolled TextKit"
let pass1 = "Pass 1 · Museion Handoff — Reading-Mode Pivot: Markdown → HTML (+ apex) vs. Hand-rolled TextKit"
#expect(WordBoundaryTruncation.fit(pass2, maxWidth: 192, lines: 2)
== "Pass 2 · Museion Handoff — … apex) vs. Hand-rolled TextKit")
#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)
}
}