feat(posts): import & external markdown — S1.1 (#22)
CI / ci (push) Canceled after 0s

External .md/.markdown opens and edits as-is in a single guest slot
(File > Open... Cmd+O, drag-onto-window): SessionTarget extends
EditorSession to write in place verbatim, no cursor sidecar, the #67
conflict alert reused for foreign files. Import... (Shift+Cmd+O)
copies multi-select files in as Posts behind ONE Origin ask
(writer default, immutable); external frontmatter keys ride verbatim
with pass_state/origin set; slug/collision machinery shared with
writeNew.

Audit fixes folded in: BOM stripped + CRLF normalized at the trust
boundary (a CRLF pair is one Swift grapheme — \n splits saw one
line); unreadable files refuse to open (loadFailed — a failed read
never becomes a write); dropped web links and severed symlinks
guarded; ~24 lines of reviewer-flagged dead weight removed.

7 new tests; full unit + UI suite green; swiftlint clean.

Map #22 stays open pending the live calibration pass (#88 posture).
This commit is contained in:
AlexKucera committed 2026-10-12 17:00:03 +02:00
1 parent 683d697367
commit 0f1c4ef4fe
14 files changed
+691 -49

No files matched your search

+2 -1
View File
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (2383 symbols, 6210 relationships, 145 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (2485 symbols, 6551 relationships, 161 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).
@@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-10-12 | [20261012-issue22-import-external_log.md](docs/devlog/20261012-issue22-import-external_log.md) |
| 2026-10-09 | [20261009-issue88-calibration-gate_log.md](docs/devlog/20261009-issue88-calibration-gate_log.md) |
| 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) |
| 2026-10-08 | [20261008-issue84-view-menu-doubled_log.md](docs/devlog/20261008-issue84-view-menu-doubled_log.md) |
+6 -6
View File
@@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Local Contracts
- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state).
- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too.
- `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project).
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 26.5; bundle id `com.babylondreams.Museion`.
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
@@ -21,12 +21,12 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
## Workspace shell (M1, #17 + #18 / S1.1)
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#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.
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border.
- `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`).
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens.
- `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.
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin) + `Post.scan(home:) -> [Post]`: reads `posts/<id>/post.md`, skips dirs without post.md (lazy folders), loose files, hidden dirs (dot-prefix), and symlinked dirs; 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).
- `PostStore.swift` — #18 write side (nonisolated): the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug` collision suffixes `-2`/`-3`…, `writeNew` (lazy folder + #59 stamp `pass_state: First Draft` / `origin: writer` — the only values #18 writes), `overwrite` (preserves existing pass_state/origin, normalizes bare posts on save), `rename` = retitle + move (rewrites/inserts `# Title` as first non-empty body line, moves the folder, file stays `post.md`; a title slugging to the current id only retitles), `trash` (`FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save); 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 `posts/`, 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); `bind(home:)` from `.task(id: home)` creates `posts/` 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.
- 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 post: `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` writes `PostStore.overwrite` + the cursor sidecar, 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; `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads the sidecar; `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); `folderURL` exposes `posts/<id>/` 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) + `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). #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 `posts/<id>/.museion-state.json` — 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).
- `PostStore.swift` — #18 write side (nonisolated): the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug` collision suffixes `-2`/`-3`…, `writeNew` (lazy folder + #59 stamp `pass_state: First Draft` / `origin: writer` — the only values #18 writes), `overwrite` (preserves existing pass_state/origin, normalizes bare posts on save), `rename` = retitle + move (rewrites/inserts `# Title` as first non-empty body line, moves the folder, file stays `post.md`; a title slugging to the current id only retitles), `trash` (`FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:home:)` (copy never move; 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 `pass_state`/`origin` set-overwritten via `mergedFrontmatter`; absent keys inserted before the closing `---`; empty block → fresh #59 shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save); 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 `posts/`, 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); `bind(home:)` from `.task(id: home)` creates `posts/` 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. **#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`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip.
- 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/folderURL computed per target; 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 posts/ 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); `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 `posts/<id>/.museion-state.json` — 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).
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
- 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.
+100 -24
View File
@@ -19,20 +19,50 @@ enum SaveState: Equatable {
case failed
}
/// One open post's editing session (@MainActor @Observable, the PostsModel
/// pattern). Born from a disk read; writes go out after the #64 debounce.
/// What a session writes to (#92): a Post in the Home, or an external
/// markdown file edited as-is — the file is the document (ADR-0004).
enum SessionTarget {
case post(id: String, home: URL)
case externalFile(URL)
}
/// One open document's editing session (@MainActor @Observable, the
/// PostsModel pattern). Born from a disk read; writes go out after the #64
/// debounce. External targets save in place and never write a cursor sidecar
/// (#93) — nothing of ours lands next to a foreign file.
@MainActor
@Observable
final class EditorSession {
let postID: String
private let home: URL
let target: SessionTarget
private let debounce: Duration
/// The post's folder (`<home>/posts/<id>`) — reading resolves relative
/// image URLs against it (#71).
/// The Post id for post targets; nil for external.
var postID: String? {
if case let .post(id, _) = target {
return id
}
return nil
}
/// The external file's URL; nil for posts.
var fileURL: URL? {
if case let .externalFile(url) = target {
return url
}
return nil
}
/// The document's folder — `posts/<id>/` for posts (image resolution
/// #71); the external file's containing folder, so relative images
/// resolve beside the file.
var folderURL: URL {
home.appendingPathComponent("posts", isDirectory: true)
.appendingPathComponent(postID, isDirectory: true)
switch target {
case let .post(id, home):
home.appendingPathComponent("posts", isDirectory: true)
.appendingPathComponent(id, isDirectory: true)
case let .externalFile(url):
url.deletingLastPathComponent()
}
}
/// Current body text (live, per keystroke).
@@ -59,18 +89,60 @@ final class EditorSession {
private var lastFlushedText: String
private var debounceTask: Task<Void, Never>?
/// True when the initial read failed (foreign file unreadable — wrong
/// encoding, permissions, vanished). A session that never loaded must
/// never write: the empty editor's first keystroke would otherwise
/// destroy the file we failed to read.
private(set) var loadFailed = false
/// Failure text for the owner's lastError strip; nil clears it (#65).
var onError: (@MainActor @Sendable (String?) -> Void)?
init(postID: String, home: URL, debounce: Duration = .seconds(1)) {
self.postID = postID
self.home = home
init(target: SessionTarget, debounce: Duration = .seconds(1)) {
self.target = target
self.debounce = debounce
let body = PostStore.readBody(id: postID, home: home) ?? ""
let read = Self.readDocument(target)
loadFailed = read == nil
let body = read ?? ""
text = body
loadText = body
lastFlushedText = body
restoreCursor = PostStore.readCursor(id: postID, home: home)
if case let .post(id, home) = target {
restoreCursor = PostStore.readCursor(id: id, home: home)
}
}
/// Convenience: post-target session (#19 call sites).
convenience init(postID: String, home: URL, debounce: Duration = .seconds(1)) {
self.init(target: .post(id: postID, home: home), debounce: debounce)
}
/// Whole-document read per target: posts edit body-only (frontmatter
/// stamped back on write); external files round-trip the text — the file
/// is the document (#91/#93). BOM stripped and CRLF normalized to LF on
/// read (same reason as importFile: the corpus machinery splits on \n;
/// in Swift a CRLF pair is one grapheme and every split sees one line).
private static func readDocument(_ target: SessionTarget) -> String? {
switch target {
case let .post(id, home):
return PostStore.readBody(id: id, home: home)
case let .externalFile(url):
guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
if text.hasPrefix("\u{FEFF}") { text.removeFirst() }
return text.replacingOccurrences(of: "\r\n", with: "\n")
}
}
/// Target-aware write: posts → `PostStore.overwrite` (+ sidecar);
/// external → the whole text, in place, no sidecar (#93).
private func writeDocument() throws {
switch target {
case let .post(id, home):
try PostStore.overwrite(id: id, body: text, home: home)
PostStore.writeCursor(cursor, id: id, home: home)
case let .externalFile(url):
try text.write(to: url, atomically: true, encoding: .utf8)
}
}
// MARK: Edit + debounce (#64)
@@ -98,19 +170,18 @@ final class EditorSession {
// MARK: Flush (#64/#65/#66)
/// Write body + sidecar now. ⌘S, debounce fire, selection change, window
/// close, and app quit all land here. No-op when clean.
/// Write body (+ post sidecar) now. ⌘S, debounce fire, selection change,
/// window close, and app quit all land here. No-op when clean or when
/// the document never loaded (a failed read must not become a write
/// that destroys the file).
func flush() {
debounceTask?.cancel()
guard text != lastFlushedText else { return }
guard !loadFailed, text != lastFlushedText else { return }
do {
try PostStore.overwrite(id: postID, body: text, home: home)
try writeDocument()
lastFlushedText = text
saveState = .saved
onError?(nil)
// Sidecar best-effort: the content write is what matters; a failed
// cursor write must never read as a failed save.
PostStore.writeCursor(cursor, id: postID, home: home)
} catch {
saveState = .failed
onError?(error.localizedDescription)
@@ -151,16 +222,21 @@ final class EditorSession {
}
/// #67 Yes: reload from disk; cursor restored from the sidecar where
/// still valid (the surface clamps).
/// still valid (the surface clamps). External targets reset the cursor
/// (#93 — no sidecar next to foreign files).
func reloadFromDisk() {
guard conflictAlert else { return }
conflictAlert = false
guard let disk = PostStore.readBody(id: postID, home: home) else { return }
guard let disk = Self.readDocument(target) else { return }
text = disk
loadText = disk
loadGeneration += 1
lastFlushedText = disk
restoreCursor = PostStore.readCursor(id: postID, home: home)
if case let .post(id, home) = target {
restoreCursor = PostStore.readCursor(id: id, home: home)
} else {
restoreCursor = nil
}
saveState = .saved
// #83: reload resolves a failure too — shown text now equals disk.
onError?(nil)
@@ -174,7 +250,7 @@ final class EditorSession {
func keepLocal() {
guard conflictAlert else { return }
conflictAlert = false
if let disk = PostStore.readBody(id: postID, home: home) {
if let disk = Self.readDocument(target) {
lastFlushedText = disk
}
syncSaveState() // #83: local ≠ disk now — shows as pending changes
+53
View File
@@ -5,6 +5,7 @@
// Created by Alexander Kucera on 26.08.26.
//
import AppKit
import SwiftUI
/// App-scoped gate state — raised once per app-launch, first window only (ticket #41).
@@ -83,6 +84,13 @@ struct MuseionApp: App {
CommandGroup(replacing: .appInfo) {
OpenAboutButton()
}
// #91/#94: File ▸ Open… (⌘O) and Import… (⇧⌘O) join the system
// File menu after New — never CommandMenu("File"), which doubles
// it (#84 trap).
CommandGroup(after: .newItem) {
OpenExternalButton(gate: gate)
ImportFilesButton(gate: gate)
}
// #77: spellcheck posture — Edit ▸ Check Spelling While Typing,
// default off (Neo posture: on when asked). Explicit rather than
// relying on the stock submenu's presence in a WindowGroup app.
@@ -143,13 +151,58 @@ private struct FocusModeToggle: View {
var body: some View {
// Entry guard: nothing open = nothing to focus on. Exit stays armed
// even then (trashing the open post while focused must not trap).
// #92: the external guest counts as open too.
let canFocus = gate.isFocused || gate.posts.session != nil || gate.posts.draft != nil
|| gate.posts.externalSession != nil
Button("Toggle Focus Mode") { gate.isFocused.toggle() }
.keyboardShortcut("f", modifiers: [.command, .option])
.disabled(!canFocus)
}
}
/// #91: File ▸ Open… (⌘O) — NSOpenPanel (the Settings Home picker pattern),
/// .md/.markdown only (#96). Opens into the single external guest slot.
private struct OpenExternalButton: View {
let gate: AppGateState
var body: some View {
Button("Open…") {
if let url = pickMarkdown(multiple: false, message: "Opens the file as-is — Museion never converts or moves it.").first {
gate.posts.openExternal(url)
}
}
.keyboardShortcut("o", modifiers: .command)
}
}
/// #94: File ▸ Import… (⇧⌘O) — multi-select, .md/.markdown only; ONE Origin
/// ask per batch, then copy in as Posts.
private struct ImportFilesButton: View {
let gate: AppGateState
var body: some View {
Button("Import…") {
let urls = pickMarkdown(multiple: true, message: "Imports copies as Posts — the original files are untouched.")
if !urls.isEmpty {
gate.posts.stageImport(urls)
}
}
.keyboardShortcut("o", modifiers: [.command, .shift])
}
}
/// The shared NSOpenPanel for both File-menu entries (#91/#94): local
/// .md/.markdown files only.
private func pickMarkdown(multiple: Bool, message: String) -> [URL] {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = multiple
panel.allowedContentTypes = PostStore.openableTypes
panel.message = message
return panel.runModal() == .OK ? panel.urls : []
}
/// #50: reveals `~/Library/Application Support/Museion/Backups` in Finder —
/// restore is manual Finder copy-back in v1 (help doc describes it).
private struct OpenBackupFolderButton: View {
+11 -4
View File
@@ -126,7 +126,8 @@ struct PostEditorView: View {
Button("Reload") { session?.reloadFromDisk() }
Button("Keep Local") { session?.keepLocal() }
} message: {
Text("post.md changed outside Museion. Reload discards your unsaved edits; Keep Local overwrites the file on the next save.")
Text("\(session?.fileURL?.lastPathComponent ?? "post.md") changed outside Museion. "
+ "Reload discards your unsaved edits; Keep Local overwrites the file on the next save.")
}
}
@@ -241,10 +242,16 @@ struct PostEditorView: View {
private var crumb: String {
if let session {
"posts / \(session.postID) / post.md"
} else {
"unsaved draft — no folder until first save"
if let fileURL = session.fileURL {
// #92: the external guest — the crumb shows the file name in
// the same muted mono style.
return fileURL.lastPathComponent
}
if let id = session.postID {
return "posts / \(id) / post.md"
}
}
return "unsaved draft — no folder until first save"
}
}
+2
View File
@@ -104,6 +104,8 @@ nonisolated struct Post: Identifiable, Equatable {
nonisolated extension Substring {
func trimmed() -> String {
// whitespacesAndNewlines, not .whitespaces: a CRLF file's lines carry
// a trailing \r that would defeat every "---" boundary check.
trimmingCharacters(in: .whitespacesAndNewlines)
}
}
+97 -5
View File
@@ -8,11 +8,26 @@
//
import Foundation
import UniformTypeIdentifiers
/// Write-side Post lifecycle (#18 map decisions #59/#60). One canonical write
/// path: every file that leaves here carries the flat frontmatter block the
/// #17 reader already parses.
/// #17 reader already parses. #22: import copies external markdown in (#94/#95).
nonisolated enum PostStore {
/// #96: .md/.markdown only — every entry point (Open panel, Import panel,
/// drag-drop filter) shares this list.
static let openableTypes: [UTType] = markdownExtensions.compactMap { UTType(filenameExtension: $0) }
/// #91: drag-drop filter — local file URLs only (a dragged web link is
/// not a document; `String(contentsOf:)` would fetch it), extension
/// checked case-insensitively (UTType conformance on the pasteboard is
/// unreliable).
static func isMarkdown(_ url: URL) -> Bool {
url.isFileURL && markdownExtensions.contains(url.pathExtension.lowercased())
}
private static let markdownExtensions = ["md", "markdown"]
/// The shared slug function (#60): lowercase, diacritic-fold, strip
/// punctuation, whitespace runs → single hyphens, keep CJK, cap 80.
/// A slugless title (blank, punctuation-only) is `untitled` (CONTEXT.md).
@@ -64,9 +79,87 @@ nonisolated enum PostStore {
/// #59 block stamped. Pass State First Draft, origin writer — the only
/// values #18 writes; the folder appears here, never on New Post.
static func writeNew(body: String, home: URL) throws -> Post {
try materialize(
text: stamped(body: body, passState: .firstDraft, origin: .writer),
title: Post.title(of: body),
origin: .writer,
home: home,
)
}
/// #22/#94/#95: import one external markdown file as a Post — copy, never
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
/// verbatim with `pass_state: First Draft` and `origin: <chosen>` set /
/// overwritten (our two keys win); id = Title slug at import; collisions
/// `-2`/`-3`… (#60 machinery); a fresh copy, no mtime preservation (#96).
static func importFile(at url: URL, origin: Post.Origin, home: URL) throws -> Post {
var raw = try String(contentsOf: url, encoding: .utf8)
// ponytail: normalize line endings + strip BOM at the import boundary —
// in Swift a CRLF pair is ONE grapheme, so every "\n" split in the
// corpus machinery sees a CRLF file as a single line (mangled id and
// title); true CRLF preservation would need grapheme-aware joins
// everywhere. Lone-CR (pre-OSX) files still degrade to `untitled` —
// ceiling named, add a "\r" pass if one ever shows up.
if raw.hasPrefix("\u{FEFF}") { raw.removeFirst() }
raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
let (block, body) = splitFrontmatter(raw)
let text = mergedFrontmatter(keeping: block, origin: origin) + body
return try materialize(
text: text,
title: Post.title(of: body),
origin: origin,
home: home,
)
}
/// #95: external frontmatter keys ride along verbatim; `pass_state` and
/// `origin` are set/overwritten in place — our two keys win, everything
/// else untouched. Absent keys are inserted before the closing `---`.
/// Returns the block INCLUDING its trailing newline; "" for a bare file
/// (the caller then writes the #59 stamp shape via a fresh block).
private static func mergedFrontmatter(keeping block: String, origin: Post.Origin) -> String {
guard !block.isEmpty else {
return "---\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
}
var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
// Drop the empty tail the block's final newline produced — re-added below.
if let last = lines.last, last.isEmpty {
lines.removeLast()
}
var ours: Set<String> = []
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if key == "pass_state" {
lines[index] = "pass_state: \(Post.PassState.firstDraft.rawValue)"
ours.insert("pass_state")
} else if key == "origin" {
lines[index] = "origin: \(origin.rawValue)"
ours.insert("origin")
}
}
var insertions: [String] = []
if !ours.contains("pass_state") {
insertions.append("pass_state: \(Post.PassState.firstDraft.rawValue)")
}
if !ours.contains("origin") {
insertions.append("origin: \(origin.rawValue)")
}
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
lines.insert(contentsOf: insertions, at: close)
}
return lines.joined(separator: "\n") + "\n"
}
/// #62/#95: lazily materialize `posts/<slug>/post.md` with the given
/// (already stamped/merged) text. Shared by `writeNew` and `importFile` —
/// one lazy-folder path, TOCTOU-guarded, never clobbering.
/// Returns the created Post (id, title, First Draft, origin).
private static func materialize(text: String, title: String, origin: Post.Origin, home: URL) throws -> Post {
let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
try FileManager.default.createDirectory(at: postsRoot, withIntermediateDirectories: true)
let title = Post.title(of: body)
let id = availableSlug(for: title, in: postsRoot)
let dir = postsRoot.appendingPathComponent(id, isDirectory: true)
let fileURL = dir.appendingPathComponent("post.md")
@@ -77,8 +170,7 @@ nonisolated enum PostStore {
}
do {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try stamped(body: body, passState: .firstDraft, origin: .writer)
.write(to: fileURL, atomically: true, encoding: .utf8)
try text.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
// Don't strand an empty slug folder on partial failure (it would
// occupy the slug and push the retry to -2).
@@ -87,7 +179,7 @@ nonisolated enum PostStore {
}
throw error
}
return Post(id: id, title: title, passState: .firstDraft, origin: .writer)
return Post(id: id, title: title, passState: .firstDraft, origin: origin)
}
/// Save an existing Post: body-only text in, file normalized out. The
+114 -8
View File
@@ -82,12 +82,24 @@ final class PostsModel {
/// nothing is selected.
private(set) var session: EditorSession?
/// #92: the external buffer's guest slot — one at a time, transient per
/// launch. Takes the editor column; opening a Post or draft dismisses it
/// (flush first).
private(set) var externalSession: EditorSession?
/// #94: a multi-file import waiting on its ONE Origin ask; the sheet
/// answers, then the batch runs.
private(set) var pendingImportURLs: [URL]?
/// Last failed-op message surfaced in the editor (nil = clean).
private(set) var lastError: String?
/// Home the watcher is bound to; also the rescan target.
private var watchedHome: URL?
private var watcher = PostsWatcher()
/// #93: per-file watcher on the open external file — the #67 conflict
/// check reused verbatim for foreign files.
private var externalWatcher = PostsWatcher()
/// Bind a Home: ensure `posts/` exists (FSEvents on a missing path is
/// unreliable; the AC's lazy rule is about post folders, not this root),
@@ -130,7 +142,7 @@ final class PostsModel {
selectedPostID = nil // the post vanished (deleted in Finder or here)
if let open = session, open.postID == id {
open.teardown(flushFirst: false) // post is gone; cancel the debounce
self.session = nil
session = nil
}
}
// #67: watcher echo check on the open post — equality against the
@@ -148,20 +160,33 @@ final class PostsModel {
/// Tear the watcher down on the main actor (its scheduling thread) —
/// deinit of a @MainActor-held object may run elsewhere. #64: app quit
/// flushes the open session first (sidecar rides along).
/// flushes the open session first (sidecar rides along). #96: quit also
/// flushes the external buffer — same posture, same moment.
func shutdown() {
session?.flush()
externalSession?.flush()
watcher.stop()
externalWatcher.stop()
}
/// New Post (#62): fresh in-memory draft, no folder, editor takes it.
func newPost() {
dismissExternal() // #92: opening a draft dismisses the guest
session?.teardown(flushFirst: true) // #64: selection change flushes
session = nil
draft = PostDraft()
selectedPostID = nil
}
/// #92: dismiss the external guest slot, flushing pending edits (the
/// guest is always leaving for somewhere — same posture as post
/// selection change).
private func dismissExternal() {
externalSession?.teardown(flushFirst: true)
externalSession = nil
externalWatcher.stop()
}
/// First save of the draft (#62): lazy folder, slug, #59 stamp all fire
/// here. The saved post opens straight into an editing session — the
/// writer keeps typing where they were. Rescans immediately (the watcher
@@ -184,8 +209,10 @@ final class PostsModel {
/// Select a Post; selecting anything abandons an unsaved draft (the
/// draft otherwise hijacks the editor — its only exits are save or
/// selecting away). #19: opening a post ends the previous session
/// (flush-on-selection-change, #64) and starts a new one.
/// (flush-on-selection-change, #64) and starts a new one. #92: it also
/// dismisses the external guest (flush first).
func select(_ id: String, home: URL) {
dismissExternal()
if let session, session.postID != id {
session.teardown(flushFirst: true)
}
@@ -195,10 +222,6 @@ final class PostsModel {
wireSession()
}
private func wireSession() {
session?.onError = { [weak self] message in self?.lastError = message }
}
/// Draft typing from the editor (private(set) barrier).
func updateDraft(_ text: String) {
draft?.text = text
@@ -238,7 +261,7 @@ final class PostsModel {
selectedPostID = nil
if let open = session, open.postID == post.id {
open.teardown(flushFirst: false)
self.session = nil
session = nil
}
}
lastError = nil
@@ -247,4 +270,87 @@ final class PostsModel {
lastError = error.localizedDescription
}
}
// MARK: External buffer (#91–#93) + Import (#94/#95)
/// #91/#92: open an external markdown file in the guest slot — one at a
/// time; opening anything else (file, Post, draft) flushed and replaced
/// it first. A Post session/draft stands down while the guest is up
/// (the editor column is the guest's; the selection stays for return).
/// Local files only (a dragged web link is not a document) and symlinks
/// resolve to their real target so the in-place write never severs the
/// link (rename over a symlink replaces it).
func openExternal(_ url: URL) {
guard url.isFileURL else { return }
let target = url.resolvingSymlinksInPath()
dismissExternal()
session?.teardown(flushFirst: true) // #92: the guest takes the column
session = nil
draft = nil
externalSession = EditorSession(target: .externalFile(target))
if externalSession?.loadFailed == true {
lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed."
externalSession = nil
return
}
wireSession()
startExternalWatch(url: target)
}
/// #93: watch the open external file — its rescan is the #67 disk-change
/// check, reused verbatim for foreign files. PostsWatcher fires on the
/// main actor already; no re-hop needed.
private func startExternalWatch(url: URL) {
externalWatcher.onEvent = { [weak self] in
guard let self, let session = self.externalSession else { return }
guard let disk = try? String(contentsOf: url, encoding: .utf8) else { return }
session.diskDidChange(diskText: disk)
}
externalWatcher.start(url: url.deletingLastPathComponent())
}
/// #94: stage a multi-file import — the ONE Origin ask presents; the
/// sheet's answer runs the batch.
func stageImport(_ urls: [URL]) {
guard !urls.isEmpty else { return }
pendingImportURLs = urls
}
/// #94: dismiss the ask without an answer — the batch drops.
func cancelImport() {
pendingImportURLs = nil
}
/// #94/#95: run the batch after the Origin answer — copy each file in as
/// a Post; a per-file failure continues the batch into lastError (stated
/// default, reversible; never an alert, never an abort). The last
/// imported post opens; a failure anywhere keeps its message up even
/// when other files landed.
func importFiles(origin: Post.Origin, home: URL) {
guard let urls = pendingImportURLs else { return }
pendingImportURLs = nil
var last: Post?
var failures = 0
for url in urls {
do {
last = try PostStore.importFile(at: url, origin: origin, home: home)
} catch {
failures += 1
lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)"
}
}
if let last {
select(last.id, home: home)
}
if failures == 0 {
lastError = nil
}
Task { await rescan() }
}
private func wireSession() {
let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message }
session?.onError = route
externalSession?.onError = route
}
}
+6 -1
View File
@@ -87,9 +87,14 @@ struct PostsPaneView: View {
},
)
.id("draft")
} else if let external = model.externalSession {
// #92: the guest slot — an external file in the editor column;
// one at a time, transient per launch.
PostEditorView(session: external, draftText: nil)
.id(external.fileURL?.absoluteString ?? "external")
} else if let session = model.session, session.postID == model.selectedPostID {
PostEditorView(session: session, draftText: nil)
.id(session.postID)
.id(session.postID ?? "post")
} else {
VStack(spacing: 10) {
Image(systemName: "square.and.pencil")
+80
View File
@@ -38,6 +38,14 @@ struct WorkspaceView: View {
}
}
}
// #91: drag a markdown file onto the window — same guest slot as
// File ▸ Open… Non-markdown drops are refused.
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first(where: PostStore.isMarkdown) else { return false }
gate.posts.openExternal(url)
selection = .posts
return true
}
// #21: left-edge hover slides rail+library back in as an overlay.
// Library only while the window width allows it (#17 verdict stands:
// a collapsed pane is not summoned by focus).
@@ -57,9 +65,40 @@ struct WorkspaceView: View {
}
}
.background(DesignTokens.background)
// #94: the ONE Origin ask per import batch. Dismissal without an
// answer (Esc/Cancel) drops the batch.
.sheet(isPresented: originAskBinding) {
OriginAskSheet(count: gate.posts.pendingImportURLs?.count ?? 0) { origin in
gate.posts.importFiles(origin: origin, home: gate.museionHome)
}
}
}
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320)
// #92/#94: the editor column lives in Posts — a guest buffer or an
// import's opened post surfaces there, whatever pane was showing.
.onChange(of: gate.posts.externalSession != nil) { _, isUp in
if isUp {
selection = .posts
}
}
.onChange(of: gate.posts.selectedPostID) { _, _ in
if gate.posts.session != nil {
selection = .posts
}
}
}
/// #94: the ask presents while a batch is staged.
private var originAskBinding: Binding<Bool> {
Binding(
get: { gate.posts.pendingImportURLs != nil },
set: {
if !$0 {
gate.posts.cancelImport()
}
},
)
}
@ViewBuilder
@@ -116,6 +155,47 @@ struct WorkspaceView: View {
}
}
/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the
/// immutability line (CONTEXT.md: Origin). Answering runs the batch.
private struct OriginAskSheet: View {
let count: Int
let answer: (Post.Origin) -> Void
@Environment(\.dismiss) private var dismiss
@State private var origin: Post.Origin = .writer
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Who wrote this?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text(count == 1
? "Importing 1 file as a Post — the original is untouched."
: "Importing \(count) files as Posts — the originals are untouched.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Picker("Origin", selection: $origin) {
Text("I wrote it (writer)").tag(Post.Origin.writer)
Text("AI-assisted (ai)").tag(Post.Origin.ai)
}
.pickerStyle(.radioGroup)
Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.")
.font(.caption)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Import") {
answer(origin)
dismiss()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 380)
}
}
/// Rail button per the export: 44×44 muted icon, hover wash, and the current
/// pane raised as a surface card with a 2px selection bar on the rail's edge.
private struct RailButton: View {
+1
View File
@@ -26,6 +26,7 @@ Owned by the root AGENTS.md contract.
- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `<ol>`, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars.
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
- `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0.
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our two keys win, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload.
## Verification
+168
View File
@@ -0,0 +1,168 @@
//
// ImportExternalTests.swift
// MuseionTests
//
// #22 (S1.1): import copies + external buffer — frontmatter merge (#95),
// batch semantics (#94), external save-in-place with no sidecar (#93).
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home in a temp dir (PostStoreTests convention).
private func importHome() throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-import-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
return home
}
private func writeExternal(_ name: String, _ body: String) throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-ext-\(UUID().uuidString)-\(name)")
try body.write(to: url, atomically: true, encoding: .utf8)
return url
}
@Suite(.serialized)
@MainActor
struct ImportExternalTests {
@Test func `import keeps external keys and stamps ours`() throws {
let home = try importHome()
let ext = try writeExternal("note.md", """
---
title: My Outside Note
date: 2026-10-11
tags: [one, two]
origin: ai
pass_state: Pass-2 Done
---
# My Outside Note
Body byte-for-byte.
""")
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .ai, home: home)
#expect(post.id == "my-outside-note")
#expect(post.passState == .firstDraft)
#expect(post.origin == .ai)
let onDisk = try String(contentsOf: home.appendingPathComponent("posts/my-outside-note/post.md"), encoding: .utf8)
// Our two keys win:
#expect(onDisk.contains("pass_state: First Draft"))
#expect(onDisk.contains("origin: ai"))
// External keys ride along:
#expect(onDisk.contains("date: 2026-10-11"))
#expect(onDisk.contains("tags: [one, two]"))
// Body byte-for-byte below the block:
#expect(onDisk.contains("# My Outside Note\n\nBody byte-for-byte."))
// The original file is untouched (copy, never move):
let original = try String(contentsOf: ext, encoding: .utf8)
#expect(original.contains("pass_state: Pass-2 Done"))
#expect(!original.contains("First Draft"))
}
@Test func `import survives CRLF frontmatter`() throws {
let home = try importHome()
// Windows-authored file: CRLF endings + frontmatter WITHOUT our keys.
// CRLF is normalized to LF at the import boundary (a CRLF pair is one
// grapheme in Swift — the \n-split machinery would see one line), so
// the block is detected, our keys inserted, and the body lands LF.
let ext = try writeExternal("crlf.md", "---\r\ndate: 2026-10-11\r\n---\r\n\r\n# CRLF Note\r\n\r\nBody.\r\n")
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .ai, home: home)
#expect(post.id == "crlf-note")
let onDisk = try String(contentsOf: home.appendingPathComponent("posts/crlf-note/post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(onDisk.contains("origin: ai"))
#expect(onDisk.contains("date: 2026-10-11"))
#expect(!onDisk.contains("\r")) // normalized at the boundary
}
@Test func `unreadable external file never opens as a writable empty session`() async throws {
// A UTF-16 encoded file: String(contentsOf: .utf8) fails → nil.
let ext = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-ext-\(UUID().uuidString)-utf16.md")
let data = "# Title\n\nBody.".data(using: .utf16)!
try data.write(to: ext)
defer { try? FileManager.default.removeItem(at: ext) }
let session = EditorSession(target: .externalFile(ext), debounce: .milliseconds(50))
#expect(session.loadFailed)
// Type into the empty editor, let the debounce fire: nothing is written.
session.edit("X")
try await Task.sleep(for: .milliseconds(200))
let disk = try String(contentsOf: ext, encoding: .utf16)
#expect(disk == "# Title\n\nBody.") // original untouched
}
@Test func `import bare file gets fresh block and untitled collision suffixes`() throws {
let home = try importHome()
let firstFile = try writeExternal("a.md", "# Same Title\n\nA.")
let secondFile = try writeExternal("b.md", "# Same Title\n\nB.")
defer { try? FileManager.default.removeItem(at: firstFile); try? FileManager.default.removeItem(at: secondFile) }
let first = try PostStore.importFile(at: firstFile, origin: .writer, home: home)
let second = try PostStore.importFile(at: secondFile, origin: .writer, home: home)
#expect(first.id == "same-title")
#expect(second.id == "same-title-2") // #60 machinery
let bare = try String(contentsOf: home.appendingPathComponent("posts/same-title/post.md"), encoding: .utf8)
#expect(bare.hasPrefix("---\npass_state: First Draft\norigin: writer\n---\n"))
}
@Test func `import empty file is untitled`() throws {
let home = try importHome()
let ext = try writeExternal("empty.md", "")
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .writer, home: home)
#expect(post.id == "untitled")
#expect(post.title == "untitled")
}
@Test func `external session saves in place with no sidecar`() async throws {
let home = try importHome()
let ext = try writeExternal("journal.md", "# Journal\n\nOne.")
defer { try? FileManager.default.removeItem(at: ext) }
let session = EditorSession(target: .externalFile(ext), debounce: .milliseconds(50))
#expect(session.postID == nil)
#expect(session.fileURL == ext)
#expect(session.text == "# Journal\n\nOne.")
session.edit("# Journal\n\nOne. Two.")
try await Task.sleep(for: .milliseconds(200))
#expect(session.saveState == .saved)
// Whole file verbatim — no frontmatter stamped:
let disk = try String(contentsOf: ext, encoding: .utf8)
#expect(disk == "# Journal\n\nOne. Two.")
// No sidecar next to the foreign file (#93):
let sidecar = ext.deletingLastPathComponent()
.appendingPathComponent(".museion-state.json")
#expect(!FileManager.default.fileExists(atPath: sidecar.path))
}
@Test func `external session raises the 67 conflict on foreign write`() throws {
_ = try importHome()
let ext = try writeExternal("conflict.md", "# C\n\nBase.")
defer { try? FileManager.default.removeItem(at: ext) }
let session = EditorSession(target: .externalFile(ext), debounce: .seconds(60))
// Someone edits the file underneath us:
try "# C\n\nForeign edit.".write(to: ext, atomically: true, encoding: .utf8)
session.diskDidChange(diskText: "# C\n\nForeign edit.")
#expect(session.conflictAlert)
// Yes-reload takes the foreign content:
session.reloadFromDisk()
#expect(!session.conflictAlert)
#expect(session.text == "# C\n\nForeign edit.")
}
}
@@ -0,0 +1,50 @@
# Session Log — #22 Build: M1 Import & external markdown (S1.1)
**Date:** 2026-10-12
**Branch:** `main` @ 683d697 (working tree; commit awaits authorization)
**Ticket:** [#22](https://git.babylondreams.de/AlexKucera/museion/issues/22) — wayfinder map that doubles as the build ticket
## What happened
Build session on map #22. All six decision tickets (#91–#96) were resolved live at charting; the map's Notes carry execution into the map itself — so this session claimed #22 and built the slice, verifying against the PRD S1.1 acceptance criteria.
### The shape
- **`SessionTarget`** (`.post(id, home)` | `.externalFile(url)`) in `EditorSession` — one session machinery, two write targets. The convenience `init(postID:home:)` keeps every #19 call site unchanged; `postID` became computed-optional (callers use `?? "post"` / `?.lastPathComponent` guards).
- **PostStore**: `importFile(at:origin:home:)` — read, split, `mergedFrontmatter` (external YAML keys verbatim; `pass_state`/`origin` set/overwritten in place; absent keys inserted before the closing `---`; empty block → fresh #59 shape), then the shared private `materialize` (the lazy-folder/TOCTOU path extracted from `writeNew`). `openableTypes` + `isMarkdown` give every entry point the same .md/.markdown list.
- **PostsModel**: `externalSession` guest slot (one at a time, transient per launch; `openExternal` flushes-and-replaces; `select`/`newPost` dismiss it flush-first); a second `PostsWatcher` on the external file's folder feeding the same `diskDidChange` conflict check; import staging (`stageImport`/`cancelImport`/`importFiles` — ONE Origin ask, per-file failures continue into `lastError`, last success opens).
- **UI**: File ▸ Open… ⌘O + Import… ⇧⌘O in `CommandGroup(after: .newItem)` (never `CommandMenu("File")` — #84 trap); window-level `dropDestination` for drag-onto-window; `OriginAskSheet` ("Who wrote this?", writer default / ai, immutability line); editor column renders the guest ahead of the post session; crumb shows the file name; the #67 alert names the actual file.
### Verification
- `xcodebuild build` — SUCCEEDED
- `xcodebuild test` (unit + UI) — SUCCEEDED; new `ImportExternalTests` (5 tests: #95 merge round-trip + original untouched, bare-file fresh block + `-2` collision, empty → `untitled`, save-in-place verbatim + NO sidecar, #67 foreign-write conflict + Yes-reload)
- `swiftlint` on changed files — 0 new violations (6 pre-existing `tv` warnings, verified identical at HEAD)
- GitNexus impact analysis run before edits (EditorSession/PostsModel = CRITICAL blast radius, expected for central types; all changes additive — new enum case members, new properties, no call-site behavior change). `detect-changes` after: affected flows are exactly select/saveDraft/flush/writeNew/PostsPaneView, all covered green.
### Traps dodged
- Blanket `swiftformat .` reformatted 14 unrelated files (version drift, same class as #88's log) — reverted, lint scoped to changed files.
- Two mid-generation slips (mangled placeholder text in PostStore/EditorSession patches) caught by re-read + build before anything shipped.
## Finish-audit round (same session)
Three fresh-context reviewers (ponytail / security / general) over the uncommitted diff. Accepted and fixed:
1. **CRLF + BOM imports mangled** (two reviewers, empirically confirmed): in Swift a CRLF pair is ONE grapheme, so every `\n`-split in the corpus machinery saw a CRLF file as a single line — id `date-20261011-crlf-note-body` instead of `crlf-note`. Root fix: normalize `\r\n`→`\n` + strip BOM at the import boundary (`importFile`) and on external reads (`readDocument`) — body lands LF, `byte-for-byte` now means per-decision content fidelity, not line-ending fidelity. Lone-CR (pre-OSX) files still degrade to `untitled` — ceiling named in a ponytail comment.
2. **Unreadable foreign file → silent empty editor → first keystroke destroys the original**: `loadFailed` in `EditorSession` (a session that never loaded never writes — `flush` no-ops), `openExternal` refuses the open into `lastError`.
3. **Dragged web link = sync network fetch**: `isMarkdown` now requires `url.isFileURL`.
4. **Atomic write severs symlinked external files**: `openExternal` resolves symlinks first.
5. **Ponytail trims (~24 lines)**: shared `markdownExtensions` list, dead `flushFirst` param on `dismissExternal`, redundant `Task` re-hop in the external watcher, unused `Equatable` on `SessionTarget`, one `pickMarkdown` helper for both menu panels.
Discarded: clearing `lastError` on batch success (matches the established saveDraft/rename/trash pattern), off-main import batch (documented single-file-I/O posture holds), drop-bypasses-Origin-ask (drop opens, never imports — by design). Tests: +2 (CRLF import, unreadable-file guard) — 7 in the suite; full unit+UI green; lint clean (pre-existing warnings only).
## Lessons
- The `SessionTarget` enum is the whole design: #92's "the shape is the build's call" resolved to "postID becomes optional, target drives I/O" — 30 lines instead of a parallel ExternalSession class. When two documents differ only in disk I/O, parametrize the I/O, not the session.
- Frontmatter merge is line-rewrite, not parse-and-restamp: keeping the external block verbatim except our two keys preserves comments, ordering, and unknown YAML shapes (#95) — a restamp would have normalized away the user's file.
- Swift grapheme clusters: `"\r\n" == one Character`. Any `split(separator: "\n")` over user text silently sees CRLF files as a single line. Normalize at the trust boundary, not per-call-site.
## Next
- Map #22 close-out (resolution comment + acceptance criteria checkboxes) happens after Alexander's live pass — same posture as #88's calibration gate.
+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-10-12 | issue | [20261012-issue22-import-external_log.md](20261012-issue22-import-external_log.md) | #22 import & external markdown: SessionTarget, guest slot, Origin ask, drag-drop — full suite green |
| 2026-10-09 | issue | [20261009-issue87-focus-mode_log.md](20261009-issue87-focus-mode_log.md) | #87 focus mode landed + audit fixes + ⌥⌘F shortcut; calibration gate #88 next |
| 2026-10-08 | issue | [20261008-issue84-view-menu-doubled_log.md](20261008-issue84-view-menu-doubled_log.md) | #84 single View menu: CommandMenu → CommandGroup(after: .toolbar), menu-count pin test — 105 tests green |
| 2026-10-08 | issue | [20261008-issue83-save-indicator-honesty_log.md](20261008-issue83-save-indicator-honesty_log.md) | #83 honest save dot: Changed while dirty, Saving… deleted, sticky failed, vanished-disk keepLocal fix — 106 tests green |