perf(editor): scope fold re-key to the edit (#142)
CI / ci (push) Canceled after 0s

With a fold open, every keystroke re-scanned the buffer, rebuilt the
full attributed string through setAttributedString (invalidating
TextKit layout for the ENTIRE document — O(n²) typing on folded
documents), and rasterized a chrome image the size of the document
(~35M pixels on a 700×50,000pt doc) to paint a handful of chevrons.

Single-line edits now re-key folds in place: a shouldChangeText
override records the edit (range + UTF-16 delta) and a pure rekey
function shifts surviving folds, kills folds whose marker line was
edited (un-hiding just that scope), and re-hides a line edited inside
a hidden scope — no parents rescan, no storage swap. Structural
edits, multi-line pastes, and wholesale loads keep the full pass; a
font probe at each survivor's scope head falls back to it whenever
hidden styling was wiped (the fence-flip restyle self-heals this way).

Chrome renders as one tiny cached layer per list parent (same glyph
rasters at ~15×18pt, geometry-flipped into the existing document-space
overlay) instead of the document-sized bitmap; an edit at/after every
parent line skips the rebuild outright, so writing at the document end
does zero geometry queries. Full-buffer scans per keystroke drop from
2–3 to one.

Finish-audit hardening: the single-line gate checks Character.isNewline
(a literal newline compare passes CRLF — one grapheme equal to neither
scalar), and apply() clears the recorded edit so structural indent/
outdent always takes the full pass (a childless unterminated block's
shift-tab is a single-line replacement that would otherwise keep a
dead fold's scope hidden — apparent line loss).

Closes #142
This commit is contained in:
AlexKucera committed 2026-11-03 10:40:14 +01:00
1 parent de1154dacd
commit cc317b65b9
9 files changed
+687 -114

No files matched your search

+3 -2
View File
@@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (5702 symbols, 23152 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** (5755 symbols, 23498 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).
@@ -182,6 +182,7 @@ This project is indexed by GitNexus as **museion** (5702 symbols, 23152 relation
- Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33)
- When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift <file>` check of the pure logic still verify honestly (#134)
- A wrapped condition list gets its brace pushed to its own line by swiftformat, which swiftlint's opening_brace then flags — avoid the wrap (nested ifs / a hoisted helper), don't fight the formatter (#142)
### Trust boundaries
- A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6)
- A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34)
@@ -194,6 +195,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-11-03 | [20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md](docs/devlog/20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md) |
| 2026-11-02 | [20261102-issue141-image-drop-illustration-ingest_log.md](docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md) |
| 2026-11-01 | [20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md](docs/devlog/20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md) |
| 2026-10-31 | [20261031-issue33-m6-micropub-draft-publish-s6-1_log.md](docs/devlog/20261031-issue33-m6-micropub-draft-publish-s6-1_log.md) |
@@ -203,5 +205,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-30 | [20261030-issue1-verify-style-constraints-prompt-end_log.md](docs/devlog/20261030-issue1-verify-style-constraints-prompt-end_log.md) |
| 2026-10-28 | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](docs/devlog/20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) |
| 2026-10-27 | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](docs/devlog/20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) |
| 2026-10-27 | [20261027-issue135-profiles-s2-settings-page-ui_log.md](docs/devlog/20261027-issue135-profiles-s2-settings-page-ui_log.md) |
<!-- write-log: window-end -->
+4
View File
@@ -74,6 +74,10 @@ All notable changes to this project will be documented in this file. The format
- **skills:** Craft canon distilled from the #4 shortlist — rhetoric (Heinrichs: argument and rhetoric, ten cards plus the fallacy index), reader-psychology (Williams: the reader-processing diagnosis sequence), prose-craft (Clark: fifteen generative tools across better-words, structure, humor, revision); a sample Pass demonstrates all three firing as fix cards (issue #7)
- **skills:** Titles-and-hooks craft skill distilled from web sources per the #4 research — the title surface (takeaway over label, bounded numbers, the worn tease, mode fit, person over committee voice) and the hook's curiosity gap (open it, foot it, honor the title–hook contract), every rule data-backed; the sample Pass gains a ninth fix card demonstrating the shelf (issue #11)
### Changed
- **editor:** Typing beside an open fold no longer rebuilds the whole document (#142) — with a fold live, every keystroke used to re-scan the buffer, rebuild the full attributed string (invalidating TextKit layout document-wide → O(n²) typing on folded documents), and rasterize a chrome image the SIZE OF THE DOCUMENT (~35M pixels on a tall doc) to paint a handful of chevrons. Single-line edits now re-key folds in place (pure delta math: shifts, marker-line deaths, scope re-hides) with no rescan and no storage swap; structural edits, multi-line pastes, and wholesale restyles keep the full pass, and a font-probe fallback self-heals any restyle that wipes the hidden styling. Chevrons/⋯N render as one tiny cached layer per list parent instead of the document-sized bitmap, and an edit below every parent skips the chrome rebuild outright. Finish-audit hardening: the single-line gate is `isNewline` (a literal `"\n"`/`"\r"` compare passes CRLF — one grapheme equal to neither), and structural indent/outdent always takes the full pass (a childless unterminated block's ⇧⇥ is a single-line edit that would keep a dead fold's scope hidden). Fifteen fold/rekey tests incl. a flip-verified audit cycle; suite 570 (issue #142)
### Fixed
- **mentor:** live passes no longer read as crashes — `session/prompt` waits pass-length (1800 s, not the 15 s request default that abandoned working turns with a false "connection lost"), a liveness row shows the engine thinking, Stop stays for the whole turn, and a missing `stopReason` never advances a pass
+1 -1
View File
@@ -37,7 +37,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `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.
- 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. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting. **#141 illustration ingest:** window-level SwiftUI `.dropDestination`s STARVE every deeper drag destination — an NSTextView registered for `.fileURL` never received one callback, and a nested editor-level SwiftUI destination never fired either, while `WorkspaceView`'s #91 window destination claimed every drag (green copy badge, silent refusal; field-verified 2026-11-02 via stderr tracing — the docs' nested/innermost-first destination model does NOT hold; one window-level target is the whole routing surface). Routing inside its perform: a PURE-markdown set (`allSatisfy` — a mixed md+image set falls through and refuses loudly, finish-audit 2026-11-02; images must not vanish silently behind the md) forwards through `openExternal` (#91's open-as-guest preserved), everything else bridges through `ProseDropBridge` (app-scoped on `AppGateState.proseDrop`, weak live-text-view handle, set in ProseTextView make/updateNSView, non-optional at both constructor call sites) into `ProseListTextView.ingestDrop(_:)`: gates = non-nil `ingestFolder` (saved posts only — drafts/guests get the strip) + every file publishable (#34's `Micropub.mimeType` set; mixed md+image refuses too), then copies each URL via `PostStore.ingestImage` and inserts the joined `illustrationRef`s at the drop point. The source must be a PLAIN file — a dropped symlink refuses (`IngestError.isLink`: `copyItem` would land the LINK itself and the #34 rail would refuse the whole send; finish-audit 2026-11-02, empirically verified), a Finder folder with an image extension refuses (`isFolder`); collisions ride `FixCardStore.uniqueFile` (`-2`/`-3`, the research-note helper — no bespoke loop). Drop-point mapping (the hard-won part, #115's family): the SwiftUI closure's `location` is UNUSABLE under this hosting; the pointer's screen position (`NSEvent.mouseLocation`) maps to an index via `firstRect(forCharacterRange:)` — its y is bottom-up screen coords like the mouse (no flip), non-contiguous layout makes OFF-SCREEN characters return garbage rects (whole-doc searches converge on the layout boundary), so `dropIndex(length:targetY:bandMinY:bandMaxY:rectY:)` — a `nonisolated static` PURE function (pinned by tests without a window) — SAMPLES the document (512 points), keeps only rects inside the viewport band (plain NSView geometry), brackets the drop between two in-band samples, binary-searches the bracket; a pointer above every in-band sample clamps to the first visible char, below all to the last in-band sample, no in-band evidence to 0 (never the old silent index-0-on-garbage), then slides the index to the next whitespace gap (never splices inside a word or an existing ref; dogfood-verified 2026-11-02, landing within one line). `alt` selected (offset +2, length 3) and scrolled to, with `CaretCentering.syncTypewriterInset` re-synced after the edit — without it the typewriter inset is stale and the editor freezes scrolling until the next keypress; one shouldChangeText step = one undo, didChangeText driving the coordinLine 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). `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, `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), `probeModel(for:)` picks the first surface on a provider else its flagship, and writes COALES per target — `persist`/`persistKey` capture-and-cancel the predecessor then (2026-10-28 audit fix) `await` its value past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write QUEUES — the last edit is always the last write to land (injectable `writeDebounce`, default 0.35 s; a superseded-in-window write never spawns, so partial key prefixes of a secret never reach `.env`; tests pass 0); `awaitPendingWrites()` is the tests' sync point; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write). `writeSurface` calls carry `zaiEndpoint` (the endpoint family when the surface is zai — written LAST because `config set model.provider` CLEARS a stale `model.base_url`, live-probed); a provider switch needs NO key re-fire — keys pre-land in all three `.env` files (2026-10-28 dogfood amendment). **#136 (Profiles S3) — the real write path + Test Connection:** `HermesSettingsWriter.swift` — the production `SettingsWriting` (the protocol + `NoopSettingsWriter` live here beside it, `: Sendable`, three methods): surface writes ride the engine's own CLI (`hermes -p <profile> config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset <key>` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **ALL THREE profiles' `.env`** (2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are igLine 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. `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.
+304 -110
View File
@@ -15,6 +15,15 @@
// folded parent shows "⋯ N" after its line. Folding never dirties the
// document (ADR-0013's posture, carried to prose).
//
// #142 (F1/F2): per-keystroke cost is paragraph-scoped. A single-line
// edit re-keys folds in place (`rekey` — delta shift, marker-line death,
// scope re-hide) with no parents rescan and no storage swap; the full
// `refreshFoldRendering` stays for structural edits and wholesale loads
// (and self-heals in via the hidden-styling probe when a fence-flip
// restyle wiped the folded attributes). Chrome renders as per-parent
// tiny layers in the overlay — never a document-sized bitmap — and an
// edit below every parent skips the rebuild outright.
//
// Key-delivery facts: arrows arrive as the function-key scalars
// \u{F700}/\u{F701} carrying .function/.numericPad device bits (strip
// before comparing modifiers); ⇧⇥ arrives as backtab \u{19}, sometimes
@@ -25,9 +34,14 @@
import AppKit
import SwiftUI
/// The chrome overlay: a click-through layer-host whose `contents` image the
/// text view renders offscreen (SwiftUI-hosted TextKit2 views never reliably
/// route through draw(_:) — layer contents sidestep the whole question).
/// The chrome overlay: a click-through layer-host that paints the list
/// chrome as one tiny CALayer per chevron/⋯N (SwiftUI-hosted TextKit2
/// views never reliably route through draw(_:) — layer contents sidestep
/// the whole question; #115 field finding). #142: per-parent layers in
/// document space replaced the old document-sized bitmap — a 700×50,000pt
/// doc used to rasterize ~35M pixels per keystroke to paint a handful of
/// chevrons; now it rasterizes ~15×18pt per glyph. The overlay rides the
/// scroll view with the text, so scrolling needs no refresh.
final class ProseChromeView: NSView {
weak var owner: ProseListTextView?
@@ -35,23 +49,17 @@ final class ProseChromeView: NSView {
nil
} // clicks reach the text view
/// Re-render the owner's chrome into a fresh image and install it as the
/// layer's contents. Deferred one main-queue tick: refresh points fire
/// inside textDidChange, after TextKit2 invalidated layout but before
/// re-layout — querying fragments synchronously finds none (#115).
func refresh() {
/// Rebuild the owner's chrome layers. Deferred one main-queue tick:
/// refresh points fire inside textDidChange, after TextKit2
/// invalidated layout but before re-layout — querying fragments
/// synchronously finds none (#115). `skipIfParentsAbove`: an edit
/// whose location sits at/after every parent line can't have moved
/// any chevron — keep the painted layers and do nothing.
func refresh(skipIfParentsAbove: NSRange? = nil) {
guard bounds.width > 0, bounds.height > 0 else { return }
DispatchQueue.main.async { [weak self] in
guard let self, let owner else { return }
// No parents anywhere and nothing painted → skip the raster.
// ponytail: the image is document-sized per refresh — rasterize the
// visible height instead if tall docs measurably chug.
if owner.proseParentCount == 0, layer?.contents == nil {
return
}
guard let image = owner.renderChromeImage(size: bounds.size) else { return }
wantsLayer = true
layer?.contents = image
owner.rebuildChromeLayers(skipIfParentsAbove: skipIfParentsAbove)
}
}
@@ -65,14 +73,37 @@ final class ProseChromeView: NSView {
final class ProseListTextView: NSTextView {
/// A fold: the marker line's buffer position + its text (the re-key
/// identity when an edit above shifts offsets).
struct Fold: Equatable {
/// identity when an edit above shifts offsets) + the hidden scope
/// (shift-maintained by the #142 cheap path; the full pass re-derives
/// it from `parents`).
nonisolated struct Fold: Equatable {
let key: Int
let lineText: String
let scope: NSRange
}
var folds: [Fold] = []
/// #142: the last accepted single-line edit (old-coords range + UTF-16
/// length delta), recorded in shouldChangeText while the storage still
/// holds the old text. Consumed by refreshFolds; nil (multi-line,
/// rejected, or none) → the full pass.
var pendingPlainEdit: (range: NSRange, delta: Int)?
override func shouldChangeText(in affectedRange: NSRange, replacementString: String?) -> Bool {
let accepted = super.shouldChangeText(in: affectedRange, replacementString: replacementString)
pendingPlainEdit = nil
if accepted, let replacement = replacementString {
let old = (string as NSString).substring(with: affectedRange)
// \.isNewline, never == "\n"/"\r": "\r\n" is ONE grapheme equal to
// neither — a CRLF-carrying edit must reach the full pass (#142 audit).
if !replacement.contains(where: \.isNewline), !old.contains(where: \.isNewline) {
pendingPlainEdit = (affectedRange, replacement.utf16.count - affectedRange.length)
}
}
return accepted
}
// MARK: Structural keys
override func keyDown(with event: NSEvent) {
@@ -127,7 +158,10 @@ final class ProseListTextView: NSTextView {
apply(edit)
}
private func performOutdent(_ item: ProseList.Item) {
/// ⇧Tab: remove up to 2 columns from every line of the block. The caret
/// rides its line's shift (parks at the new line start inside it).
/// Internal for the #142 audit pin (drives apply's structural routing).
func performOutdent(_ item: ProseList.Item) {
guard let edit = ProseList.outdent(item, caret: selectedRange().location, in: string) else { return }
apply(edit)
}
@@ -144,6 +178,10 @@ final class ProseListTextView: NSTextView {
/// folds are open, where the post-edit fold refresh already does it.
private func apply(_ edit: ProseList.Edit) {
guard shouldChangeText(in: edit.range, replacementString: edit.replacement) else { return }
// Structural edits reshape blocks — always the full pass. A childless
// unterminated block's outdent is a SINGLE-line replacement, and the
// cheap path would keep the dead fold's scope hidden (#142 audit).
pendingPlainEdit = nil
textStorage?.replaceCharacters(in: edit.range, with: edit.replacement)
didChangeText()
let length = (string as NSString).length
@@ -160,9 +198,15 @@ final class ProseListTextView: NSTextView {
/// textDidChange calls it LAST (after its paragraph reattribute and
/// session.edit, so hidden styling lands on top of the refreshed
/// presentation) and the wholesale content swaps (generation load, draft
/// echo — no textDidChange fires for those) call it directly. No folds →
/// chrome-only refresh; refreshFoldRendering ends in its own refresh.
/// echo — no textDidChange fires for those) call it directly. #142: a
/// recorded single-line edit takes the in-place re-key (no rescan, no
/// storage swap); no folds → chrome-only refresh, everything else → the
/// full pass.
func refreshFolds() {
defer { pendingPlainEdit = nil }
if let edit = pendingPlainEdit, !folds.isEmpty, rekeyAfterPlainEdit(edit) {
return
}
guard !folds.isEmpty else {
chrome.refresh()
return
@@ -174,7 +218,7 @@ final class ProseListTextView: NSTextView {
if let idx = folds.firstIndex(where: { $0.key == parent.markerLine.location }) {
folds.remove(at: idx)
} else {
folds.append(Fold(key: parent.markerLine.location, lineText: lineText(of: parent.markerLine)))
folds.append(Fold(key: parent.markerLine.location, lineText: lineText(of: parent.markerLine), scope: parent.foldScope))
}
refreshFoldRendering()
}
@@ -192,7 +236,7 @@ final class ProseListTextView: NSTextView {
parents
.filter { lineText(of: $0.markerLine) == fold.lineText }
.min { abs($0.markerLine.location - fold.key) < abs($1.markerLine.location - fold.key) }
.map { Fold(key: $0.markerLine.location, lineText: fold.lineText) }
.map { Fold(key: $0.markerLine.location, lineText: fold.lineText, scope: $0.foldScope) }
}.filter { seenKeys.insert($0.key).inserted } // two folds can't land on one parent
let sel = selectedRange()
textStorage?.setAttributedString(ProsePresenter.attribute(string))
@@ -396,102 +440,24 @@ final class ProseListTextView: NSTextView {
DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: hide)
}
// MARK: Chrome (chevron + ⋯ N)
/// Plain overlay sibling that owns the chrome drawing — TextKit2 views hosted
/// under SwiftUI never route through NSTextView.draw(_:), but a plain NSView
/// subview always draws. Click-through (hitTest nil); document-coordinate
/// space, so it rides the scroll view with the text.
private let chrome = ProseChromeView()
/// Install the overlay once the view reaches a window — the inherited
/// NSTextView inits (which build the full TextKit stack) stay untouched.
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
guard window != nil, chrome.superview == nil else { return }
chrome.owner = self
chrome.frame = bounds
chrome.autoresizingMask = [.width, .height]
addSubview(chrome, positioned: .above, relativeTo: nil)
chrome.refresh()
}
/// Parents count for the chrome's no-parents raster skip.
var proseParentCount: Int {
ProseList.parents(in: string).count
}
/// Render the whole chrome (chevrons + ⋯ N) into an image in the layer.
/// Top-left flipped coordinates — same space as lineRect's output.
func renderChromeImage(size: NSSize) -> NSImage? {
guard let window else { return nil }
let image = NSImage(size: size)
image.lockFocusFlipped(true)
drawListChrome()
image.unlockFocus()
return image
}
/// Parents whose marker line is not hidden inside another fold's scope —
/// hidden ones collapse to ~zero height and would paint phantom chevrons.
private var visibleParents: [ProseList.ParentHint] {
let parents = ProseList.parents(in: string)
let hiddenScopes = folds.compactMap { fold in
parents.first(where: { $0.markerLine.location == fold.key })?.foldScope
}
return parents.filter { parent in
!hiddenScopes.contains { NSLocationInRange(parent.markerLine.location, $0) }
}
}
func drawListChrome() {
for parent in visibleParents {
guard let startRect = lineRect(ofOffset: parent.markerLine.location) else { continue }
let folded = folds.contains { $0.key == parent.markerLine.location }
drawChrome(folded ? "▸" : "▾", folded: folded,
at: NSPoint(x: startRect.minX - 14, y: startRect.midY - chromeSize * 0.62))
if folded {
// ⋯ N after the parent's visible line text, not after the marker.
let text = lineText(of: parent.markerLine) as NSString
let lastChar = parent.markerLine.location + max(0, text.length - 1)
if let endRect = lineRect(ofOffset: lastChar) {
drawChrome("⋯ \(parent.hiddenLineCount)", folded: true,
at: NSPoint(x: endRect.maxX + 6, y: endRect.midY - chromeSize * 0.62))
}
}
}
}
override func mouseDown(with event: NSEvent) {
// Plain single-clicks only — shift-click extends selection, double/
// triple-click select word/paragraph; neither toggles a fold.
if !event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.capsLock).isEmpty || event.clickCount > 1 {
super.mouseDown(with: event)
return
}
let point = convert(event.locationInWindow, from: nil)
for parent in visibleParents {
guard let rect = lineRect(ofOffset: parent.markerLine.location) else { continue }
// Toggle zone: the gutter through the marker span ("- ", "1. ")
// of the marker line's first visual line.
if point.y >= rect.minY - 1, point.y <= rect.maxY + 1, point.x < rect.minX + 12 {
toggleFold(parent)
return
}
}
super.mouseDown(with: event)
}
/// mono-11 chrome, rust when folded, muted open (the outliner's
/// "⋯ N" vocabulary carried to prose).
private let chromeSize: CGFloat = 11
private func drawChrome(_ glyph: String, folded: Bool, at point: NSPoint) {
NSAttributedString(string: glyph, attributes: [
.font: NSFont.monospacedSystemFont(ofSize: chromeSize, weight: .regular),
.foregroundColor: folded ? NSColor(DesignTokens.accent) : NSColor(DesignTokens.muted),
]).draw(at: point)
}
/// #142 audit: glyph rasters cached by string — only ▸/▾ plus one per
/// distinct ⋯ N label exist, so a 50k-parent document shares a handful
/// of images instead of re-rasterizing every glyph per keystroke.
/// ponytail: layers are still built for every parent (scroll fires no
/// refresh, so viewport-culled parents would never gain a chevron);
/// cull to the visible band + refresh on scroll if pathological
/// parent counts still chug.
private var chromeGlyphImages: [String: NSImage] = [:]
// MARK: Geometry (TextKit2)
@@ -513,3 +479,231 @@ final class ProseListTextView: NSTextView {
return convert(windowRect, from: nil)
}
}
// MARK: - #142 in-place re-key (single-line edits)
extension ProseListTextView {
/// One `rekey` pass: survivors (shifted), dead scopes to un-hide, the
/// span needing re-hide, the caret park target.
nonisolated struct RekeyOutcome: Equatable {
let folds: [Fold]
let diedScopes: [NSRange]
let rehide: NSRange?
let park: Int?
}
/// The cheap path's view glue: apply the pure re-key, un-hide dead
/// scopes, re-hide the edited line, park a caret stranded inside a
/// hidden scope. Guarded by a probe — hidden styling must still be IN
/// the storage (a wholesale restyle, e.g. the fence-flip's full
/// attribute pass, wipes it); damaged → false and the caller falls
/// back to the full pass.
func rekeyAfterPlainEdit(_ edit: (range: NSRange, delta: Int)) -> Bool {
let result = Self.rekey(folds: folds, edit: edit.range, delta: edit.delta, in: string)
let buffer = string as NSString
for fold in result.folds {
guard fold.scope.length > 0, fold.scope.location < buffer.length,
let font = textStorage?.attribute(.font, at: fold.scope.location, effectiveRange: nil) as? NSFont,
font.pointSize < 1
else { return false }
}
folds = result.folds
if let storage = textStorage {
for scope in result.diedScopes {
// #142 audit: bounds-harden the sink — a shift can't push a
// scope out of the buffer on any reachable path, but
// reattribute's paragraph scan would trap if it ever did.
guard scope.location >= 0, scope.length > 0, NSMaxRange(scope) <= buffer.length else { continue }
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: scope)
}
if let rehide = result.rehide, rehide.length > 0 {
storage.setAttributes(ProseTypography.foldedAttributes, range: rehide)
}
}
if let park = result.park {
setSelectedRange(NSRange(location: min(park, buffer.length), length: 0))
}
// A fold death changes chevron state — only an all-survivor edit may
// skip the rebuild when every parent line sits above it.
chrome.refresh(skipIfParentsAbove: result.diedScopes.isEmpty ? edit.range : nil)
return true
}
/// #142: pure re-key math for a single-line edit. Per fold: an edit
/// entirely above shifts key + scope by delta; an edit touching the
/// marker line's content kills the fold (the full re-key's stored-
/// lineText match could no longer find it — same death, minus the
/// jump-to-duplicate-markers fuzz); an edit inside the scope grows or
/// shrinks it and flags the edited line for re-hiding (the
/// coordinator's paragraph reattribute just un-hid it) plus a caret
/// park at the marker end. Multi-line/structural edits stay on the
/// full pass. `lineText` stays fresh on survivors by construction —
/// only edits outside the marker line leave a fold alive.
nonisolated static func rekey(
folds: [Fold],
edit: NSRange,
delta: Int,
in text: String,
) -> RekeyOutcome {
let buffer = text as NSString
var survivors: [Fold] = []
var diedScopes: [NSRange] = []
var rehide: NSRange?
var park: Int?
let editEnd = NSMaxRange(edit)
for fold in folds {
// Old marker-content span [key, key+lineText): a zero-length edit
// "touches" it even at either boundary (an insertion at the head
// or at the caret-park position changes the line's text → death,
// full-pass parity).
let contentEnd = fold.key + fold.lineText.utf16.count
let touchedMarker = (edit.location < contentEnd && editEnd > fold.key)
|| (edit.length == 0 && fold.key <= edit.location && edit.location <= contentEnd)
// Scope shift, old-coords rules: translate when the edit is above,
// grow/shrink when inside (a single-line edit can't span across).
var scope = fold.scope
if edit.location < scope.location {
scope.location += delta
} else if edit.location < NSMaxRange(fold.scope) {
scope.length = max(0, scope.length + delta)
}
guard buffer.length > 0, !touchedMarker else {
diedScopes.append(scope) // shifted above for the un-hide pass
continue
}
if edit.location < fold.key {
survivors.append(Fold(key: fold.key + delta, lineText: fold.lineText, scope: scope))
continue
}
if edit.location < NSMaxRange(scope) {
// Edit inside the hidden scope: the edited line needs re-hiding
// and the caret (which sits at the edit) parks at the marker end.
let line = buffer.lineRange(for: NSRange(location: min(edit.location, buffer.length - 1), length: 1))
rehide = NSIntersectionRange(line, scope)
park = fold.key + fold.lineText.utf16.count
}
survivors.append(Fold(key: fold.key, lineText: fold.lineText, scope: scope))
}
return RekeyOutcome(folds: survivors, diedScopes: diedScopes, rehide: rehide, park: park)
}
}
// MARK: - Chrome (chevron + ⋯ N)
extension ProseListTextView {
/// Install the overlay once the view reaches a window — the inherited
/// NSTextView inits (which build the full TextKit stack) stay untouched.
/// #142: layer-hosting from the start; sublayer geometry is flipped
/// inside the rebuild to match lineRect's top-left y.
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
guard window != nil, chrome.superview == nil else { return }
chrome.owner = self
chrome.wantsLayer = true
chrome.frame = bounds
chrome.autoresizingMask = [.width, .height]
addSubview(chrome, positioned: .above, relativeTo: nil)
chrome.refresh()
}
/// #142: rebuild the chrome as one tiny layer per visible parent —
/// same glyph rasters as the bitmap era (drawChrome into a small
/// flipped image), positioned in the overlay's document space.
/// `skipIfParentsAbove`: an edit at/after every parent line moves no
/// chevron — keep the painted layers untouched (typing at the end of a
/// long document skips every lineRect query).
func rebuildChromeLayers(skipIfParentsAbove: NSRange? = nil) {
guard let overlay = chrome.layer else { return }
overlay.isGeometryFlipped = true // sublayer frames speak lineRect's top-left y
let parents = ProseList.parents(in: string)
if parentsUnmoved(parents, below: skipIfParentsAbove) {
return // chevrons can't have moved — keep the painted layers
}
let visible = visibleParents(parents)
var layers: [CALayer] = []
for parent in visible {
guard let startRect = lineRect(ofOffset: parent.markerLine.location) else { continue }
let folded = folds.contains { $0.key == parent.markerLine.location }
layers.append(chromeGlyphLayer(folded ? "▸" : "▾", folded: folded,
at: NSPoint(x: startRect.minX - 14, y: startRect.midY - chromeSize * 0.62)))
if folded {
// ⋯ N after the parent's visible line text, not after the marker.
let text = lineText(of: parent.markerLine) as NSString
let lastChar = parent.markerLine.location + max(0, text.length - 1)
if let endRect = lineRect(ofOffset: lastChar) {
layers.append(chromeGlyphLayer("⋯ \(parent.hiddenLineCount)", folded: true,
at: NSPoint(x: endRect.maxX + 6, y: endRect.midY - chromeSize * 0.62)))
}
}
}
overlay.sublayers = layers
}
/// True when the edit sits at/after every parent line and layers are
/// already painted — no chevron can have moved, so the rebuild may
/// skip every lineRect query.
private func parentsUnmoved(_ parents: [ProseList.ParentHint], below edit: NSRange?) -> Bool {
guard let edit, let painted = chrome.layer?.sublayers, !painted.isEmpty else { return false }
return parents.allSatisfy { NSMaxRange($0.markerLine) <= edit.location }
}
/// One small raster per glyph, contents-pinned to the layer — the
/// bitmap era's drawing calls at ~15×18pt instead of document size.
/// Box fixed wide; glyphs draw left-aligned from the box's top-left,
/// matching draw(at:)'s geometry in the flipped overlay.
private func chromeGlyphLayer(_ glyph: String, folded: Bool, at point: NSPoint) -> CALayer {
let size = NSSize(width: 64, height: chromeSize * 1.6)
if chromeGlyphImages[glyph] == nil {
let image = NSImage(size: size)
image.lockFocusFlipped(true)
drawChrome(glyph, folded: folded, at: .zero)
image.unlockFocus()
chromeGlyphImages[glyph] = image
}
let layer = CALayer()
layer.contents = chromeGlyphImages[glyph]
layer.contentsScale = window?.backingScaleFactor ?? 2
layer.frame = NSRect(origin: point, size: size)
return layer
}
override func mouseDown(with event: NSEvent) {
// Plain single-clicks only — shift-click extends selection, double/
// triple-click select word/paragraph; neither toggles a fold.
if !event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.capsLock).isEmpty || event.clickCount > 1 {
super.mouseDown(with: event)
return
}
let point = convert(event.locationInWindow, from: nil)
for parent in visibleParents(ProseList.parents(in: string)) {
guard let rect = lineRect(ofOffset: parent.markerLine.location) else { continue }
// Toggle zone: the gutter through the marker span ("- ", "1. ")
// of the marker line's first visual line.
if point.y >= rect.minY - 1, point.y <= rect.maxY + 1, point.x < rect.minX + 12 {
toggleFold(parent)
return
}
}
super.mouseDown(with: event)
}
/// Parents whose marker line is not hidden inside another fold's scope —
/// hidden ones collapse to ~zero height and would paint phantom chevrons.
/// Takes the caller's scan (#142): mouseDown pays one, the chrome rebuild
/// reuses its own.
private func visibleParents(_ parents: [ProseList.ParentHint]) -> [ProseList.ParentHint] {
let hiddenScopes = folds.compactMap { fold in
parents.first(where: { $0.markerLine.location == fold.key })?.foldScope
}
return parents.filter { parent in
!hiddenScopes.contains { NSLocationInRange(parent.markerLine.location, $0) }
}
}
private func drawChrome(_ glyph: String, folded: Bool, at point: NSPoint) {
NSAttributedString(string: glyph, attributes: [
.font: NSFont.monospacedSystemFont(ofSize: chromeSize, weight: .regular),
.foregroundColor: folded ? NSColor(DesignTokens.accent) : NSColor(DesignTokens.muted),
]).draw(at: point)
}
}
+1
View File
@@ -44,6 +44,7 @@ Owned by the root AGENTS.md contract.
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
- `ProseRekeyTests.swift` (#142, F1 — scenario header at file top; own file, split from ProseListTests at the file-length ceiling) — `ProseFoldRekeyTests` drives the keystroke pipeline through the REAL seams (`shouldChangeText` records → storage mutates → `refreshFolds`): a single-line edit above re-keys in place with hidden styling intact (no storage swap), typing on the marker line kills the fold AND restores its scope to view, a multi-line edit still takes the full pass, and a wholesale restyle (the fence-flip shape) self-heals into the full pass via the font probe; `ProseRekeyMathTests` pins the pure `rekey` math exactly (shift above, untouched below, death + translated diedScope, boundary-insertion deaths at both marker-content edges, scope-interior deletion → shrunk scope + rehide range + caret park). The painted-layer chrome skip itself is unpinnable headless (needs a window) — dogfood owns it.
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `cannedKeys` feeds `readProviderKey(provider:)` — #136 dogfood amendment: keys land in ALL THREE `.env` files, so hydration refills every key field with no per-provider profile list; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing). **#136 (Profiles S3):** the RecordingWriter double carries the new protocol shape (surface records include `zaiEndpoint`, key records the fan-out `profiles`, `cannedReads` feeds `readSurface`); the #136 model-side pins live in `SettingsModelWritePathTests.swift` (own file, file-length ceiling) sharing the now-internal `RecordingWriter` + `liveShapedRegistry` — a provider switch to a keyed zai threads the endpoint family into the surface write WITHOUT re-firing keys (they pre-landed in all three `.env` files at entry time), key writes carry the surfaces-on-provider list as the zai base_url write-through targets (chat first), rapid key edits coalesce into one write (superseded writes never spawn — partial key prefixes never reach `.env`; `writeDebounce: 0` keeps the suite deterministic), hydrate maps profile reads + infers the zai key type from the coding base_url (unread/unknown-provider surfaces stay seeded) and SEEDS a custom zai base_url instead of clobbering it, an edit made mid-hydrate never gets stomped, a second edit WAITS for the in-flight write (record order pinned `old → new`), and an unkeyed Test Connection authFails fast off the network; `probeModel` picks the first surface on a provider else its flagship. `HermesSettingsWriterTests.swift` (own file) — the real write path against the fake CLI (Real-Process pattern): write→`config get` round-trip, the exact config-set ORDER (provider → model → effort → base_url LAST, because setting model.provider clears base_url — live-probed), nil-effort unset + idempotent unset-when-absent, the `.env` writes over temp profile dirs (the key lands in ALL THREE profiles — a key with no surface on its provider still persists; foreign lines + comments preserved byte-for-byte, 0600 — hermes' own posture, the zai base_url config-set rides ONLY the listed profiles, an empty key leaves bytes alone but still writes the zai base_url, non-zai providers never config-set; readProviderKey round-trips, a line-broken key value is refused with nothing written — the env-injection guard), profile-named failures, missing-binary refusals + nil reads, and pure `upsertEnv` edges (in-place replace, append, trailing-newline, empty). `ProviderProbeTests.swift` (own file) — the factsheet decode matrix: zai 1113 → wrongKeyType, 401s per provider (Anthropic detail carries `request_id`), 429/foreign bodies → requestFailed; the three SSE dialects (zai chat-completions content + reasoning channels, Anthropic text_delta/stop_reason, OpenAI Responses output_text.delta/completed/incomplete/failed) — works carries reply + model count, `finish=length`/`max_tokens`/`incomplete` + empty → starved, response.failed → requestFailed, and the live 2026-10-28 z.ai **200-carried error envelope** (wrong content-type) decodes as the provider error; `ssePayloads` skipping event/DONE/blank lines; `decodeModelsCount` shapes; free `probeHTTPResponse`/`probeData` canned-response helpers live here (shared-helper convention). `ProviderProbeTransportTests.swift` (own file — the decode suite crossed its type-body ceiling, MCPToolsPromoteTests precedent) — the request builders (the 2026-10-28 Content-Type pin across all providers; Anthropic `x-api-key` + pinned version + required max_tokens; zai `thinking:enabled`+`reasoning_effort:low` wire at the 512 cap; **OpenAI in the ResponseLine truncated
- `PersonaLoadOrderTests.swift` (#1) — persona-content pins over the REAL bundled payload (`ProfileProvisioner.defaultPayloadRoot()`): both personas carry the `## Draft first, rules last` load-order doctrine (pass-persona 1.5 / session-persona 1.2, the PRD prompt-end rule), and the section is verbatim-shared between the pair (the four-shared-sections contract, ref/writing skills/AGENTS.md). Verified layout lives in `docs/research/prompt-layout-factsheet.md`.
+7 -1
View File
@@ -283,7 +283,13 @@ struct ProseFoldRenderingTests {
// an edit above shifts every line down by 3 ("x\n\n" prefix)
textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x\n\n")
textView.refreshFoldRendering()
#expect(textView.folds == [ProseListTextView.Fold(key: 3, lineText: "- parent")])
#expect(textView.folds == [
ProseListTextView.Fold(
key: parent.markerLine.location + 3,
lineText: "- parent",
scope: NSRange(location: parent.foldScope.location + 3, length: parent.foldScope.length),
),
])
let font = try #require(textView.textStorage?.attribute(.font, at: 13, effectiveRange: nil) as? NSFont)
#expect(font.pointSize < 1) // the shifted child stays hidden
}
+263
View File
@@ -0,0 +1,263 @@
//
// ProseRekeyTests.swift
// Museion
//
// #142 (F1): "a keystroke beside a fold re-keys it in place" — Given a
// folded list and the caret elsewhere, When a single-line edit lands,
// Then the fold survives with key + hidden scope shifted by the edit
// delta (no whole-document rescan or restyle), and a fold whose marker
// line was edited dies with its scope restored to view.
//
// Two suites: the view-level pipeline (shouldChangeText records →
// storage mutates → refreshFolds re-keys in place) and the pure
// `rekey` math.
//
import AppKit
@testable import Museion
import Testing
@MainActor
struct ProseFoldRekeyTests {
private func makeView(_ text: String) -> ProseListTextView {
let textView = ProseListTextView()
textView.isRichText = false
textView.textStorage?.setAttributedString(ProsePresenter.attribute(text))
return textView
}
/// The coordinator's keystroke pipeline — shouldChangeText records the
/// single-line edit, the storage mutates, refreshFolds re-keys in place.
private func type(
_ replacement: String, in range: NSRange,
of textView: ProseListTextView,
) {
textView.shouldChangeText(in: range, replacementString: replacement)
textView.textStorage?.replaceCharacters(in: range, with: replacement)
textView.refreshFolds()
}
@Test func `single-line edit above rekeys fold in place`() throws {
let text = "intro\n\n- parent\n - child\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
type("xx", in: NSRange(location: 0, length: 0), of: textView) // in the intro line
#expect(textView.folds == [
ProseListTextView.Fold(
key: parent.markerLine.location + 2,
lineText: "- parent",
scope: NSRange(location: parent.foldScope.location + 2, length: parent.foldScope.length),
),
])
// the shifted scope is still hidden — nothing swapped it away
let font = try #require(
textView.textStorage?.attribute(.font, at: parent.foldScope.location + 2, effectiveRange: nil) as? NSFont,
)
#expect(font.pointSize < 1)
}
@Test func `typing on the marker line kills the fold and restores its scope`() throws {
let text = "- parent\n - child\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
type("x", in: NSRange(location: 0, length: 0), of: textView) // at the line head
#expect(textView.folds.isEmpty)
let font = try #require(
textView.textStorage?.attribute(.font, at: parent.foldScope.location + 1, effectiveRange: nil) as? NSFont,
)
#expect(font.pointSize > 10) // the dead scope is visible again
}
@Test func `multi-line edit still takes the full pass`() throws {
let text = "- parent\n - child\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
type("x\n\n", in: NSRange(location: 0, length: 0), of: textView)
#expect(textView.folds == [
ProseListTextView.Fold(
key: parent.markerLine.location + 3,
lineText: "- parent",
scope: NSRange(location: parent.foldScope.location + 3, length: parent.foldScope.length),
),
])
}
@Test func `newline deletion routes to the full pass`() throws {
// Forward-delete at the parked caret removes the marker line's \n and
// merges the child into it — the OLD text contains a line break, so
// the edit must NOT take the cheap path. The cheap path's delta math
// would keep the fold alive on a no-longer-parent line; the full pass
// re-scans and kills it. Pins the isSingleLine(old) guard.
let text = "intro\n\n- parent\n - child\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
type("", in: NSRange(location: 15, length: 1), of: textView) // delete the \n
#expect(textView.string == "intro\n\n- parent - child\n")
#expect(textView.folds.isEmpty) // merged line has no children → fold dies
}
@Test func `crlf in the edited text routes to the full pass`() throws {
// "\r\n" is ONE Swift grapheme equal to neither "\n" nor "\r" — a
// literal line-break compare lets this deletion ride the cheap path,
// keeping a stale fold whose hidden scope eats half the merged line.
// The isNewline gate must route it to the full pass (the #142 audit's
// converged finding).
let text = "intro\r\n\r\n- parent\r\n - child\r\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
type("", in: NSRange(location: 17, length: 2), of: textView) // delete the CRLF after "- parent"
#expect(textView.string == "intro\r\n\r\n- parent - child\r\n")
#expect(textView.folds.isEmpty) // merged line has no children → fold dies
let font = try #require(
textView.textStorage?.attribute(.font, at: 17, effectiveRange: nil) as? NSFont,
)
#expect(font.pointSize > 10) // the merged line is fully visible
}
@Test func `structural outdent always takes the full pass`() throws {
// #142 audit: a childless UNTERMINATED block's outdent is a single-line
// replacement — apply() must clear pendingPlainEdit or the cheap path
// keeps the dead fold's scope hidden (the line appears lost).
let text = "- p\n - c1"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
let child = try #require(ProseList.item(at: 6, in: text))
textView.setSelectedRange(NSRange(location: 6, length: 0))
textView.performOutdent(child)
textView.refreshFolds() // the coordinator's tail — no delegate headless
#expect(textView.string == "- p\n- c1")
#expect(textView.folds.isEmpty) // "- p" lost its only child → fold dies
let font = try #require(
textView.textStorage?.attribute(.font, at: 4, effectiveRange: nil) as? NSFont,
)
#expect(font.pointSize > 10) // the outdented line is visible
}
@Test func `scope interior edit rehides the line and parks the caret`() throws {
// The cheap path's view glue, with the coordinator simulated: the
// paragraph reattribute un-hides the edited hidden line, then
// refreshFolds must re-hide it and park the caret at the marker end.
// The edit lands in the SECOND hidden line — the scope-head probe
// can't catch this damage (the first hidden line is untouched), so
// only the rehide glue covers it.
let text = "intro\n\n- parent\n - c1\n - c2\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
let edit = NSRange(location: 25, length: 0) // inside the second hidden line " - c2"
textView.setSelectedRange(edit)
textView.shouldChangeText(in: edit, replacementString: "x")
textView.textStorage?.replaceCharacters(in: edit, with: "x")
// the coordinator's paragraph reattribute (PostEditorView order)
let paragraph = (textView.string as NSString).paragraphRange(for: textView.selectedRange())
try ProsePresenter.reattribute(#require(textView.textStorage as? NSMutableAttributedString), paragraphRange: paragraph)
textView.refreshFolds()
#expect(textView.folds == [
ProseListTextView.Fold(key: 7, lineText: "- parent", scope: NSRange(location: 16, length: 15)),
])
let font = try #require(
textView.textStorage?.attribute(.font, at: 25, effectiveRange: nil) as? NSFont,
)
#expect(font.pointSize < 1) // re-hidden by the glue
#expect(textView.selectedRange().location == 15) // parked at the marker end
}
@Test func `wholesale restyle self-heals into the full pass`() throws {
// The fence-flip branch replaces the whole storage AFTER the edit was
// recorded — the cheap path's probe must notice the hidden styling is
// gone and fall back, or the fold would render open-but-invisible.
// (Edit lands in the intro line, above the fold, so the fold itself
// survives the re-key and only the probe can catch the damage.)
let text = "intro\n\n- parent\n - child\n"
let textView = makeView(text)
let parent = try #require(ProseList.parents(in: text).first)
textView.toggleFold(parent)
textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x")
textView.textStorage?.setAttributedString(ProsePresenter.attribute(textView.string))
textView.refreshFolds()
#expect(textView.folds.count == 1)
let font = try #require(
textView.textStorage?.attribute(.font, at: textView.folds[0].scope.location, effectiveRange: nil) as? NSFont,
)
#expect(font.pointSize < 1) // re-hidden by the full pass
}
}
@MainActor
struct ProseRekeyMathTests {
/// intro | blank | parent + two children | tail — one foldable parent.
private let text = "intro\n\n- parent\n - child one\n - child two\n- tail\n"
// layout: marker line (7,9), content end 15, scope (16,28), tail at 44.
private func makeFold() throws -> ProseListTextView.Fold {
let parent = try #require(ProseList.parents(in: text).first)
return ProseListTextView.Fold(key: parent.markerLine.location, lineText: "- parent", scope: parent.foldScope)
}
@Test func `edit above shifts key and scope`() throws {
let fold = try makeFold()
let result = ProseListTextView.rekey(
folds: [fold], edit: NSRange(location: 0, length: 0), delta: 2, in: "xx" + text,
)
#expect(result.folds == [ProseListTextView.Fold(key: 9, lineText: "- parent", scope: NSRange(location: 18, length: 28))])
#expect(result.diedScopes.isEmpty)
#expect(result.rehide == nil)
#expect(result.park == nil)
}
@Test func `edit below the scope leaves the fold untouched`() throws {
let fold = try makeFold()
let result = ProseListTextView.rekey(
folds: [fold], edit: NSRange(location: 44, length: 0), delta: 1, in: text + "z",
)
#expect(result.folds == [fold])
#expect(result.diedScopes.isEmpty)
#expect(result.rehide == nil)
}
@Test func `editing the marker line kills the fold`() throws {
let fold = try makeFold()
let result = ProseListTextView.rekey(
folds: [fold], edit: NSRange(location: 7, length: 8), delta: -3,
in: "intro\n\n- god\n - child one\n - child two\n- tail\n",
)
#expect(result.folds.isEmpty)
#expect(result.diedScopes == [NSRange(location: 13, length: 28)]) // translated for the un-hide
#expect(result.rehide == nil)
#expect(result.park == nil)
}
@Test func `insertions at either marker-content boundary kill too`() throws {
let fold = try makeFold()
// at the head (el == key) and at the park position (el == contentEnd)
for location in [7, 15] {
let result = ProseListTextView.rekey(
folds: [fold], edit: NSRange(location: location, length: 0), delta: 1,
in: "intro\n\n- parentx\n - child one\n - child two\n- tail\n",
)
#expect(result.folds.isEmpty, "insertion at \(location) should kill the fold")
#expect(result.diedScopes.count == 1)
}
}
@Test func `deletion inside the scope shrinks it and flags a re-hide`() throws {
let fold = try makeFold()
// delete "one" (26,3) inside the first hidden line
let result = ProseListTextView.rekey(
folds: [fold], edit: NSRange(location: 26, length: 3), delta: -3,
in: "intro\n\n- parent\n - child \n - child two\n- tail\n",
)
#expect(result.folds == [ProseListTextView.Fold(key: 7, lineText: "- parent", scope: NSRange(location: 16, length: 25))])
#expect(result.diedScopes.isEmpty)
// the edited line, clipped to the scope — the paragraph reattribute
// un-hid it and it must go back under
#expect(result.rehide == NSRange(location: 16, length: 11))
#expect(result.park == 15) // caret parks at the marker line's content end
}
}
@@ -0,0 +1,103 @@
# #142 — paragraph-scoped fold re-key + per-glyph chrome layers
> **Date:** 2026-11-03
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/Museion/issues/142
## Goal
With a fold open, every keystroke re-attributed and re-rasterized the whole
document (audit F1/F2 High): a full-buffer `ProseList.parents` scan, a
full-document `NSMutableAttributedString` rebuild through
`setAttributedString` (invalidating TextKit layout for the entire document,
per keystroke — O(n²) typing on folded documents), plus a chrome overlay
rastering an NSImage the size of the FULL document (~35M pixels on a
700×50,000pt doc) with 2–3 further full-buffer scans.
## What Was Done
- **F1 cheap re-key path** (`ProseListTextView.swift`): a `shouldChangeText`
override records the last accepted single-line edit (old-coords range +
UTF-16 delta, `pendingPlainEdit`); `refreshFolds` routes it through
`rekey` — a pure, `nonisolated static` function returning `RekeyOutcome`
(survivors shifted by delta, dead folds with translated scopes for
un-hiding, a re-hide range, a caret-park target). No parents rescan, no
storage swap. `Fold` gained the hidden `scope` (shift-maintained).
- **Guards around the cheap path**: a font probe at each survivor's scope
head falls back to the full pass when hidden styling is gone (the
fence-flip's wholesale restyle self-heals this way, pinned);
`apply()` nulls `pendingPlainEdit` — structural edits always take the full
pass (finish-audit: a childless unterminated block's ⇧⇥ is a single-line
replacement that would otherwise keep a dead fold's scope hidden);
the single-line gate is `\.isNewline`, never a literal `"\n"`/`"\r"`
compare (`"\r\n"` is ONE grapheme equal to neither — finish-audit,
converged ponytail+general finding, pinned).
- **F2 chrome rework**: chevrons/⋯N render as one tiny CALayer per visible
parent (contents = small flipped-NSImage raster, cached by glyph string in
`chromeGlyphImages`; overlay layer `isGeometryFlipped` so sublayer frames
speak lineRect's top-left y). Deleted the bitmap era:
`renderChromeImage`, `proseParentCount`, `drawListChrome`. An edit at/after
every parent line skips the rebuild outright (`parentsUnmoved`) — typing
at document end does zero `lineRect` queries. Scans per keystroke: 2–3 → 1
(the rebuild's own, same cost class as the staying `fenceDelimCount`).
- **Tests** (`MuseionTests/ProseRekeyTests.swift`, own file): view-level
pipeline pins (re-key in place, marker-line death + scope restore,
multi-line/CRLF/newline-deletion routing, wholesale-restyle self-heal,
structural outdent, scope-interior re-hide + park) and pure-math pins
(shift above/below, death + translated diedScope, boundary insertions,
scope-interior deletion). Existing `ProseFoldRenderingTests` Fold pins
widened with `scope`.
- **DOX**: `Museion/AGENTS.md` (#142 fold-maintenance + chrome bullets) and
`MuseionTests/AGENTS.md` (ProseRekeyTests entry).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Delta-shift re-key instead of rescanning parents per keystroke | A single-line edit can only shift offsets below it, kill a fold via its marker line, or touch one hidden scope — all O(1)-per-fold math. Full pass stays for multi-line/structural edits, wholesale loads, toggleFold. |
| Fold death on ANY marker-line-content edit (incl. insertion at the caret-park position) | Full-pass parity: the stored `lineText` no longer matches after such an edit, so the full re-key would kill it anyway — and it keeps `lineText` fresh on survivors by construction. |
| Font probe as the cheap path's safety net | Any wholesale restyle (fence-flip branch replaces the whole storage AFTER the edit was recorded) wipes hidden styling; probing one attribute per survivor is O(folds) and self-heals into the full pass without API coupling to the coordinator. |
| Per-glyph CALayers, not a viewport-sized bitmap | The overlay rides the scroll view (scroll fires no refresh — a viewport bitmap would need scroll tracking; culled layers would never regain chevrons). Same rendering calls as the bitmap era at ~15×18pt per glyph; CoreAnimation culls offscreen layers. |
| Glyph-raster cache keyed by glyph string | Only ▸/▾ plus one per distinct ⋯N exist — a 50k-parent document shares a handful of images instead of re-rasterizing per glyph per keystroke (finish-audit security finding). |
| `parentsUnmoved` rebuild skip | Chevron positions only move when lines shift; an edit at/after every parent line provably moves none. Kills the per-keystroke lineRect cost for the common write-at-end case. |
| Same-file `extension ProseListTextView` blocks (repo posture) | PostStore/MentorPaneView precedent; class body shrank 318→275 lines; a new file buys nothing at 2 extension consumers. |
| `performOutdent` widened internal | The apply()-fix pin must drive the real structural seam; repo has a "widened internal for tests" convention. |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| CRLF edits rode the cheap path | `"\r\n"` is ONE Swift `Character` equal to neither `"\n"` nor `"\r"`; a literal line-break compare passes it (two reviewers converged, both probe-verified) | `\.isNewline` keypath (stdlib; repo precedent MicropubMedia.swift:147); pinned by seeding a CRLF buffer and deleting the parent-line terminator |
| Structural ⇧⇥ made a line vanish | A childless UNTERMINATED block's outdent is a single-line replacement → cheap path → dead fold's scope stays hidden (security reviewer verified by executing the math) | `pendingPlainEdit = nil` in `apply()`; pinned via `performOutdent` |
| First rehide/park pin passed vacuously under its flip | The test edited the scope's FIRST hidden line — the scope-head probe's full-pass fallback re-hid it, so the pin guarded the wrong seam | Moved the edit to the SECOND hidden line (probe can't see it); re-flipped, pin failed, restored |
| `let replacement` shorthand didn't compile | The parameter is `replacementString`; bare `let replacement` binds a same-named optional that doesn't exist | `let replacement = replacementString` |
| Static funcs unreachable unqualified from instance methods | Swift resolves instance-context unqualified calls to instance members | `Self.isSingleLine(...)` |
| swiftlint vs swiftformat brace war | swiftformat puts the brace on its own line after wrapped condition lists; swiftlint's `opening_brace` flags it (one such warning pre-exists at HEAD) | Restructured to avoid wrapping (nested ifs, hoisted `parentsUnmoved` helper) |
| Multi-line `for … where …` failed to compile ("Expected '{'") | Wrapped where-clause + brace-on-next-line form rejected | Guard-inside-loop |
| 2 full-suite failures on first run (UI smoke + EditorSession debounce) | Load flakes under concurrent build/analyze (learning #30 class) — both green in isolation; a third (`SessionLifecycleTests`) flaked in the finish-audit run, also green in isolation | No code change; definitive idle-machine runs: 567/567, then 569/570+verified flake |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/ProseListTextView.swift` | Cheap re-key path + guards, per-glyph chrome layers with raster cache + skip, deletions of the bitmap machinery, extensions split |
| `MuseionTests/ProseRekeyTests.swift` | New: pipeline + pure-math suites (9 + 6 tests), scenario header |
| `MuseionTests/ProseListTests.swift` | Fold pins widened with `scope`; suites split out |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | #142 DOX |
| `AGENTS.md` | GitNexus index-stats line (analyze churn) |
## Open Items & Next Steps
- [ ] **Dogfood**: chevron alignment under `isGeometryFlipped` is the one
headless-unverifiable fact — if chevrons land mirrored vertically,
flip that boolean in `rebuildChromeLayers`.
- [ ] Deferred (finish-audit, ceiling comments in code): viewport culling
of chrome layers + scroll-triggered refresh (needs it to avoid
stranding culled parents); phantom off-screen chevron rects
(pre-existing `lineRect` class, same blocker).
- [ ] F4 (per-keystroke O(document) fence scans) remains — separate audit
finding, out of #142 scope.
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-11-03 | issue | [20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md](20261103-issue142-fold-rekey-paragraph-scoped-chrome-layers_log.md) | #142: single-line edits re-key folds in place; chrome becomes per-glyph layers — no more per-keystroke full-document restyle/raster |
| 2026-11-02 | issue | [20261102-issue141-image-drop-illustration-ingest_log.md](20261102-issue141-image-drop-illustration-ingest_log.md) | Image drop → assets/ ingest at drop point; window-destination routing, firstRect viewport-band solve, finish-audit fixes |
| 2026-11-01 | issue | [20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md](20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md) | #34 illustrations: media-endpoint upload, refs rewrite INLINE with URLs (dogfood killed the photo property); audit: injection/symlink/dedup — 546 tests |
| 2026-10-31 | issue | [20261031-issue33-m6-micropub-draft-publish-s6-1_log.md](20261031-issue33-m6-micropub-draft-publish-s6-1_log.md) | Two-step Micro.blog publish: Micropub draft→update, Keychain token, trustworthyURL gate, category inert |