diff --git a/AGENTS.md b/AGENTS.md index 75ac59d..6983d78 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** (5542 symbols, 22245 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** (5626 symbols, 22797 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). @@ -193,14 +193,14 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| -| 2026-10-31 | [20261031-issue33-m6-micropub-draft-publish-s6-1_log.md](20261031-issue33-m6-micropub-draft-publish-s6-1_log.md) | -| 2026-10-31 | [20261031-issue32-m4-trend-view-s5-2_log.md](20261031-issue32-m4-trend-view-s5-2_log.md) | -| 2026-10-30 | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | -| 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | -| 2026-10-30 | [20261030-issue1-verify-style-constraints-prompt-end_log.md](20261030-issue1-verify-style-constraints-prompt-end_log.md) | -| 2026-10-28 | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](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](20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | -| 2026-10-27 | [20261027-issue135-profiles-s2-settings-page-ui_log.md](20261027-issue135-profiles-s2-settings-page-ui_log.md) | -| 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | -| 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_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) | +| 2026-10-30 | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](docs/devlog/20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | +| 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](docs/devlog/20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | +| 2026-10-30 | [20261030-issue1-verify-style-constraints-prompt-end_log.md](docs/devlog/20261030-issue1-verify-style-constraints-prompt-end_log.md) | +| 2026-10-28 | [20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md](docs/devlog/20261028-issue137-profiles-s4-engine-lifecycle-model-switch-ux_log.md) | +| 2026-10-27 | [20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md](docs/devlog/20261027-issue136-profiles-s3-settings-write-path-test-connection_log.md) | +| 2026-10-27 | [20261027-issue135-profiles-s2-settings-page-ui_log.md](docs/devlog/20261027-issue135-profiles-s2-settings-page-ui_log.md) | +| 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 afe50ae..32abd1f 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 +- **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 82b020b..49d1bbb 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -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 `/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`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#6 (S3.4): `DeslopLint.emit(body:pieceID:pieceURL:kind:home:)` — the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitter `lint` fix cards in `/cards/` (see `DeslopLint.swift`)** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#122 Blind Read:** `blindRead(home:mentor:)` (file-scope extension) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). **#33 (S6.1):** `micropubSendDraft(home:token:transport:)` (same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (`Post.title` = the entry's name, `splitFrontmatter` body = the content; no scan dependency), `Micropub.sendDraft` over the injected Transport, and a successful draft stamps the piece's `micropub_url` (`try?` — the draft already landed; a stamp failure only costs the cross-reopen memory). +- `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]()` — 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-uploads (Micro.blog keeps both copies; dedup via `q=source` is v2's call). **`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`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#6 (S3.4): `DeslopLint.emit(body:pieceID:pieceURL:kind:home:)` — the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitter `lint` fix cards in `/cards/` (see `DeslopLint.swift`)** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#122 Blind Read:** `blindRead(home:mentor:)` (file-scope extension) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). **#33 (S6.1):** `micropubSendDraft(home:token:transport:)` (same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (`Post.title` = the entry's name, `splitFrontmatter` body = the content; no scan dependency), `Micropub.sendDraft` over the injected Transport, and a successful draft stamps the piece's `micropub_url` (`try?` — the draft already landed; a stamp failure only costs the cross-reopen memory). **#34 (S6.2):** the send first routes through the private `uploadIllustrations` rail (same file) whenever the body carries asset illustration refs — floor + pre-flight + `q=config` + one upload per PNG — then hands `Micropub.sendDraft` the wire body with every uploaded ref REWRITTEN to its URL in place (position preserved, no photo property); a piece WITHOUT illustrations keeps the exact #33 single-request wire (pinned). - `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). diff --git a/Museion/Micropub.swift b/Museion/Micropub.swift index 6bb1024..e974e63 100644 --- a/Museion/Micropub.swift +++ b/Museion/Micropub.swift @@ -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)) + } } diff --git a/Museion/MicropubMedia.swift b/Museion/MicropubMedia.swift new file mode 100644 index 0000000..7157885 --- /dev/null +++ b/Museion/MicropubMedia.swift @@ -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 ` 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+"[^"]*")?\)"#, + ) +} diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index e4ca23a..57ef75e 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -23,7 +23,7 @@ Owned by the root AGENTS.md contract. - `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects///` + `archive///` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. - `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects///` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects///post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`. - `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts. -- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). +- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). **#34 (S6.2):** `MicropubMediaTests.swift` (own file — `micropubPNG()`/`micropubMediaScripted` helpers internal, the scripted transport routes config → upload → create by target URL) pins the media surface: illustration parse (plain + inline + quoted-title + empty-alt refs captured honestly; remote http(s) and non-`assets/` refs left alone), rewrite (each UPLOADED ref swaps in place with its uploaded URL — position and alt preserved, quoted titles drop, foreign images and unuploaded refs byte-identical, a URL carrying markdown-active chars rides the ANGLE form `![alt]()` — a plain dest would close early and smuggle a live link), the mime matrix (all six formats + the refusal), the config request + `media-endpoint` decode (trust-gated — an injection-carrying endpoint is requestFailed), the multipart `file` POST asserted over BYTES (part head, payload, closing delimiter, per-request boundary), `uploadMedia`'s create-mirroring decode (Location → body url → trust gate; authFailed on 403), the no-photo-keys-EVER create pin (images travel inline in content — a photo property renders wherever the theme decides, live-verified 2026-11-01), the boundary pin (empty map passes through verbatim, adjacent start/end refs rewrite with clean cursor math), and the multi-line-alt agreement pin (a ref whose alt spans lines doesn't parse at all — a parsed-but-unrewritten ref would ship a broken relative link); the #34 model pins live in `MicropubModelTests.swift` — the three-hop ORDER (q=config, multipart carrying the PNG bytes, create with the ref REWRITTEN to its uploaded URL exactly where placed while the disk body keeps the local ref — no photo property keys), the AC2 floor (WHITESPACE-empty alt — the #6 trimmed-emptiness class — refuses naming the destination with ZERO requests served, nothing stamped), missing-file + SYMLINKED-asset refusals pre-wire (containment resolves symlinks — never read through a planted link), DUPLICATE refs to one asset uploading once and sharing the URL, and a piece without illustrations sending exactly ONE request (#33's wire unchanged). - `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons). - `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses. - `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve). diff --git a/MuseionTests/MicropubMediaTests.swift b/MuseionTests/MicropubMediaTests.swift new file mode 100644 index 0000000..40058df --- /dev/null +++ b/MuseionTests/MicropubMediaTests.swift @@ -0,0 +1,295 @@ +// +// MicropubMediaTests.swift +// MuseionTests +// +// #34 (S6.2): illustrations travel with it. Scenario: +// +// Given a saved Post whose body references ink-sketch PNGs from its +// assets/ with alt text +// When the writer sends the piece as a draft and publishes +// Then each PNG uploads once via the media endpoint (q=config → +// multipart → 202 + Location) and its ref REWRITES IN PLACE with +// the uploaded URL — the image renders exactly where the writer +// placed it, alt travels in the markdown — and a photo without +// alt text never ships: the send refuses naming the illustration +// before anything touches the wire. +// The mentor never assesses images (G12) — the flow consults no +// engine anywhere. +// +// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub): +// `q=config` names the media endpoint; `POST /micropub/media` +// multipart → 202 + Location = the upload URL. No photo property: +// it renders wherever the THEME decides, not where placed +// (live-verified 2026-11-01 — bottom of the post, position lost). +// + +import Foundation +@testable import Museion +import Testing + +// MARK: Shared helpers (shared-helper convention) + +/// A tiny deterministic PNG payload — the client never inspects the +/// bytes (the server does); tests only need recognizable ones. +nonisolated func micropubPNG() -> Data { + Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x01, 0x02, 0x03]) +} + +/// A transport that routes the #34 three-step flow by target: +/// q=config → media upload → create. Records every request it served. +nonisolated func micropubMediaScripted(log: MicropubRequestLog) -> Micropub.Transport { + { request in + log.append(request) + let target = request.url?.absoluteString ?? "" + if target.contains("q=config") { + return (Data(#"{"media-endpoint":"https://micro.blog/micropub/media"}"#.utf8), micropubHTTP(200)) + } + if target.contains("/micropub/media") { + return (Data("{}".utf8), micropubHTTP(202, headers: ["Location": "https://micro.blog/uploads/2026/ink.png"])) + } + return (Data("{}".utf8), micropubHTTP(201, headers: ["Location": "https://example.micro.blog/inked"])) + } +} + +@Suite("MicropubMediaTests") +struct MicropubMediaTests { + // MARK: Parsing the body's illustration refs (G12: plain refs into assets/) + + @Test func `illustrations finds asset refs and leaves foreign images alone`() { + let body = """ + # Title + + Prose with ![an inline ref](assets/inline.png) inside. + + ![A winding path.](assets/path.png "The agora at dusk") + + ![remote](https://example.com/x.png) + + ![not ours](images/other.png) + + ![](assets/blank.png) + """ + let found = Micropub.illustrations(in: body) + // Honest parse: every assets/ ref, alt captured verbatim (the + // floor judges trimmed emptiness — the parse never hides one). + #expect(found == [ + .init(alt: "an inline ref", destination: "assets/inline.png"), + .init(alt: "A winding path.", destination: "assets/path.png"), + .init(alt: "", destination: "assets/blank.png"), + ]) + } + + @Test func `rewriting swaps each ref for its uploaded url in place`() { + let body = """ + # Title + + Prose with ![an inline ref](assets/inline.png) inside. + + ![A winding path.](assets/path.png "The agora at dusk") + + ![remote](https://example.com/x.png) + + ![not ours](images/other.png) + + ![no upload yet](assets/pending.png) + """ + let wire = Micropub.rewritingIllustrations(body, uploaded: [ + "assets/inline.png": "https://micro.blog/uploads/a.png", + "assets/path.png": "https://micro.blog/uploads/b.png", + ]) + // Position is the writer's: each ref rewrites exactly where it + // stands, alt + surrounding text verbatim; foreign images and + // refs without an upload stay put; a quoted title drops. + #expect(wire.contains("Prose with ![an inline ref](https://micro.blog/uploads/a.png) inside.")) + #expect(wire.contains("![A winding path.](https://micro.blog/uploads/b.png)")) + #expect(wire.contains("![remote](https://example.com/x.png)")) + #expect(wire.contains("![not ours](images/other.png)")) + #expect(wire.contains("![no upload yet](assets/pending.png)")) + #expect(wire.hasPrefix("# Title")) + // Only the uploaded refs' assets/ destinations leave. + #expect(!wire.contains("assets/inline.png")) + #expect(!wire.contains("assets/path.png")) + } + + @Test func `mime types cover the media endpoint's formats and refuse the rest`() { + #expect(Micropub.mimeType(forDestination: "assets/ink.png") == "image/png") + #expect(Micropub.mimeType(forDestination: "assets/ink.PNG") == "image/png") + #expect(Micropub.mimeType(forDestination: "assets/photo.jpeg") == "image/jpeg") + #expect(Micropub.mimeType(forDestination: "assets/anim.gif") == "image/gif") + #expect(Micropub.mimeType(forDestination: "assets/modern.webp") == "image/webp") + #expect(Micropub.mimeType(forDestination: "assets/vector.svg") == "image/svg+xml") + #expect(Micropub.mimeType(forDestination: "assets/note.md") == nil) + } + + @Test func `a url carrying markdown-active characters rides the angle form`() { + // The uploaded URL is server-controlled data landing in the + // wire body as markdown — a `)` in a plain-paren destination + // would close the image early and smuggle a live attacker + // link into the post (the trustworthyURL gate was built for + // frontmatter, not this sink). Angle form caps the worst + // case at broken rendering. + let wire = Micropub.rewritingIllustrations( + "![alt](assets/a.png)", + uploaded: ["assets/a.png": "https://x.example/x)[evil](https://evil.example"], + ) + #expect(wire == "![alt]()") + // A clean URL keeps the plain form (pinned by the rewrite test). + } + + @Test func `rewriting passes through untouched bodies and handles boundary refs`() { + // Empty map (and all-matches-skipped — same guard) returns the + // body verbatim; adjacent refs at string start/end rewrite + // with clean cursor math. + let adjacent = "![a](assets/a.png)![b](assets/b.png)" + #expect(Micropub.rewritingIllustrations(adjacent, uploaded: [:]) == adjacent) + let one = Micropub.rewritingIllustrations(adjacent, uploaded: ["assets/a.png": "https://micro.blog/uploads/a.png"]) + #expect(one == "![a](https://micro.blog/uploads/a.png)![b](assets/b.png)") + } + + @Test func `a multi-line alt never parses so both passes agree`() { + // A ref whose alt spans lines must NOT parse — if it parsed but + // didn't rewrite, the local assets/ ref would ride the wire as + // a broken relative link. It rides as prose, never uploaded. + let body = "# Title\n\n![two\nlines](assets/path.png)\n\n![fine](assets/ok.png)" + #expect(Micropub.illustrations(in: body) == [.init(alt: "fine", destination: "assets/ok.png")]) + let wire = Micropub.rewritingIllustrations(body, uploaded: [ + "assets/path.png": "https://micro.blog/uploads/a.png", + "assets/ok.png": "https://micro.blog/uploads/b.png", + ]) + #expect(wire.contains("![two\nlines](assets/path.png)")) // untouched + #expect(wire.contains("![fine](https://micro.blog/uploads/b.png)")) // the well-formed ref still rewrites + } + + // MARK: q=config (hop 1) + + @Test func `config request asks the endpoint for its media endpoint`() { + let request = Micropub.makeConfigRequest(token: "tok") + let components = URLComponents(url: request.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false) + #expect(components?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true) + #expect(request.httpMethod == nil || request.httpMethod == "GET") // GET is the default + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok") + } + + @Test func `mediaEndpoint decodes the discovered endpoint and refuses honestly`() async { + let log = MicropubRequestLog() + // The named endpoint, trust-gated. + let named = await Micropub.mediaEndpoint( + token: "tok", + transport: micropubCanned(200, body: #"{"media-endpoint":"https://micro.blog/micropub/media"}"#, log: log), + ) + #expect(named == .url("https://micro.blog/micropub/media")) + + // A config that names nothing usable is a failed request, never + // a silent default. + let bare = await Micropub.mediaEndpoint(token: "tok", transport: micropubCanned(200, body: "{}", log: log)) + guard case .failed(.requestFailed) = bare else { + Issue.record("expected requestFailed, got \(bare)") + return + } + + // An injection-carrying endpoint is refused (the writer's PNG + // and token would POST to it) — the trustworthyURL gate. + let hostile = await Micropub.mediaEndpoint( + token: "tok", + transport: micropubCanned(200, body: "{\"media-endpoint\":\"https://x.example/a\\n---\\ninjected\"}", log: log), + ) + guard case .failed(.requestFailed) = hostile else { + Issue.record("expected requestFailed for the injected endpoint, got \(hostile)") + return + } + + let denied = await Micropub.mediaEndpoint( + token: "tok", + transport: micropubCanned(401, body: #"{"error_description":"bad token"}"#, log: log), + ) + guard case .failed(.authFailed) = denied else { + Issue.record("expected authFailed, got \(denied)") + return + } + } + + // MARK: The multipart upload (hop 2) + + @Test func `media upload request is a multipart file post to the discovered endpoint`() { + let request = Micropub.makeMediaUploadRequest( + mediaEndpoint: "https://micro.blog/micropub/media", + filename: "ink.png", + mimeType: "image/png", + data: micropubPNG(), + token: "tok", + ) + #expect(request.url?.absoluteString == "https://micro.blog/micropub/media") + #expect(request.httpMethod == "POST") + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok") + let contentType = request.value(forHTTPHeaderField: "Content-Type") ?? "" + #expect(contentType.hasPrefix("multipart/form-data; boundary=")) + let boundary = contentType.components(separatedBy: "boundary=").last ?? "" + + // The multipart shape, asserted over bytes: part head, payload, + // closing delimiter. + let body = request.httpBody ?? Data() + let head = Data(( + "--\(boundary)\r\n" + + "Content-Disposition: form-data; name=\"file\"; filename=\"ink.png\"\r\n" + + "Content-Type: image/png\r\n\r\n" + ).utf8) + #expect(body.firstRange(of: head) != nil) + #expect(body.firstRange(of: micropubPNG()) != nil) // the bytes ride intact + #expect(body.suffix(Data("--\(boundary)--\r\n".utf8).count) == Data("--\(boundary)--\r\n".utf8)) + } + + @Test func `uploadMedia reads Location then body url and gates the url`() async { + let log = MicropubRequestLog() + // Location wins; body url is the fallback. + let located = await Micropub.uploadMedia( + mediaEndpoint: "https://micro.blog/micropub/media", + filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok", + transport: micropubCanned( + 202, body: #"{"url":"https://ignored.example/should-not-win"}"#, + headers: ["Location": "https://micro.blog/uploads/ink.png"], log: log, + ), + ) + #expect(located == .url("https://micro.blog/uploads/ink.png")) + + let fallback = await Micropub.uploadMedia( + mediaEndpoint: "https://micro.blog/micropub/media", + filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok", + transport: micropubCanned(202, body: #"{"url":"https://micro.blog/uploads/from-body"}"#, log: log), + ) + #expect(fallback == .url("https://micro.blog/uploads/from-body")) + + // No URL anywhere → request failure, never a silent success. + let bare = await Micropub.uploadMedia( + mediaEndpoint: "https://micro.blog/micropub/media", + filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok", + transport: micropubCanned(202, body: "{}", log: log), + ) + guard case .failed(.requestFailed) = bare else { + Issue.record("expected requestFailed, got \(bare)") + return + } + + let denied = await Micropub.uploadMedia( + mediaEndpoint: "https://micro.blog/micropub/media", + filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok", + transport: micropubCanned(403, body: "{}", log: log), + ) + guard case .failed(.authFailed) = denied else { + Issue.record("expected authFailed, got \(denied)") + return + } + } + + // MARK: The create (hop 3) + + @Test func `draft request carries no photo keys ever`() { + // #34 amendment (2026-11-01): images travel INLINE — the rail + // rewrites each asset ref to its uploaded URL inside content. + // A photo property would render wherever the theme decides. + let request = Micropub.makeDraftRequest(title: "T", body: "![alt](https://micro.blog/uploads/a.png)", token: "tok") + let props = micropubJSON(request)["properties"] as? [String: Any] + #expect(props?["photo"] == nil) + #expect(props?["mp-photo-alt"] == nil) + #expect(props?["content"] as? [String] == ["![alt](https://micro.blog/uploads/a.png)"]) + } +} diff --git a/MuseionTests/MicropubModelTests.swift b/MuseionTests/MicropubModelTests.swift index 69076c0..557b188 100644 --- a/MuseionTests/MicropubModelTests.swift +++ b/MuseionTests/MicropubModelTests.swift @@ -141,4 +141,150 @@ struct MicropubModelTests { #expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/second") } + + // MARK: #34 (S6.2) — illustrations travel with it + + /// Plants a PNG beside the piece; returns the piece's post.md URL. + @MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL { + let post = try PostStore.writeNew(body: body, home: home) + model.select(post.id, home: home) + let dir = try #require(PostStore.folder(of: post.id, home: home)) + try FileManager.default.createDirectory(at: dir.appendingPathComponent("assets", isDirectory: true), withIntermediateDirectories: true) + try micropubPNG().write(to: dir.appendingPathComponent("assets/path.png")) + return dir.appendingPathComponent("post.md") + } + + @Test @MainActor func `illustrations upload once and travel inline where placed`() async throws { + let (model, home) = try makeModelHome() + let fileURL = try plantIllustratedPiece( + model, home, + body: "# Inked\n\nProse before.\n\n![A winding path.](assets/path.png)\n\nProse after.", + ) + + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + + #expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil)) + // The three hops, in order: q=config → upload → create. + #expect(log.requests.count == 3) + let config = URLComponents(url: log.requests[0].url ?? Micropub.endpoint, resolvingAgainstBaseURL: false) + #expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true) + #expect(log.requests[1].url?.absoluteString == "https://micro.blog/micropub/media") + #expect(log.requests[1].httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart + // The create: the ref REWRITTEN in place with its uploaded URL + // — exactly where the writer placed it (2026-11-01: the photo + // PROPERTY rendered at the bottom, position lost), alt in the + // markdown, NO photo property keys. + let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any]) + let expected = "# Inked\n\nProse before.\n\n![A winding path.](https://micro.blog/uploads/2026/ink.png)\n\nProse after." + #expect(props["content"] as? [String] == [expected]) + #expect(props["photo"] == nil) + #expect(props["mp-photo-alt"] == nil) + + // The piece on disk is untouched — only the wire rewrote the ref. + let disk = try String(contentsOf: fileURL, encoding: .utf8) + #expect(disk.contains("![A winding path.](assets/path.png)")) + #expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/inked") + } + + @Test @MainActor func `a photo without alt text never ships`() async throws { + let (model, home) = try makeModelHome() + // Whitespace-only alt, not just empty — the floor mirrors the + // TRIMMED emptiness (#6: an isEmpty guard would pass this). + let fileURL = try plantIllustratedPiece( + model, home, + body: "# Inked\n\n![ ](assets/path.png)\n\nProse.", + ) + + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + + guard case let .refused(reason) = outcome else { + Issue.record("expected refused, got \(outcome)") + return + } + #expect(reason.contains("assets/path.png")) // names the illustration + #expect(log.requests.isEmpty) // the floor holds BEFORE anything touches the wire + #expect(Post.scan(home: home).first?.micropubURL == nil) + // The piece is untouched — the ref still rides it on disk. + let disk = try String(contentsOf: fileURL, encoding: .utf8) + #expect(disk.contains("![ ](assets/path.png)")) + } + + @Test @MainActor func `a symlinked illustration refuses before anything goes out`() async throws { + let (model, home) = try makeModelHome() + let fileURL = try plantIllustratedPiece( + model, home, + body: "# Inked\n\n![Linked.](assets/link.png)\n\nProse.", + ) + // link.png is a symlink OUT of the piece — containment must + // refuse it (the cards/learnings posture: never read through + // a planted link), never upload the target's bytes. + let outside = home.appendingPathComponent("secret.png") + try micropubPNG().write(to: outside) + try FileManager.default.createSymbolicLink( + at: fileURL.deletingLastPathComponent().appendingPathComponent("assets/link.png"), + withDestinationURL: outside, + ) + + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + + guard case let .refused(reason) = outcome else { + Issue.record("expected refused, got \(outcome)") + return + } + #expect(reason.contains("assets/link.png")) + #expect(log.requests.isEmpty) + } + + @Test @MainActor func `duplicate refs to one asset upload once and share the url`() async throws { + let (model, home) = try makeModelHome() + _ = try plantIllustratedPiece( + model, home, + body: "# Inked\n\n![A path.](assets/path.png)\n\nTail.\n\n![A path again.](assets/path.png)", + ) + + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + + #expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil)) + // config + ONE upload + create — the FILE uploads once, not once per ref. + #expect(log.requests.count == 3) + #expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1) + let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any]) + let content = try #require((props["content"] as? [String])?.first) + // Both refs share the one uploaded URL. + #expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3) + } + + @Test @MainActor func `a missing illustration refuses before anything goes out`() async throws { + let (model, home) = try makeModelHome() + _ = try plantIllustratedPiece( + model, home, + body: "# Inked\n\n![A ghost.](assets/ghost.png)\n\nProse.", + ) // path.png planted, ghost.png never + + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + + guard case .refused = outcome else { + Issue.record("expected refused, got \(outcome)") + return + } + #expect(log.requests.isEmpty) + } + + @Test @MainActor func `a piece without illustrations sends exactly one request`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Plain\n\nBody.", home: home) + model.select(post.id, home: home) + + let log = MicropubRequestLog() + _ = await model.micropubSendDraft(home: home, token: "tok", transport: micropubMediaScripted(log: log)) + + // The #33 path unchanged: no config round-trip, straight to the create. + #expect(log.requests.count == 1) + #expect(log.requests[0].url == Micropub.endpoint) + } } diff --git a/docs/devlog/20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md b/docs/devlog/20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md new file mode 100644 index 0000000..c7212e9 --- /dev/null +++ b/docs/devlog/20261101-issue34-m6-illustrations-travel-inline-s6-2_log.md @@ -0,0 +1,70 @@ +# #34 M6: Illustrations travel with it (S6.2) — inline rewrite + +> **Date:** 2026-11-01 +> **Type:** issue +> **Reference:** [git.babylondreams.de/AlexKucera/museion#34](https://git.babylondreams.de/AlexKucera/museion/issues/34) + +## Goal + +Ink-sketch PNGs in a Post's `assets/` upload to Micro.blog via the Micropub media endpoint and travel with the piece, with alt text — G12: the author judges style, the mentor never assesses images. AC floor: a photo without alt text never ships. + +## What Was Done + +- `Museion/MicropubMedia.swift` (new) — `nonisolated extension Micropub`: `illustrations(in:)` parses `![alt](assets/…)` refs (one shared single-line-alt regex), `rewritingIllustrations(_:uploaded:)` builds the wire body, `mimeType(forDestination:)` (the endpoint's exact formats), `makeConfigRequest` (q=config), `makeMediaUploadRequest`/`uploadMedia` (multipart `file` POST, per-request boundary, sanitized Content-Disposition filename; Location → body url → trust-gated decode). +- `Museion/Micropub.swift` — `micropubSendDraft` routes through the private `uploadIllustrations` rail: alt floor → pre-flight (mime gate, symlink-resolved path containment, one payload per FILE) → q=config → one upload per file → refs rewritten in place; `makeDraftRequest`/`sendDraft` back to the exact #33 shape (no photos param, no photo property keys). +- `MuseionTests/MicropubMediaTests.swift` (new) + `MicropubModelTests.swift` — 15 pins: parse/rewrite (position, alt verbatim, quoted-title drop, angle form, boundaries, multi-line agreement), mime matrix, multipart bytes, decode gates, three-hop order, whitespace-alt floor, symlink refusal, duplicate-destination upload-once, no-photo-keys-ever, no-illustration single request. +- Live dogfood (alexanderkucera.com, 2026-11-01): upload + attach worked; the shipped photo-PROPERTY transport rendered the image at the BOTTOM of the post — position lost. Fixed by swapping to inline URL rewriting (refs keep their place, alt rides the markdown). +- Finish-audit (3 fresh-context reviewers): 7 findings fixed — markdown injection via upload URL (angle-form destination), symlinked-asset exfiltration (resolvingSymlinksInPath containment), duplicate-ref double upload (per-file payloads), whitespace-alt pin gap (#6 class), rewrite boundary pins, mime matrix completion, regex recompile (`static let`). All four behavior guards flip-verified in one batch cycle (4 pins failed on their own guards, restored, green). +- Ticket #141 published (drop-image-onto-editor ingest UX, blocked by #34) after a design discussion — alt type-over placeholder, slugged filenames, saved-posts-only, prose-only. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| INLINE URL rewrite, no `photo`/`mp-photo-alt` property | Live dogfood proved the property renders wherever the theme decides (bottom); inline refs preserve position, alt rides the markdown, and sending both would double-render. Net code smaller than the property shape. | +| Angle form `![alt]()` when the URL carries `()<> ` chars | `trustworthyURL` was built for line-bounded frontmatter; a `)` in a plain-paren destination closes the image early and smuggles a live attacker link. Angle form caps worst case at broken rendering. | +| One payload per FILE (duplicate refs share it) | Header+footer refs to one asset uploaded twice and orphaned the first URL; iterating the deduped payload list is shorter than the per-ref loop it replaced. | +| Symlink-resolved containment | Lexical `standardizedFileURL` prefix passes a symlinked `assets/` — the bytes would upload off-machine under the writer's token. Matches the cards/learnings symlink posture. | +| Floor at the rail only (chokepoint guard deleted) | With no photos param, a parsed body ref is the ONLY way an image ships and every send routes through the rail — a second guard defended nothing (#6's rule applied honestly, not reflexively). | +| Regex stays NSRegularExpression (`static let`) | The Regex-literal conversion rewrites a coordinate system three reviewers' probes verified correct; the free hoist kills the only real cost (recompile per access). | +| #141 own ticket, not a #34 rider | Ingest UX is new surface beyond #34's ACs; #34 closes clean. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Published image rendered at post bottom, not where placed | Ref stripped from wire body; image attached as a `photo` property, which the theme renders wherever it wants | Rewrite refs in place with uploaded URLs (the flagged interpretation choice, settled by dogfood) | +| Build error "Unprintable ASCII character" | A patch inserted a literal TAB byte inside a Swift string literal instead of the `\t` escape | Byte-exact Python replace (patch-tool fuzzy matching can't be trusted with invisible bytes) | +| `mark` lint violation from a comment | A test comment line began `// MARKDOWN` — the rule matches `// MARK`-prefixed lines loosely | Reworded the comment | +| `large_tuple` violation | Per-file payload list as a 3-tuple | Private `Payload` struct inside the rail | +| Restore-after-flip aborted mid-script | Restore tuple ordered `(old='', new=…)` — empty old_string asserts against 15k matches | Insert-before-anchor restore with `count==1` anchors, re-verified markers | +| UI smoke test red for ~30 min (61s activation timeout) | #134-class window-server state (app itself proven to launch and stay alive; failure survived isolation + testmanagerd restart) | Nothing — cleared on its own before the final verification run (546/546) | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/MicropubMedia.swift` | NEW — parse/rewrite/mime/config/multipart media surface | +| `Museion/Micropub.swift` | Illustration rail in `micropubSendDraft`; draft request back to #33 shape | +| `MuseionTests/MicropubMediaTests.swift` | NEW — 11 media-surface pins | +| `MuseionTests/MicropubModelTests.swift` | +6 #34 model pins incl. floor, symlink, duplicate | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX: the inline-rewrite contract + pin inventory | +| `AGENTS.md` (root) | GitNexus stats line + session-log window | + +## Verification + +- Full suite **546 executed / 546 passed / 0 failed** (xcodebuild macOS, xcresult-counted) — 529 baseline + 17 net new +- Flip cycle: all four audit guards disabled in one batch → exactly the four pins failed → restored → green +- swiftformat 0 dirty; swiftlint clean on all touched files +- GitNexus detect-changes (intended Micropub family + docs only) + analyze re-run + +## Open Items & Next Steps + +- [ ] One live re-publish of an illustrated piece (Send Again → Publish) to see the inline position on the real blog — then close #34 +- [ ] #34's AC1 wording says "attaches as photo" — mechanism is now inline; amend or accept on close +- [ ] #141 (drop image onto prose editor) unblocks when #34 closes — filename slugging must keep the space-free destination contract +- [ ] v2 candidates (declined): upload dedup via q=source on re-send, HEIC conversion, host-allowlist for trustworthyURL + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 4d14126..d393ed0 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-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 | | 2026-10-30 | issue | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | #122 Blind Read: advisory whole-document A/B on a fresh museion session, randomized unlabeled pair, reveal after verdict; 500 tests |