feat(publish): illustrations travel inline (#34)
CI / ci (push) Canceled after 0s

A piece's assets/ ink-sketch images publish with it: Send as Draft
first uploads every referenced image to Micro.blog's media endpoint
(q=config discovery, one multipart file POST per FILE — duplicate
refs share an upload), then each ![alt](assets/…) ref REWRITES IN
PLACE with its uploaded URL in the wire content. The image renders
exactly where the writer placed it and the alt rides the markdown;
the piece on disk never changes.

The first shape attached uploads as a Micropub photo property with
mp-photo-alt — live dogfood (2026-11-01) showed the theme renders
properties at the bottom of the post, losing position. No property
ships at all now; inline refs are the only transport, which also
makes the parsed body ref the only way an image ships — the alt
floor at the illustration rail is therefore the only gate a photo
needs (G12: a whitespace-empty alt refuses naming the file before
anything touches the wire; the mentor is never consulted).

Pre-flight gates every payload: the endpoint's exact formats
(PNG/JPEG/GIF/WebP/SVG), 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](<url>) — a plain-paren
destination would close at the first ) and smuggle a live link into
the published post; the frontmatter trust gate does not cover
markdown's grammar.

Finish-audit (three reviewers) drove the angle form, the symlink
containment, the per-file upload dedup, and four pins; all four
behavior guards flip-verified in one batch cycle. Suite 546 passed /
0 failed; swiftformat + swiftlint clean. Ingest UX (drop image onto
the editor) is #141, blocked by this issue.
This commit is contained in:
AlexKucera committed 2026-11-01 21:52:58 +01:00
1 parent 414f1392ef
commit 695ec27e11
10 files changed
+840 -19

No files matched your search

+2 -2
View File
@@ -30,8 +30,8 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
- `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue.
- `Micropub.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubPublishSheet.swift`** — the G9 ask-before surface owning both steps: Send as Draft → (review via the preview link) → Publish, each its own explicit click; refusals inline orange with buttons kept (ApplyAskSheet posture); the token field appears when none is saved or after an auth failure (re-entry replaces — never a dead end), a fresh entry is saved ONCE to the Keychain; `Send Again` re-drafts (the piece changed post-draft) and overwrites the remembered URL; `.onAppear` seeds from the piece's `micropubURL` so a draft from an earlier session still publishes.
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePosLine truncated
- `Micropub.swift` + `MicropubMedia.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) + #34 (S6.2) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped, except #34's asset illustration refs which REWRITE to their uploaded URLs on the WIRE — position and alt stay the writer's; the piece on disk never changes], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; #34: uploaded illustrations ride INLINE inside `content` — the rail rewrites each asset ref to its uploaded URL exactly where it stands; NO `photo` property (a property renders wherever the theme decides — live-verified 2026-11-01: bottom of the post, position lost)); `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable; `decodeFailure` is internal (the one failure decode — MicropubMedia's media steps share it rather than fork it) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubMedia.swift`** — #34 (S6.2, G12) illustrations travel with it (a `nonisolated extension Micropub`): `illustrations(in:)` parses the body's `![alt](assets/…)` refs — the ONLY images Museion uploads (remote http(s) refs ride as prose; ceiling (ponytail): plain paren form, no fence scan, no space-bearing destinations); `rewritingIllustrations(_:uploaded:)` builds the wire content (each UPLOADED ref swaps exactly where it stands — position and alt are the writer's, a quoted title drops, foreign images and unuploaded refs ride byte-identical, and a URL carrying markdown-active characters (`)`/`(`/`<>`/space) rides the ANGLE form `![alt](<url>)` — a plain-paren dest would close at the first `)` and smuggle a live attacker link; trustworthyURL was built for line-bounded frontmatter, not this sink — parse and rewrite share ONE regex (a `let`) so they can never drift); `mimeType(forDestination:)` = exactly the endpoint's formats (png/jpg/jpeg/gif/webp/svg — anything else refuses, no guessed content type ships); `mediaEndpoint(token:transport:)` = `GET ?q=config` decode of `media-endpoint` behind the trustworthyURL gate (the writer's PNG and token POST to the discovered endpoint); `makeMediaUploadRequest`/`uploadMedia` = the multipart `file` POST (boundary per request; the filename is sanitized — a quote/control char can't break the Content-Disposition) decoding exactly like the create (Location → body `url` → trust gate → requestFailed; 401/403 → authFailed); `Illustration`/`MediaResult` are the shared shapes (`Photo` died with the property path); the alt group in the shared regex is SINGLE-LINE by design — a ref whose alt spans lines doesn't parse at all (rides as prose, never uploads, never rewrites — a parsed-but-unrewritten ref would ship a broken relative link). The publish FLOOR lives in ONE gate (#6: where all callers route — a parsed body ref is the ONLY way an image ships, and every send routes through it): the model rail — `uploadIllustrations` (private PostsModel helper beside `micropubSendDraft` in Micropub.swift) — refuses BEFORE any wire traffic (the refusal names the destination — the parse itself never hides a ref), pre-flights every payload read and CONTAINS it in the piece — a `../` ref OR a symlinked asset refuses (`resolvingSymlinksInPath` both sides, the cards/learnings posture; the payload list is one entry per FILE — duplicate refs share it and upload once) — before the first upload, uploads are all-or-nothing (a failed upload never sends a half-illustrated piece), and the engine is consulted for nothing — style judgment stays with the author (G12). ponytail: a re-send re-uploadsLine truncated
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePosLine truncated
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
- `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).
+106 -5
View File
@@ -8,6 +8,10 @@
// auth — no OAuth in v1; the token lives in the Keychain, entered
// once. Frontmatter `category:` is permitted but inert (v1 never
// sends it — the request carries name + content only).
// #34 (S6.2): uploaded illustrations rewrite their asset refs IN
// PLACE with the uploaded URLs (position is the writer's) — the
// media surface (parse/upload/config/rewrite) lives in
// MicropubMedia.swift, the orchestration in micropubSendDraft below.
//
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the
@@ -56,14 +60,19 @@ nonisolated enum Micropub {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
// h=entry with markdown content and name for the title; the
// Title publishes as the entry's name, the body ships verbatim
// (GLOSSARY: never stripped). category: never sent in v1.
// (GLOSSARY: never stripped) — the one carve-out is #34's asset
// illustration refs, which REWRITE to their uploaded URLs on
// the WIRE (position and alt are the writer's; the piece on
// disk never changes). No photo property: it would render
// wherever the theme decides, not where placed (2026-11-01).
// category: never sent in v1.
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
],
] as [String: Any],
], options: [.sortedKeys])
return request
}
@@ -85,7 +94,8 @@ nonisolated enum Micropub {
// MARK: The two steps
/// Step 1: send the piece as a draft. The piece's Title is the
/// entry's name; the markdown body is the content.
/// entry's name; the markdown body is the content; #34's uploaded
/// illustrations already rewrote their refs in the body.
static func sendDraft(
title: String,
body: String,
@@ -156,7 +166,9 @@ nonisolated enum Micropub {
return true
}
private static func decodeFailure(status: Int, body: Data) -> Outcome {
/// Internal for MicropubMedia's media steps (#34) — the one failure
/// decode this client speaks; extensions share it rather than fork it.
static func decodeFailure(status: Int, body: Data) -> Outcome {
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
let detail = (root["error_description"] as? String) ?? (root["error"] as? String) ?? "HTTP \(status)"
if status == 401 || status == 403 {
@@ -263,9 +275,21 @@ extension PostsModel {
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return .refused("This piece has no text to send.")
}
// #34 (S6.2): illustrations travel with it (the rail below
// owns the floor, the uploads, and the REWRITTEN wire body —
// G12: the mentor is never consulted about images).
var wireBody = body
if !Micropub.illustrations(in: body).isEmpty {
switch await uploadIllustrations(dir: dir, body: body, token: token, transport: transport) {
case let .ready(rewritten):
wireBody = rewritten
case let .blocked(outcome):
return outcome
}
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
body: body,
body: wireBody,
token: token,
transport: transport,
)
@@ -280,4 +304,81 @@ extension PostsModel {
}
return outcome
}
/// #34 (S6.2): the illustration rail of `micropubSendDraft`. The
/// FLOOR first (G12): a photo without alt text never ships, and
/// nothing touches the wire until every illustration clears it —
/// the ONLY gate (the only way an image ships is a parsed body ref,
/// and every send routes through here). Then one upload per PNG
/// (q=config → multipart → Location) and `ready`'s body is the
/// wire content with each ref REWRITTEN to its uploaded URL — the
/// image renders exactly where the writer placed it, alt travels
/// in the markdown (the piece on disk never changes). Style
/// judgment stays with the author.
private enum IllustrationRail {
case ready(String) // the rewritten wire body
case blocked(Micropub.Outcome)
}
private func uploadIllustrations(
dir: URL,
body: String,
token: String,
transport: Micropub.Transport,
) async -> IllustrationRail {
let illustrations = Micropub.illustrations(in: body)
if let bare = illustrations.first(where: { $0.alt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) {
return .blocked(.refused("\(bare.destination) has no alt text — a photo never ships without it."))
}
// Pre-flight: every file in hand (and inside this piece — a
// `../` ref or a symlinked asset is out of shape) before the
// first upload. One payload per FILE: duplicate refs to one
// destination upload once and share the URL.
struct Payload {
let destination: String
let mimeType: String
let data: Data
}
let root = dir.resolvingSymlinksInPath().path + "/"
var payloads: [Payload] = []
for illustration in illustrations where !payloads.contains(where: { $0.destination == illustration.destination }) {
guard let mimeType = Micropub.mimeType(forDestination: illustration.destination) else {
return .blocked(.refused("\(illustration.destination) is not a PNG/JPEG/GIF/WebP/SVG — Micro.blog can't host it."))
}
let fileURL = dir.appendingPathComponent(illustration.destination)
guard fileURL.resolvingSymlinksInPath().path.hasPrefix(root),
let data = try? Data(contentsOf: fileURL)
else {
return .blocked(.refused("Couldn't read \(illustration.destination) from this piece's assets."))
}
payloads.append(Payload(destination: illustration.destination, mimeType: mimeType, data: data))
}
// ponytail: a re-send re-uploads (Micro.blog keeps both
// copies) — dedup via q=source listing is v2's call.
let mediaEndpoint: String
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named):
mediaEndpoint = named
case let .failed(outcome):
return .blocked(outcome)
}
var uploaded: [String: String] = [:]
for payload in payloads {
let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
mimeType: payload.mimeType,
data: payload.data,
token: token,
transport: transport,
)
switch outcome {
case let .url(url):
uploaded[payload.destination] = url
case let .failed(failure):
return .blocked(failure) // all-or-nothing: a failed upload never sends a half-illustrated piece
}
}
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploaded))
}
}
+207
View File
@@ -0,0 +1,207 @@
//
// MicropubMedia.swift
// Museion
//
// #34 (S6.2): illustrations travel with it. Ink-sketch PNGs in the
// piece's assets/ upload and travel INLINE: q=config names the media
// endpoint, the PNG rides a multipart POST, and each `assets/` ref
// REWRITES in place with its uploaded URL — the image renders exactly
// where the writer placed it, alt travels in the markdown (a photo
// PROPERTY would render wherever the theme decides — live-verified
// 2026-11-01: bottom of the post, position lost). The FLOOR (G12):
// no photo ships without alt text — the only gate; style judgment
// stays with the author and the mentor NEVER assesses images
// (nothing here consults the engine).
//
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `GET /micropub?q=config` carries `media-endpoint`;
// `POST <media-endpoint>` multipart → 202 + Location = upload URL.
//
import Foundation
nonisolated extension Micropub {
/// One illustration ref in the body: `![alt](assets/…)`.
struct Illustration: Equatable {
/// Verbatim bracket text — the parse never hides a ref; the
/// floor (trimmed emptiness) is the model's call.
let alt: String
/// The ref's destination as written, always `assets/`-rooted.
let destination: String
}
/// A media-step result: the URL (the config-named endpoint, or an
/// upload's Location) or the failure outcome to surface as-is.
enum MediaResult: Equatable {
case url(String)
case failed(Outcome)
}
// MARK: Parsing the body (G12: plain image refs into assets/)
/// Every `assets/` image ref in the body — the only images Museion
/// uploads. Remote http(s) refs ride as prose (not ours to upload),
/// and refs rooted elsewhere stay put. Ceiling (ponytail): the
/// plain paren form; a destination containing spaces (the
/// `<(assets/my ink.png)>` form) doesn't match and rides verbatim —
/// never uploaded, never gated. No fence scan either: an
/// illustration ref inside a code fence is not corpus reality.
static func illustrations(in body: String) -> [Illustration] {
guard let regex = illustrationRegex else { return [] }
let scanner = body as NSString
return regex.matches(in: body, range: NSRange(location: 0, length: scanner.length)).map { match in
Illustration(
alt: scanner.substring(with: match.range(at: 1)),
destination: scanner.substring(with: match.range(at: 2)),
)
}
}
/// The wire content: the body with each uploaded illustration ref
/// REWRITTEN in place with its uploaded URL — position is the
/// writer's, so the image renders exactly where placed and the alt
/// travels in the markdown. A ref with no upload in the map (and
/// every untouched line) rides byte-identical. The piece on disk
/// is never modified.
static func rewritingIllustrations(_ body: String, uploaded: [String: String]) -> String {
guard let regex = illustrationRegex else { return body }
let scanner = body as NSString
let matches = regex.matches(in: body, range: NSRange(location: 0, length: scanner.length))
var result = ""
var cursor = 0
for match in matches {
guard let url = uploaded[scanner.substring(with: match.range(at: 2))] else { continue }
result += scanner.substring(with: NSRange(location: cursor, length: match.range.location - cursor))
// Alt rides verbatim from the match; a quoted title drops
// (it never parsed into the Illustration either). The
// destination rides the ANGLE form when the URL carries
// markdown-active characters — a plain-paren dest would
// close at the first `)` and smuggle a live attacker link
// into the published post (the trustworthyURL gate was
// built for line-bounded frontmatter, not this sink).
let active = url.rangeOfCharacter(from: CharacterSet(charactersIn: "()<> \t")) != nil
let dest = active ? "<\(url)>" : url
result += "![\(scanner.substring(with: match.range(at: 1)))](\(dest))"
cursor = match.range.location + match.range.length
}
guard cursor > 0 else { return body } // nothing rewritten
return result + scanner.substring(from: cursor)
}
/// The upload's content type — exactly the formats Micro.blog's
/// media endpoint accepts. Anything else refuses honestly; no
/// guessed content type ever ships.
static func mimeType(forDestination destination: String) -> String? {
switch URL(fileURLWithPath: destination).pathExtension.lowercased() {
case "png": "image/png"
case "jpg", "jpeg": "image/jpeg"
case "gif": "image/gif"
case "webp": "image/webp"
case "svg": "image/svg+xml"
default: nil
}
}
// MARK: q=config (hop 1)
static func makeConfigRequest(token: String) -> URLRequest {
var components = URLComponents(url: endpoint, resolvingAgainstBaseURL: false)!
components.queryItems = [URLQueryItem(name: "q", value: "config")]
var request = URLRequest(url: components.url!)
request.timeoutInterval = 30
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
return request
}
/// Ask the endpoint where media goes. The discovered endpoint is
/// trust-boundary data — the writer's PNG and token POST to it —
/// so it passes the same format gate as the draft URL.
static func mediaEndpoint(token: String, transport: Transport = urlSessionTransport) async -> MediaResult {
do {
let (data, response) = try await transport(makeConfigRequest(token: token))
guard (200 ..< 300).contains(response.statusCode) else {
return .failed(decodeFailure(status: response.statusCode, body: data))
}
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
guard let raw = root["media-endpoint"] as? String, trustworthyURL(raw) else {
return .failed(.requestFailed(status: response.statusCode, detail: "no trustworthy media endpoint in q=config"))
}
return .url(raw)
} catch {
return .failed(.unreachable(error.localizedDescription))
}
}
// MARK: The multipart upload (hop 2)
static func makeMediaUploadRequest(
mediaEndpoint: String,
filename: String,
mimeType: String,
data: Data,
token: String,
) -> URLRequest {
let boundary = "museion-\(UUID().uuidString)"
// The filename rides a Content-Disposition header — quotes and
// control characters can never break out of it.
let safeFilename = filename.filter { $0 != "\"" && !$0.isNewline && !($0.asciiValue.map { $0 < 0x20 } ?? false) }
var request = URLRequest(url: URL(string: mediaEndpoint)!)
request.httpMethod = "POST"
request.timeoutInterval = 60
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
var body = Data()
body.append(Data("--\(boundary)\r\n".utf8))
body.append(Data("Content-Disposition: form-data; name=\"file\"; filename=\"\(safeFilename)\"\r\n".utf8))
body.append(Data("Content-Type: \(mimeType)\r\n\r\n".utf8))
body.append(data)
body.append(Data("\r\n--\(boundary)--\r\n".utf8))
request.httpBody = body
return request
}
/// Upload one file to the media endpoint. The decode mirrors the
/// create's: Location header first, body `url` second, every URL
/// trust-gated — a 2xx with no trustworthy URL is a failure, never
/// a silent success.
static func uploadMedia(
mediaEndpoint: String,
filename: String,
mimeType: String,
data: Data,
token: String,
transport: Transport = urlSessionTransport,
) async -> MediaResult {
do {
let (body, response) = try await transport(makeMediaUploadRequest(
mediaEndpoint: mediaEndpoint,
filename: filename,
mimeType: mimeType,
data: data,
token: token,
))
guard (200 ..< 300).contains(response.statusCode) else {
return .failed(decodeFailure(status: response.statusCode, body: body))
}
let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]
let url = response.value(forHTTPHeaderField: "Location") ?? root["url"] as? String
guard let url, trustworthyURL(url) else {
return .failed(.requestFailed(status: response.statusCode, detail: "no trustworthy upload URL in the response"))
}
return .url(url)
} catch {
return .failed(.unreachable(error.localizedDescription))
}
}
/// The one illustration-ref pattern both passes share (the parse
/// and the rewrite can never drift). The alt class is single-line
/// (`[^\]\n]*`) on purpose: a ref whose alt spans lines must NOT
/// parse — it rides as prose, never uploaded, never rewritten (a
/// parsed-but-unrewritten ref would ship a broken relative link).
/// A `let` — the pattern is compile-constant; compiling it per
/// access was the only cost.
private static let illustrationRegex = try? NSRegularExpression(
pattern: #"!\[([^\]\n]*)\]\((assets/[^\s)]+)(?:\s+"[^"]*")?\)"#,
)
}