diff --git a/AGENTS.md b/AGENTS.md index 6983d78..1fde070 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (5626 symbols, 22797 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** (5702 symbols, 23152 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). @@ -184,6 +184,7 @@ This project is indexed by GitNexus as **museion** (5626 symbols, 22797 relation ### 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) - Post.frontmatter is LINE-BOUNDED on read — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (stampingFrontmatter), so gate external data before it reaches a stamp, not at scan (#33) ## Session Logs @@ -193,6 +194,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 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) | | 2026-10-31 | [20261031-issue32-m4-trend-view-s5-2_log.md](docs/devlog/20261031-issue32-m4-trend-view-s5-2_log.md) | @@ -202,5 +204,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 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) | -| 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 32abd1f..c326890 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format ### Added +- **editor:** Drop an image into the prose (#141) — dragging an image file onto a saved post's prose editor COPIES it (never moves) into the piece's `assets/` under a parser-clean slugged name (collision `-2` via the shared uniqueFile helper) and inserts `![alt](assets/.)` at the drop point with `alt` selected for immediate type-over; one edit step = one undo. The type gate is exactly the publish rail's set (#34's `Micropub.mimeType` — PNG/JPEG/GIF/WebP/SVG: nothing enters `assets/` that can't ship), a Finder folder or a dropped SYMLINK refuses (`copyItem` would land the link itself and the publish rail would refuse the whole send), and drafts/outline/guest surfaces refuse loudly with a transient strip. Routing rides the window-level SwiftUI drop destination — field-verified to starve every deeper drag destination (nested SwiftUI targets never fire, AppKit NSDraggingDestination never fires) — pure-markdown sets keep the open-as-guest behavior, mixed md+image sets refuse loudly instead of silently dropping the images. The drop-point mapping inverts the one geometry source that answers under SwiftUI hosting (`firstRect`, bottom-up screen coords): a viewport-banded sample→bracket→binary-search over it — non-contiguous layout returns garbage rects for off-screen characters, so only in-band rects are trusted — then a whitespace-gap slide so a landing never splices inside a word or an existing ref; the solve is a pure function pinned by windowless tests, and the typewriter inset re-syncs after the edit so scrolling never freezes. Eleven tests incl. a flip-verified finish-audit cycle; suite 557 (issue #141) - **publish:** Illustrations travel with it (PRD S6.2, G12) — a piece's `assets/` ink-sketch images now publish: Send as Draft first uploads every referenced image to Micro.blog's media endpoint (discovered per send via `GET ?q=config`, one multipart `file` POST per FILE — duplicate refs share an upload — decoding Location/body-url behind the trust gate), then each `![alt](assets/…)` ref REWRITES IN PLACE with its uploaded URL in the wire content, so the image renders exactly where the writer placed it and the alt rides the markdown (live dogfood killed the first shape: a Micropub `photo` property renders wherever the theme decides — the bottom — losing position; no property ships at all now). The piece on disk never changes. The floor (G12): a photo without alt text never ships — the send refuses naming the illustration BEFORE anything touches the wire, and a parsed body ref is the only way an image ships. Pre-flight gates every payload: the endpoint's exact formats only (PNG/JPEG/GIF/WebP/SVG — nothing enters `assets/` that can't ship), path containment resolved through symlinks (a planted link never uploads outside-file bytes under the writer's token), all-or-nothing uploads. A URL carrying markdown-active characters rides the angle form `![alt]()` — a plain-paren destination would close at the first `)` and smuggle a live link into the published post (the frontmatter trust gate doesn't cover markdown's grammar). The mentor is consulted for nothing — style judgment stays with the author. Seventeen tests incl. a flip-verified audit cycle; suite 546 (issue #34) - **publish:** Micropub draft → publish to Micro.blog (PRD S6.1, G2/G11) — a Publish button in the editor toolbar opens the two-step ask: Send as Draft (JSON Micropub `h=entry` create — name = the piece's Title, markdown content verbatim, `post-status: draft`; the piece's frontmatter `category:` is accepted but never travels), review via the Micro.blog preview link, then Publish (the `action=update` post-status flip against the piece's remembered `micropub_url` — persisted in frontmatter so a draft survives a reopen; Send Again re-drafts after edits). The Micro.blog app token lives in the Keychain (login keychain, entered once in the sheet, re-offered only on an auth failure — rotation replaces). Every draft URL passes a format gate at both the decode and the scan read-back: the URL is trust-boundary data landing in frontmatter, and a newline-`---` rider would close the block and reparse as attacker markdown in the writer's piece; the preview URL is display-only, never the publish target. Frontmatter-only stamps keep the body and foreign keys byte-identical (issue #33) - **stats:** Trend view — the writer's arc (PRD S5.2) — a Trends pane (rail destination after Learnings, measurement beside memory): one line chart per style metric (burstiness, type-token ratio, sentence variation, trigram repetition) across unaided-first-draft CAPTURES over time, each card carrying an honest first→last read (`improving`/`steady`/`slipping` at ±0.01, direction inverted for trigram repetition — the one ↓-better metric; one capture shows its value with no verdict) plus the per-metric ↑/↓-better hint and a one-line plain-language gloss of the term beneath each chart (grain + better-direction, pinned distinct). Points are capture moments, never draft grades — the pane answers "am I getting better," not "is this draft good." The edited-text leak is closed by construction: `Post.scan` reads the five `stats_*` frontmatter keys into `firstDraftStats` only when every key parses to a finite double AND the piece carries the capture gate's immutable pair (origin writer, type post) — so ai-origin pieces, outlines, edited-before-first-pass drafts, and imported or hand-edited frontmatter (non-finite values, stamped ai pieces) carry nothing to show, while a migrated writer piece keeps its real arc. The pane rides PostsModel's watched scan (no scan of its own, refreshes with the library); fixed y-domains keep single captures visible (sentence variation scales to its peak); the empty state names how the data arrives (issue #32) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 49d1bbb..0cc86fa 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -24,7 +24,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). - `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`). - `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling). -- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. **#33 (S6.1):** `stampMicropubURL(id:url:home:)` — in-place `micropub_url` stamp through `stampingFrontmatter` (frontmatter-only: body + foreign keys byte-identical, so the open session's readBody echo check never fires); vanished piece throws. +- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. **#33 (S6.1):** `stampMicropubURL(id:url:home:)` — in-place `micropub_url` stamp through `stampingFrontmatter` (frontmatter-only: body + foreign keys byte-identical, so the open session's readBody echo check never fires); vanished piece throws. **#141:** same-file extension — the illustration ingest write side: `ingestImage(from:pieceFolder:)` copies (never moves) a dropped image into the piece's `assets/` and returns the ref destination; type gate = #34's `Micropub.mimeType` set (PNG/JPEG/GIF/WebP/SVG — nothing enters assets/ that can't ship, `IngestError.notPublishable`), a Finder folder with an image extension refuses (`isFolder`), a symlinked/file-shaped `assets/` refuses (`hostileAssets` — never write through it, the rail would refuse the send anyway); base name through the shared `slug` (parser-clean: the #34 regex never matches space-bearing destinations, so ref and file agree at ingest), collisions suffix `-2`/`-3` within `assets/`; `illustrationRef(_:)` is the one `![alt](assets/…)` builder the drop surface and tests share. - `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`). - `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft). - `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`. @@ -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/` 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. +- 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 coordinator (reattribute + session.edit + folds); refusals land in the transient `showIngestNotice` strip (mono-11 rust pill pinned to the scroll view's top-center, auto-hide ~4 s), multi-image ingest is non-atomic by design (ponytail comment). Outline surfaces have no ProseTextView → the bridge is nil → image drags bounce (AC4), markdown forwards. Reading mode swaps the surface away — no editor drop target while reading. - Settings (#135 Profiles S2 + #136 Profiles S3 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; 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 config set model.provider/model.default/model.reasoning_effort` set-or-unset + `model.base_url` for the z.ai family; wire-verified `✓ Set/✓ Unset ` lines — unset-when-absent = idempotent success, exit 1 + the not-set line), provider keys upsert `VAR=value` into **ALL THREE profiles' `.env`** (2026-10-28 dogfood amendment: a key entered before any surface is on its provider still persists — inert vars are ignored by hermes for other providers — and pre-lands for any later provider switch; var names from hermes' own registry, `ModelProvider.envVarName`: GLM_API_KEY/ANTHROPIC_API_KEY/OPENAI_API_KEY; foreign lines preserved byte-for-byte via pure `upsertEnv`; a value containing a line break/NUL is REFUSED at the shared sink before any file is touched (2026-10-28 audit fix: a pasted `key\nOTHER_VAR=x` is an env-file injection — the error rides `lastWriteError`); an `NSLock` serializes the read→upsert→write across concurrent cross-provider key writes (the same three files — a racing last writer would drop the other's var); 0600 — hermes' own .env posture; an EMPTY key leaves `.env` alone — the field sets, never removes; the zai `model.base_url` write-through rides only the profiles on zai — `profiles` is that target list, not the .env list), `readSurface` hydrates via `config get` ×4 (provider/model/effort/base_url) and `readProviderKey` reads each provider's var back (first non-empty across the three `.env` files) so a restart neither blanks the key fields nor refuses Test Connection; all blocking work hops off-main inside `Task.detached`; secrets never ride argv and never reach `lastWriteError`; `hermesBinary` nil (pre-gate) refuses writes honestly. `ProviderProbe.swift` — Test Connection (factsheet §4, live-probed wire shapes 2026-10-27, corrected 2026-10-28 after dogfood): step 1 `GET /models` (key validity + reachability; z.ai proves nothing about key-type pairing — §1.2), step 2 a minimal STREAMING chat call — **every request carries `Content-Type: application/json`** (the 2026-10-28 live incident: without it URLSession defaults to form-urlencoded — z.ai answers HTTP 200 with an error envelope, OpenAI can't parse the body at all; curl set it, the app didn't, Anthropic tolerated it); zai pins the stable GLM wire (`thinking:enabled`+`reasoning_effort:low`) at `{endpoint}/chat/completions`; **OpenAI speaks the RESPONSES API** (`{endpoint}/responses`, `input` + `max_output_tokens` — maintainer correction 2026-10-28, chat-completions is the retired path); Anthropic posts `{endpoint}/v1/messages` (`max_tokens` required) authing via `x-api-key` + pinned `anthropic-version` 2023-06-01, never Bearer; the token cap is **512** (`probeTokenCap` — the live tail proved 64 starves reasoning models: glm-5.3 burned 64/64 on thinking, finish=length, zero content); decode is honest per the factsheet envelopes — zai `error.code` 1113 → wrongKeyType, 401s → authFailed (Anthropic detail carries `request_id`), transport errors → unreachable, `finish=length`/`max_tokens`/`incomplete` + empty content → starved, an empty 200 → requestFailed, and **errors riding a 2xx decode as the provider error** (z.ai's 200-carried content-type envelope live-probed; OpenAI nests it under `response.error`); `works` carries latency + model count (the reply payload died in the 2026-10-28 audit — no consumer); the `Transport` closure is injectable (production buffers the streamed response over URLSession); URL builders are nil-safe (a garbage endpoint reads unreachable, never traps). The Provider Keys page carries a per-provider **Test Connection** button + one-line verdict (`TestConnectionResult`: accent "✓ works · N ms · N models" / orange decoded failures). DesignTokens gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480. **#137 (S4):** `SettingsModel.onChatSurfaceWrite` fires after a SUCCESSFUL chat-surface write ONLY (never pass surfaces — their engines are one-shot — never key writes, never failures); `SettingsPaneView` takes the closure and WorkspaceView wires it to `gate.mentor.requestRestart()`, so a committed Chat model change restarts the resident engine in place (deferred to turn end while streaming, slice A's API). - Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. - Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir ]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one
    , killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `
    ` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
    diff --git a/Museion/MuseionApp.swift b/Museion/MuseionApp.swift
    index 2fbdc63..1c469e7 100644
    --- a/Museion/MuseionApp.swift
    +++ b/Museion/MuseionApp.swift
    @@ -13,6 +13,12 @@ import SwiftUI
     @MainActor
     @Observable
     final class AppGateState {
    +	/// #141: the live prose text view — the window-level drop destination
    +	/// (the ONLY destination that ever fires; nested editor-level SwiftUI
    +	/// targets are never consulted, and AppKit views registered for file
    +	/// drags are starved by it — field-verified 2026-11-02) routes image
    +	/// drops to the editor through this handle.
    +	let proseDrop = ProseDropBridge()
     	var gateRaised = true
     	/// True once the gate sheet's onDismiss fired (dismissal completion, #48) —
     	/// the provisioning failure card presents only after this.
    diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift
    index 120d066..17b4cde 100644
    --- a/Museion/PostEditorView.swift
    +++ b/Museion/PostEditorView.swift
    @@ -176,12 +176,25 @@ struct PostEditorView: View {
     				draftText: session == nil ? draftText : nil,
     			)
     		} else if let session {
    -			ProseTextView(session: session, spellChecking: gate.spellChecking, focused: gate.isFocused, caretHint: flipBackCaret)
    +			ProseTextView(
    +				session: session,
    +				spellChecking: gate.spellChecking,
    +				focused: gate.isFocused,
    +				caretHint: flipBackCaret,
    +				dropBridge: gate.proseDrop,
    +			)
     		} else {
    -			ProseTextView(draft: draftMirror, spellChecking: gate.spellChecking, focused: gate.isFocused, onEdit: { newText in
    -				draftMirror = newText
    -				draftEdited?(newText)
    -			}, caretHint: flipBackCaret)
    +			ProseTextView(
    +				draft: draftMirror,
    +				spellChecking: gate.spellChecking,
    +				focused: gate.isFocused,
    +				onEdit: { newText in
    +					draftMirror = newText
    +					draftEdited?(newText)
    +				},
    +				caretHint: flipBackCaret,
    +				dropBridge: gate.proseDrop,
    +			)
     		}
     	}
     
    @@ -309,6 +322,13 @@ private struct SaveStateDot: View {
     
     // MARK: - TextKit2 surface (the lifted spike pane)
     
    +/// #141: the SwiftUI drop target's handle down to the live prose text
    +/// view (weak — dies with the editor surface).
    +@MainActor
    +final class ProseDropBridge {
    +	weak var textView: ProseListTextView?
    +}
    +
     /// NSTextView in a scroll view; attributes are presentation-only over a plain
     /// store. Session mode: edits → session.edit (debounce), cursor → session,
     /// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
    @@ -322,17 +342,28 @@ struct ProseTextView: NSViewRepresentable {
     	/// #21: focus mode — the text ground joins the workspace background.
     	var focused = false
     	var caretHint: (location: Int, token: Int)?
    +	/// #141: the piece folder dropped images ingest into — saved posts
    +	/// only (drafts have no folder until first save; the external guest
    +	/// isn't a piece). Nil = image drags refuse loudly.
    +	var ingestFolder: URL?
    +	/// #141: the drop bridge — the WINDOW-level SwiftUI drop target
    +	/// reaches this text view through it (app-scoped, passed down from
    +	/// the gate at both call sites — never optional).
    +	var dropBridge: ProseDropBridge
     
     	init(
     		session: EditorSession,
     		spellChecking: Bool = false,
     		focused: Bool = false,
     		caretHint: (location: Int, token: Int)? = nil,
    +		dropBridge: ProseDropBridge,
     	) {
     		self.session = session
     		self.spellChecking = spellChecking
     		self.focused = focused
     		self.caretHint = caretHint
    +		ingestFolder = session.postID != nil ? session.folderURL : nil
    +		self.dropBridge = dropBridge
     	}
     
     	init(
    @@ -341,12 +372,14 @@ struct ProseTextView: NSViewRepresentable {
     		focused: Bool = false,
     		onEdit: @escaping (String) -> Void,
     		caretHint: (location: Int, token: Int)? = nil,
    +		dropBridge: ProseDropBridge,
     	) {
     		self.draft = draft
     		self.spellChecking = spellChecking
     		self.focused = focused
     		self.onEdit = onEdit
     		self.caretHint = caretHint
    +		self.dropBridge = dropBridge
     	}
     
     	/// Cursor state snapshot from the live view (#66).
    @@ -361,6 +394,8 @@ struct ProseTextView: NSViewRepresentable {
     
     	func makeNSView(context: Context) -> NSScrollView {
     		let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
    +		tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests)
    +		dropBridge.textView = tv // #141: the SwiftUI drop target's handle
     		tv.isRichText = false // plain source of truth; attributes are presentation
     		tv.allowsUndo = true
     		tv.isAutomaticQuoteSubstitutionEnabled = false
    @@ -407,6 +442,8 @@ struct ProseTextView: NSViewRepresentable {
     		guard let tv = scroll.documentView as? ProseListTextView else { return }
     		// #77: posture toggle while editing — cheap idempotent set.
     		tv.isContinuousSpellCheckingEnabled = spellChecking
    +		tv.ingestFolder = ingestFolder // #141: cheap idempotent set
    +		dropBridge.textView = tv // #141: idempotent re-point
     		// #21: the ground follows focus in/out without a remount.
     		let ground = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
     		tv.backgroundColor = ground
    diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift
    index 1b46d9b..07b0441 100644
    --- a/Museion/PostStore.swift
    +++ b/Museion/PostStore.swift
    @@ -788,3 +788,88 @@ nonisolated extension PostStore {
     			.write(to: file, atomically: true, encoding: .utf8)
     	}
     }
    +
    +// MARK: - #141 Illustration ingest
    +
    +/// #141's refusal reasons — the drop surface shows `localizedDescription`
    +/// as its visible feedback (CardError/WriteError voice).
    +struct IngestError: LocalizedError {
    +	let message: String
    +	var errorDescription: String? {
    +		message
    +	}
    +
    +	static func notPublishable(_ name: String) -> IngestError {
    +		IngestError(message: "“\(name.prefix(40))” isn’t publishable — PNG, JPEG, GIF, WebP, or SVG.")
    +	}
    +
    +	/// A dropped symlink (e.g. an unzipped archive entry) — copyItem would
    +	/// land the LINK itself in assets/; the #34 rail then refuses the send.
    +	static func isLink(_ name: String) -> IngestError {
    +		IngestError(message: "“\(name.prefix(40))” is a link, not an image file.")
    +	}
    +
    +	/// A Finder folder with an image extension — the extension gate
    +	/// alone would copyItem a whole directory into assets/.
    +	static func isFolder(_ name: String) -> IngestError {
    +		IngestError(message: "“\(name.prefix(40))” is a folder, not an image.")
    +	}
    +
    +	/// assets/ exists as a symlink or a file — never write through it
    +	/// (research/promote posture: the #34 rail would refuse the send).
    +	static func hostileAssets() -> IngestError {
    +		IngestError(message: "assets/ isn’t a plain folder in this piece.")
    +	}
    +}
    +
    +nonisolated extension PostStore {
    +	/// The inserted ref for a landed asset: `![alt](assets/…)` with
    +	/// `alt` as the selected placeholder for immediate type-over. The
    +	/// destination is parser-clean BY CONSTRUCTION (see `ingestImage`),
    +	/// so this exact string rides #34's rail — one helper so the drop
    +	/// surface and the tests can never drift.
    +	static func illustrationRef(_ destination: String) -> String {
    +		"![alt](\(destination))"
    +	}
    +
    +	/// #141: copy a dropped image into the piece's `assets/` — copy,
    +	/// never move — and return the ref destination that names it. The
    +	/// base name goes through the shared `slug` (whitespace→hyphens and
    +	/// more: lowercase, diacritic-fold, 80-char cap) because the #34
    +	/// parser never matches space-bearing destinations — the ref and
    +	/// the file must agree at ingest. Collisions suffix `-2`/`-3`…
    +	/// within `assets/`. Type gate = #34's publish-able set, checked
    +	/// BEFORE anything lands.
    +	static func ingestImage(from source: URL, pieceFolder: URL) throws -> String {
    +		let name = source.lastPathComponent
    +		guard Micropub.mimeType(forDestination: name) != nil else {
    +			throw IngestError.notPublishable(name)
    +		}
    +		// The source must be a plain file: copyItem would land a symlink
    +		// AS a link (finish-audit 2026-11-02), and the #34 rail then
    +		// refuses the whole send — nothing enters assets/ that can't ship.
    +		let values = try? source.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
    +		guard source.isFileURL, let values,
    +		      values.isDirectory != true, values.isSymbolicLink != true
    +		else {
    +			throw values?.isSymbolicLink == true ? IngestError.isLink(name) : IngestError.isFolder(name)
    +		}
    +		let assets = pieceFolder.appendingPathComponent("assets", isDirectory: true)
    +		if FileManager.default.fileExists(atPath: assets.path) {
    +			// A symlinked or file-shaped assets/ never takes the write.
    +			guard let values = try? assets.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]),
    +			      values.isDirectory == true, values.isSymbolicLink != true
    +			else {
    +				throw IngestError.hostileAssets()
    +			}
    +		} else {
    +			try FileManager.default.createDirectory(at: assets, withIntermediateDirectories: true)
    +		}
    +		let ext = source.pathExtension.lowercased()
    +		let base = slug(from: source.deletingPathExtension().lastPathComponent)
    +		let landed = FixCardStore.uniqueFile(assets, base: base, ext: ext)
    +		let destination = "assets/\(landed)"
    +		try FileManager.default.copyItem(at: source, to: assets.appendingPathComponent(landed))
    +		return destination
    +	}
    +}
    diff --git a/Museion/ProseListTextView.swift b/Museion/ProseListTextView.swift
    index 25a1a55..ec420be 100644
    --- a/Museion/ProseListTextView.swift
    +++ b/Museion/ProseListTextView.swift
    @@ -222,6 +222,180 @@ final class ProseListTextView: NSTextView {
     		return len > 0 ? buffer.substring(with: NSRange(location: line.location, length: len)) : ""
     	}
     
    +	// MARK: Image ingest (#141)
    +
    +	/// #141: the piece folder dropped images ingest into — non-nil only
    +	/// on a saved post's prose surface (drafts and the external guest
    +	/// carry nil; image drags then refuse loudly). Set by ProseTextView
    +	/// when the session is known.
    +	var ingestFolder: URL?
    +
    +	/// #141's drop-point solve, pure for tests (#115 field finding: under
    +	/// SwiftUI hosting the TextKit2 point→character APIs misanswer — invert
    +	/// the one geometry source that DOES answer, `firstRect`, whose y is
    +	/// bottom-up screen coords like mouseLocation and DECREASES with index).
    +	/// Non-contiguous layout makes OFF-SCREEN chars lie (zero/stale rects,
    +	/// dogfood 2026-11-02) — so sample the document, keep only rects inside
    +	/// the viewport band (plain NSView geometry — trusted), bracket the drop
    +	/// between two in-band samples, binary-search the bracket. Pointer above
    +	/// every in-band sample → the first visible char; below all → the last
    +	/// in-band sample; no in-band evidence at all (viewless/garbage) → 0.
    +	nonisolated static func dropIndex(
    +		length: Int,
    +		targetY: CGFloat,
    +		bandMinY: CGFloat,
    +		bandMaxY: CGFloat,
    +		sampleCount: Int = 512,
    +		rectY: (Int) -> CGFloat,
    +	) -> Int {
    +		guard length > 0 else { return 0 }
    +		var lastAbove: Int?
    +		var firstInBand = -1
    +		for s in 0 ... sampleCount {
    +			let i = min(length - 1, s * length / sampleCount)
    +			let y = rectY(i)
    +			guard y >= bandMinY, y <= bandMaxY else { continue }
    +			if firstInBand < 0 {
    +				firstInBand = i
    +			}
    +			if y >= targetY {
    +				lastAbove = i // at-or-above the drop on screen
    +			} else if let above = lastAbove, above < i {
    +				// Bracket [above, i] straddles the drop; both ends are
    +				// in-band (laid out, monotone) so the search probes real rects.
    +				var lo = above
    +				var hi = i
    +				while lo < hi {
    +					let mid = (lo + hi) / 2
    +					if rectY(mid) >= targetY {
    +						lo = mid + 1
    +					} else {
    +						hi = mid
    +					}
    +				}
    +				return min(lo, length)
    +			}
    +		}
    +		return min(lastAbove ?? max(firstInBand, 0), length)
    +	}
    +
    +	private func rectY(_ i: Int, of length: Int) -> CGFloat {
    +		guard window != nil, i >= 0, i < length else { return -1 } // viewless (tests): land at index 0
    +		return firstRect(forCharacterRange: NSRange(location: i, length: 1), actualRange: nil).midY
    +	}
    +
    +	/// #141's SwiftUI entry — the window `.dropDestination`'s perform
    +	/// routes here after markdown forwarding is ruled out upstream.
    +	/// The drop point is read from the live pointer (NSEvent.mouseLocation
    +	/// — the SwiftUI closure's location proved unusable, dogfood 2026-11-02).
    +	/// Gates: saved piece, every file publishable (#34's mimeType set) —
    +	/// refuse loudly otherwise; then copy each file into assets/ and
    +	/// insert the refs at the drop point, `alt` selected for type-over.
    +	/// One shouldChangeText step = one undo; didChangeText drives the
    +	/// delegate (reattribute + session.edit + folds).
    +	func ingestDrop(_ urls: [URL]) -> Bool {
    +		guard let ingestFolder else {
    +			showIngestNotice("Illustrations only land in a saved post's prose editor.")
    +			return false
    +		}
    +		// The publish-able set IS #34's mimeType gate — nothing the rail
    +		// can't ship ever enters assets/. A mixed md+image set refuses
    +		// here too (only pure-markdown sets are forwarded upstream).
    +		guard urls.allSatisfy({ Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else {
    +			showIngestNotice("Drop images (PNG, JPEG, GIF, WebP, SVG) or markdown — one kind at a time.")
    +			return false
    +		}
    +		let length = (string as NSString).length
    +		let mouse = NSEvent.mouseLocation
    +		let screenVisible = window?.convertToScreen(convert(visibleRect, to: nil)) ?? .zero
    +		var index = Self.dropIndex(
    +			length: length,
    +			targetY: mouse.y,
    +			bandMinY: screenVisible.minY,
    +			bandMaxY: screenVisible.maxY,
    +		) { i in
    +			rectY(i, of: length)
    +		}
    +		// Never splice inside a word or link — slide to the next gap
    +		// (a drop ON an existing ref appends after it, dogfood 2026-11-02).
    +		let buffer = string as NSString
    +		func isGap(_ c: unichar) -> Bool {
    +			guard let scalar = Unicode.Scalar(Int(c)) else { return false }
    +			return CharacterSet.whitespacesAndNewlines.contains(scalar)
    +		}
    +		if index > 0, index < length,
    +		   !isGap(buffer.character(at: index - 1)),
    +		   !isGap(buffer.character(at: index))
    +		{
    +			while index < length, !isGap(buffer.character(at: index)) {
    +				index += 1
    +			}
    +		}
    +		do {
    +			// ponytail: multi-image ingest is non-atomic — if file N
    +			// fails mid-loop, earlier copies orphan in assets/ (harmless:
    +			// never referenced, never shipped; the collision suffix
    +			// absorbs them on retry). Pre-flight all sources if it bites.
    +			let snippet = try urls.map {
    +				try PostStore.illustrationRef(PostStore.ingestImage(from: $0, pieceFolder: ingestFolder))
    +			}.joined(separator: " ")
    +			guard shouldChangeText(in: NSRange(location: index, length: 0), replacementString: snippet) else { return false }
    +			textStorage?.replaceCharacters(in: NSRange(location: index, length: 0), with: snippet)
    +			didChangeText()
    +			// The first ref's `alt` (offset +2, length 3): one keystroke
    +			// replaces it with the real description.
    +			let alt = NSRange(location: index + 2, length: 3)
    +			setSelectedRange(alt)
    +			// Leave the scroll stack as a keystroke would (dogfood
    +			// 2026-11-02: without this the inset was out of sync and the
    +			// editor froze scrolling until the next keypress).
    +			CaretCentering.syncTypewriterInset(textView: self)
    +			scrollRangeToVisible(alt)
    +			return true
    +		} catch {
    +			showIngestNotice("Couldn't ingest the image — \(error.localizedDescription)")
    +			return false // refused honestly: the drop bounces + the strip names why
    +		}
    +	}
    +
    +	/// The transient refusal strip — mono-11 rust on a surface pill
    +	/// (focusChip voice), pinned to the scroll view's top-center so it
    +	/// never scrolls with the document. Auto-hides ~4 s after the last
    +	/// refusal.
    +	private var ingestNotice: NSTextField?
    +	private var ingestNoticeHide: DispatchWorkItem?
    +
    +	private func showIngestNotice(_ text: String) {
    +		let strip: NSTextField
    +		if let ingestNotice {
    +			strip = ingestNotice
    +		} else {
    +			strip = NSTextField(labelWithString: "")
    +			strip.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .regular)
    +			strip.textColor = NSColor(DesignTokens.accent)
    +			strip.alignment = .center
    +			strip.lineBreakMode = .byTruncatingMiddle
    +			strip.cell?.truncatesLastVisibleLine = true
    +			strip.wantsLayer = true
    +			strip.layer?.cornerRadius = DesignTokens.radius
    +			strip.layer?.masksToBounds = true
    +			strip.layer?.backgroundColor = NSColor(DesignTokens.surface).withAlphaComponent(0.96).cgColor
    +			ingestNotice = strip
    +		}
    +		strip.stringValue = text
    +		guard let host = enclosingScrollView ?? window?.contentView else { return }
    +		if strip.superview !== host {
    +			host.addSubview(strip)
    +		}
    +		strip.sizeToFit()
    +		let width = min(strip.frame.width + 28, host.bounds.width - 24)
    +		strip.frame = NSRect(x: (host.bounds.width - width) / 2, y: host.bounds.height - 36, width: width, height: 26)
    +		ingestNoticeHide?.cancel()
    +		let hide = DispatchWorkItem { [weak strip] in strip?.removeFromSuperview() }
    +		ingestNoticeHide = hide
    +		DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: hide)
    +	}
    +
     	// MARK: Chrome (chevron + ⋯ N)
     
     	/// Plain overlay sibling that owns the chrome drawing — TextKit2 views hosted
    diff --git a/Museion/WorkspaceView.swift b/Museion/WorkspaceView.swift
    index 49a84e0..26ee832 100644
    --- a/Museion/WorkspaceView.swift
    +++ b/Museion/WorkspaceView.swift
    @@ -51,10 +51,21 @@ 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
    +				// #141: the window destination is the only one that ever
    +				// fires (field-verified 2026-11-02 — nested editor-level
    +				// SwiftUI targets are never consulted, and AppKit views
    +				// registered for file drags are starved by it).
    +				// PURE-markdown sets keep #91's open-as-guest; a mixed
    +				// md+image set falls through and ingestDrop refuses it
    +				// loudly (images must not vanish silently behind the md).
    +				// Nil text view: bounce.
    +				if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
    +					gate.posts.openExternal(url)
    +					selection = .posts
    +					return true
    +				}
    +				guard let textView = gate.proseDrop.textView else { return false }
    +				return textView.ingestDrop(urls)
     			}
     			// #21: left-edge hover slides rail+library back in as an overlay.
     			// Library only while the window width allows it (#17 verdict stands:
    diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md
    index 57ef75e..ff693ef 100644
    --- a/MuseionTests/AGENTS.md
    +++ b/MuseionTests/AGENTS.md
    @@ -37,7 +37,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 `
      `, 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 keys win — external `type: outline` overwritten to `type: post`, 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. Imports land at `projects/posts//post.md` (#107). +- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, 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. Imports land at `projects/posts//post.md` (#107). `ImageIngestTests.swift` (#141, own file, `@Suite` + `@MainActor` — scenario header at file top) pins the ingest write side: a dropped image lands slugged (`My Ink Sketch.png` → `assets/my-ink-sketch.png`), byte-identical, COPY-never-move (the source survives); a same-named second drop collides `-2` and the ref's destination always matches the landed name; `PostStore.illustrationRef` builds the exact `![alt](assets/…)` string and it rides #34's rail (`Micropub.illustrations` parses it with alt + destination — the Send-as-Draft round-trip shape); HEIC/PDF/a Finder folder with an image extension all throw `IngestError` with `assets/` never materialized. The drag layer pins drive `ingestDrop` directly (the SwiftUI drop target's perform entry, no drag session): copies/lands/inserts/alt-selects; HEIC and a nil-folder draft both refuse loudly with nothing planted. **Finish-audit pins (2026-11-02):** a dropped SYMLINK refuses with nothing planted (`isLink` — `copyItem` would land the link itself, empirically verified); a mixed image+markdown set refuses loudly with nothing inserted (the ingest-side gate of the window destination's pure-markdown routing — the SwiftUI closure itself is unpinned, no harness); and the drop-point solve is pinned WITHOUT a window via the extracted pure `dropIndex` (banded synthetic rectY: exact drop-line landing, pointer-above-viewport → first visible char — the flip-verified discriminator against the old zero-trusted fallback, pointer-below → band tail, garbage geometry → 0) — all flip-verified in one batched cycle (each pin failed on its own guard). - `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet. **#112:** extract/insertRun pins — subtree pull by path (ids travel, bad paths nil), sibling splices at any parent (index clamp-to-append, contiguous run order, unresolvable parent false + untouched, empty run refused). **#114:** `headingsLadderBody` pin — ladder shape to the `######` floor, bullet remainder re-based, preamble verbatim, mixed-content prose drops. - `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). **#112 (S6):** nine pins — `draggedIDs` dedup (selection rides, ancestor carries descendants, unselected/no-selection go solo), `isValidDrop` (ref moving / inside moving subtree / own-parent-legal / unknown), precise `before`/`afterLast`/`lastChild` landings (incl. the seam-below-a-deeper-follower FIRST-child nest and cross-parent extraction that keyboard batches refuse), contiguous deduped batch landing with id travel, origin no-ops + invalid refusals (snapshot equality — storage untouched), zoom projection (children rooted, depths re-based, zoom root's fold ignored, inner folds still hide, unknown id → whole doc), `rangeIDs` nil across the zoom boundary, and `hitTestDrop` fat-gap bands (30/40/30, ±6 into edge rows, window-space y-up frames, empty rows nil). - `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`). diff --git a/MuseionTests/ImageIngestTests.swift b/MuseionTests/ImageIngestTests.swift new file mode 100644 index 0000000..7537709 --- /dev/null +++ b/MuseionTests/ImageIngestTests.swift @@ -0,0 +1,214 @@ +// +// ImageIngestTests.swift +// MuseionTests +// +// #141: illustration ingest — a dropped image lands in the piece's +// assets/ under a parser-clean slugged name (collision -2), copied +// never moved, and the inserted ref rides #34's rail (parses with +// alt + destination). Non-publishable types refuse honestly with +// nothing planted. +// +// ## Scenario: Drop an image, get a publish-able illustration +// From #141 +// +// Given a saved post open in the prose editor and a publishable image +// file in Finder +// When the writer drops it at a point in the prose +// Then the file is copied (never moved) into the piece's assets/ under +// a slugged name, and ![alt](assets/.) is inserted at the +// drop point with alt selected for type-over +// And a non-publishable file refuses with nothing copied or inserted +// + +import AppKit +import Foundation +@testable import Museion +import Testing + +@MainActor +struct ImageIngestTests { + /// Throwaway Home + a saved post standing in for the open editor + /// (PostStoreTests convention). + private func ingestHome() throws -> (home: URL, folder: URL) { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("imageingest-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + let post = try PostStore.writeNew(body: "# Ink\n\nBody.", home: home) + let folder = try #require(PostStore.folder(of: post.id, home: home)) + return (home, folder) + } + + /// A source image standing in for the Finder drag — minimal bytes; + /// the gate is extension-based, matching #34's rail. + private func imageSource(_ name: String, bytes: [UInt8] = [0x89, 0x50, 0x4E, 0x47]) throws -> URL { + let dir = FileManager.default.temporaryDirectory + .appendingPathComponent("imageingest-src-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let url = dir.appendingPathComponent(name) + try Data(bytes).write(to: url) + return url + } + + @Test func `dropped image lands slugged, copied never moved, and rides the rail`() throws { + let (home, folder) = try ingestHome() + let source = try imageSource("My Ink Sketch.png") + let bytes = try Data(contentsOf: source) + + let destination = try PostStore.ingestImage(from: source, pieceFolder: folder) + + #expect(destination == "assets/my-ink-sketch.png") + #expect(try Data(contentsOf: folder.appendingPathComponent(destination)) == bytes) // landed byte-identical + #expect(FileManager.default.fileExists(atPath: source.path)) // copy, never move + + // The inserted ref must ride #34's rail: it parses with the alt + // placeholder and the landed destination (slug + collision agree). + let ref = PostStore.illustrationRef(destination) + #expect(ref == "![alt](assets/my-ink-sketch.png)") + #expect(Micropub.illustrations(in: ref) == [Micropub.Illustration(alt: "alt", destination: destination)]) + } + + @Test func `same-named second drop collides -2 with the ref matching the landed name`() throws { + let (_, folder) = try ingestHome() + _ = try PostStore.ingestImage(from: imageSource("sketch.png"), pieceFolder: folder) + + let second = try PostStore.ingestImage(from: imageSource("sketch.png"), pieceFolder: folder) + + #expect(second == "assets/sketch-2.png") // -2, not a clobber + #expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets/sketch.png").path)) + #expect(Micropub.illustrations(in: PostStore.illustrationRef(second)).first?.destination == second) + } + + @Test func `non-publishable types refuse with nothing planted`() throws { + let (_, folder) = try ingestHome() + let heic = try imageSource("photo.heic") + let pdf = try imageSource("paper.pdf") + // A Finder FOLDER with an image extension — the extension gate + // alone would copyItem a whole directory into assets/. + let folderPng = FileManager.default.temporaryDirectory + .appendingPathComponent("imageingest-src-\(UUID().uuidString)", isDirectory: true) + .appendingPathComponent("trick.png", isDirectory: true) + try FileManager.default.createDirectory(at: folderPng, withIntermediateDirectories: true) + + #expect(throws: IngestError.self) { try PostStore.ingestImage(from: heic, pieceFolder: folder) } + #expect(throws: IngestError.self) { try PostStore.ingestImage(from: pdf, pieceFolder: folder) } + #expect(throws: IngestError.self) { try PostStore.ingestImage(from: folderPng, pieceFolder: folder) } + // Refusal planted nothing — assets/ was never even materialized. + #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path)) + } + + // MARK: - #141 drag-layer entry (ingestDrop — the SwiftUI drop + + // target's perform lands on the text view) + + @Test func `ingestDrop copies lands the ref and selects alt`() throws { + let (_, folder) = try ingestHome() + let tv = ProseListTextView() + tv.string = "Hello paragraph.\n\nSecond paragraph.\n" + tv.ingestFolder = folder + + #expect(try tv.ingestDrop([imageSource("ink sketch.png")])) + + let landed = folder.appendingPathComponent("assets").appendingPathComponent("ink-sketch.png") + #expect(FileManager.default.fileExists(atPath: landed.path)) + #expect(tv.string.contains("![alt](assets/ink-sketch.png)"), "ref not inserted: \(tv.string)") + let refNSString = tv.string as NSString + let refLoc = refNSString.range(of: "![alt](assets/ink-sketch.png)").location + #expect(tv.selectedRange() == NSRange(location: refLoc + 2, length: 3), "alt not selected (sel=\(tv.selectedRange()))") + } + + @Test func `ingestDrop refuses loudly and plants nothing`() throws { + let (_, folder) = try ingestHome() + let tv = ProseListTextView() + tv.string = "Body.\n" + tv.ingestFolder = folder + #expect(try !tv.ingestDrop([imageSource("photo.heic")])) + #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path)) + // A draft (no folder) refuses with the same honesty. + let draft = ProseListTextView() + draft.ingestFolder = nil + #expect(try !draft.ingestDrop([imageSource("x.png")])) + } + + // MARK: - #141 finish-audit pins + + @Test func `a dropped symlink refuses with nothing planted`() throws { + // copyItem would land the LINK itself (empirically verified, + // 2026-11-02) — the #34 rail then refuses the whole send. + let (_, folder) = try ingestHome() + let target = try imageSource("real image.png") + let linkURL = target.deletingLastPathComponent() + .appendingPathComponent("linked image.png") + try? FileManager.default.removeItem(at: linkURL) + try FileManager.default.createSymbolicLink(at: linkURL, withDestinationURL: target) + defer { try? FileManager.default.removeItem(at: linkURL) } + + #expect(throws: IngestError.self) { + _ = try PostStore.ingestImage(from: linkURL, pieceFolder: folder) + } + #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path)) + } + + @Test func `a mixed image and markdown set refuses loudly`() throws { + // The window destination forwards only PURE-markdown sets (#91); + // a mixed set must reach this refusal, not vanish behind the md. + let (_, folder) = try ingestHome() + let tv = ProseListTextView() + tv.string = "Body.\n" + tv.ingestFolder = folder + let md = FileManager.default.temporaryDirectory + .appendingPathComponent("mixed-\(UUID().uuidString).md") + try Data("# Guest\n".utf8).write(to: md) + defer { try? FileManager.default.removeItem(at: md) } + + #expect(try !tv.ingestDrop([imageSource("ink sketch.png"), md])) + #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path)) + #expect(tv.string == "Body.\n", "mixed set must not insert: \(tv.string)") + } + + // MARK: - #141 drop-point solve (pure) + + /// Viewport band [200, 800]; characters 2000…6000 laid out with y + /// decreasing 800→400; everything off-screen reports 0 (the lie + /// non-contiguous layout tells). MidY at i = 800 − 0.1·(i − 2000). + private func bandedRectY(_ i: Int) -> CGFloat { + guard i >= 2000, i <= 6000 else { return 0 } + return CGFloat(800.0 - 0.1 * Double(i - 2000)) + } + + @Test func `dropIndex lands on the drop line`() { + // y crosses 600 between 4000 (== 600, at-or-above) and 4001. + let index = ProseListTextView.dropIndex( + length: 10000, targetY: 600, bandMinY: 200, bandMaxY: 800, + sampleCount: 100, rectY: bandedRectY, + ) + #expect(index == 4001) + } + + @Test func `dropIndex above the viewport clamps to the first visible char`() { + // Pointer above every in-band sample — the old code trusted a + // zero-initialized "above" and landed at the document start. + // (sampleCount 100 → samples land on 2000/4000/6000 exactly.) + let index = ProseListTextView.dropIndex( + length: 10000, targetY: 900, bandMinY: 200, bandMaxY: 800, + sampleCount: 100, rectY: bandedRectY, + ) + #expect(index == 2000) + } + + @Test func `dropIndex below the viewport clamps into the band tail`() { + let index = ProseListTextView.dropIndex( + length: 10000, targetY: 100, bandMinY: 200, bandMaxY: 800, + sampleCount: 100, rectY: bandedRectY, + ) + #expect(index == 6000) + } + + @Test func `dropIndex with no in-band rects falls to the document start`() { + // Viewless/garbage geometry (tests, or a hostile layout) — the + // honest floor. + let index = ProseListTextView.dropIndex( + length: 10000, targetY: 500, bandMinY: 200, bandMaxY: 800, + ) { _ in 0 } + #expect(index == 0) + } +} diff --git a/docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md b/docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md new file mode 100644 index 0000000..465731b --- /dev/null +++ b/docs/devlog/20261102-issue141-image-drop-illustration-ingest_log.md @@ -0,0 +1,78 @@ +# #141 — Drop an image onto the prose editor: illustration ingest + +> **Date:** 2026-11-02 +> **Type:** issue +> **Reference:** Gitea issue #141 (museion) + +## Goal + +Drag an image file onto a saved post's prose editor → the file is **copied** (never moved) into the piece's `assets/` under a parser-clean slugged name, and `![alt](assets/.)` is inserted at the drop point with `alt` selected for type-over. Type gate = exactly #34's publishable set (PNG/JPEG/GIF/WebP/SVG via `Micropub.mimeType`); drafts/outlines/guest refuse loudly; markdown drops keep #91's open-as-guest behavior. Followed by a full finish-audit pass (three fresh-context reviewers) with all accepted findings fixed and flip-verified. + +## What Was Done + +- `PostStore.swift` — `IngestError` (LocalizedError: `notPublishable` / `isFolder` / `isLink` / `hostileAssets`), `illustrationRef(_:)` (the one `![alt](…)` builder), `ingestImage(from:pieceFolder:)`: extension+mimeType gate → plain-file gate (folder AND symlink refuse — `copyItem` copies the link itself) → `hostileAssets` destination gate → slug + `FixCardStore.uniqueFile` collision (`-2`/`-3`) → copy → returns the ref destination. +- `ProseListTextView.swift` — `ingestFolder`, `ingestDrop(_:)` (gates → copy each → one `shouldChangeText` insert → select `alt` → `syncTypewriterInset` → `scrollRangeToVisible`), `dropIndex(...)` — the drop-point solve extracted as a `nonisolated static` pure function, `showIngestNotice` transient rust strip (auto-hide ~4 s). +- `WorkspaceView.swift` — the window-level `.dropDestination` is the sole routing surface: PURE-markdown sets (`allSatisfy`) open as guest, everything else bridges to `ingestDrop`. +- `MuseionApp.swift` / `PostEditorView.swift` — app-scoped `ProseDropBridge` (weak live text-view handle) on `AppGateState.proseDrop`, pointed at the live view by `ProseTextView` make/updateNSView; non-optional at both constructor call sites. +- `MuseionTests/ImageIngestTests.swift` — 11 tests: slug/copy/rail-parse, `-2` collision, refusal matrix (HEIC/PDF/folder-with-png-ext), `ingestDrop` insert+alt-select, loud refusal, symlink source, mixed md+image set, and 4 windowless `dropIndex` pins (banded synthetic rectY). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Window-level `.dropDestination` as the only drag surface | Field-verified: it starves EVERY deeper destination — NSTextView's `NSDraggingDestination` overrides and a nested editor-level SwiftUI destination both never fire. One window target routes both markdown and images. | +| Drop point from `NSEvent.mouseLocation`, not the closure's `location` | The SwiftUI closure's location proved unusable under this hosting (every conversion chain mis-mapped by ~⅓ document). The live pointer during perform IS the drop point. | +| Viewport-banded sample→bracket→binary-search over `firstRect` | #115 extension: `firstRect(forCharacterRange:)` is the only geometry source that answers under SwiftUI hosting; its y is bottom-up screen coords like the mouse (no flip); non-contiguous layout makes off-screen chars return garbage rects, so only in-viewport-band rects are trusted (plain NSView geometry). Pointer above band → first visible char; below → band tail; no evidence → 0. | +| Whitespace-gap slide after landing | Line-grain y-only mapping can land inside a word or an existing ref token; slide to the next gap (a drop ON a ref appends after it). | +| `syncTypewriterInset` after the insert | Dogfood: without it the typewriter inset is stale and the editor freezes scrolling until the next keypress — leave the scroll stack as a keystroke would. | +| Symlink source refuses (`isLink`) | Finish-audit (empirically verified): `copyItem` lands the LINK itself; the #34 rail then refuses the whole publish (all-or-nothing) — a publish DoS plus a latent exfil if the rail ever loosens. | +| PURE-markdown routing (`allSatisfy`) | Finish-audit: `first(where:)` silently dropped images in mixed md+image drags behind the opened guest. Mixed sets now hit the loud refusal. | +| Collisions via `FixCardStore.uniqueFile` | House helper with identical `-2` semantics (finish-audit ponytail finding); deleted the bespoke loop. | +| `dropIndex` extracted pure | Makes the geometry solve testable without a window — the HIGH finish-audit finding (silent index-0 landing) lived exactly in the untestable part. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Image drops did nothing (green copy badge, silent refusal) | Window-level SwiftUI `.dropDestination` starves all deeper drag destinations — nested SwiftUI targets never fire, AppKit `NSDraggingDestination` never fires | Route everything through the window destination; bridge to the live text view via app-scoped `ProseDropBridge` | +| Ref landed at start/end/one-paragraph-off through every conversion chain | SwiftUI closure location + `characterIndex(for:)` mis-map under SwiftUI hosting (#115 family) | Read `NSEvent.mouseLocation`, map via `firstRect` rects (bottom-up screen coords — NO flip) | +| Ref landed at the layout boundary / document start | Non-contiguous layout: off-screen characters return zero/stale rects; whole-doc binary search converged on garbage; `lastAbove=0` trusted without in-band evidence | Viewport-band filter (sample→bracket→search) + in-band-evidence guards + pure-function extraction with tests | +| Ref spliced INSIDE an existing `![alt](…)` token | Line-grain insert + links carry no whitespace | Whitespace-gap slide | +| Editor jumped and scrolling froze until next keypress | Insert left the typewriter inset stale; next keystroke's `syncTypewriterInset` healed it | Call `syncTypewriterInset` right after the edit | +| Mixed md+image drags silently dropped the images | `urls.first(where: isMarkdown)` forwarded any set containing an md | `allSatisfy` gate; mixed falls through to the loud refusal | +| `CharacterSet.characterIsMember` suggested by a reviewer | Not bridged to Swift — compile error this session | Keep the `Unicode.Scalar` membership helper | +| `log stream`/`log show` unreliable for the app's NSLog | — | Capture stderr directly: run the binary with `> scratch/museion-stderr*.log 2>&1` | +| xcresult summary read fails with "doesn't exist" | Reading the bundle while xcodebuild finalizes it (#33, known) | Read only after the process exits | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostStore.swift` | `IngestError`, `illustrationRef`, `ingestImage` (symlink/folder/mime gates, uniqueFile collision) | +| `Museion/ProseListTextView.swift` | `ingestFolder`, pure `dropIndex`, `ingestDrop`, `showIngestNotice` | +| `Museion/WorkspaceView.swift` | Window destination routing: pure-markdown → guest, else → ingestDrop | +| `Museion/MuseionApp.swift` | `AppGateState.proseDrop` app-scoped bridge | +| `Museion/PostEditorView.swift` | `ProseDropBridge` class + non-optional `dropBridge` plumbing | +| `MuseionTests/ImageIngestTests.swift` | New: 11 tests incl. finish-audit pins (all flip-verified batched) | +| `Museion/AGENTS.md` | #141 contracts rewritten to final architecture (routing, gates, drop-point solve, audit pins) | +| `MuseionTests/AGENTS.md` | ImageIngestTests description incl. finish-audit pins | +| `AGENTS.md` | Session-log window refresh | + +## Verification + +- Full suite **557/557** (551 baseline + 6 new), xcresult executed-count verified, idle machine +- Flip cycle: all 3 new guards flipped off in one batch — each pin failed on its own guard; restored, green +- swiftformat clean; swiftlint zero new violations (PostEditorView's 6 warnings byte-identical at HEAD) +- Dogfood: drop lands within one line of the pointer; scrolling stays live +- GitNexus detect-changes (high — index-relative; the diff-scope review covered the real blast radius) + analyze refreshed + +## Open Items & Next Steps + +- [ ] Drop placement is line-grain (no x-axis refinement within the line) — v2 knob if it bothers +- [ ] Deferred finish-audit LOWs: dangling-symlink name squat, main-actor copy size cap, `isFolder` message catch-all (vanished/web URLs), `assets/` vs `Assets/` case split-brain +- [ ] The window destination's pure-markdown routing is unpinned (no SwiftUI drop harness) — ingest-side gate is pinned +- [ ] User's scratch: `prompt-order-probe` test post still carries the spliced line-9 refs from the buggy round + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index d393ed0..b9a8273 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 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 | | 2026-10-31 | issue | [20261031-issue32-m4-trend-view-s5-2_log.md](20261031-issue32-m4-trend-view-s5-2_log.md) | #32 trend view: four metric charts over first-draft captures, read-back origin/type gate + finite parse; audit fixed nan/inf crash — 508 tests |