feat(publish): Micropub draft → publish (#33)
CI / ci (push) Canceled after 0s

Two-step publish to Micro.blog over Micropub: Send as Draft (JSON
h=entry create — name = the Title, markdown content verbatim,
post-status draft), review via the preview link, then Publish (the
action=update post-status flip). The piece remembers its draft URL
as a frontmatter micropub_url stamp — in-place, body and foreign
keys byte-identical — so a draft survives a reopen; Send Again
re-drafts after edits. The app token lives in the Keychain (login
keychain; entered once in the sheet, re-offered only on auth
failure — ADR-0014's no-Keychain rule covers only provider keys
hermes reads from .env). Frontmatter category: is permitted but
never sent in v1 — pinned on the wire.

The draft URL is trust-boundary data landing in frontmatter, so
every URL passes a format gate (https + host, no line/control
characters) at BOTH ends: the response decode (Location header →
body url; the preview link is display-only, never the publish
target) and Post.scan's read-back — imported frontmatter rides
verbatim, and a newline--- rider would otherwise close the block
and reparse as attacker markdown in the writer's piece.

Twenty tests pin the wire contract, decode matrix, own-slot keychain
round-trip, stamp/scan, and the model flow (flush-first, refusal
guards, the category AC); all four audit guards are flip-verified.
Full suite 529 passed / 0 failed. Live end-to-end on a real post
(needs the owner's app token) remains open on the ticket.
This commit is contained in:
AlexKucera committed 2026-10-31 17:49:50 +01:00
1 parent 3ee6756467
commit 414f1392ef
15 files changed
+1106 -7

No files matched your search

+5 -4
View File
@@ -22,15 +22,16 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette.
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \<title\>" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `<home>/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media querieLine truncated
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse.
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc.
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`).
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling).
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `<piece>/passes/pass-<n>.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update iLine truncated
- `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`).
- `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft).
- `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `<home>/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`.
- `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent).
- `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue.
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePosLine truncated
- `Micropub.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubPublishSheet.swift`** — the G9 ask-before surface owning both steps: Send as Draft → (review via the preview link) → Publish, each its own explicit click; refusals inline orange with buttons kept (ApplyAskSheet posture); the token field appears when none is saved or after an auth failure (re-entry replaces — never a dead end), a fresh entry is saved ONCE to the Keychain; `Send Again` re-drafts (the piece changed post-draft) and overwrites the remembered URL; `.onAppear` seeds from the piece's `micropubURL` so a draft from an earlier session still publishes.
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePosLine truncated
- `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).
+283
View File
@@ -0,0 +1,283 @@
//
// Micropub.swift
// Museion
//
// #33 (S6.1): the Micro.blog Micropub client + the app-token store.
// Two-step publish (G2/G11): create with `post-status: draft`, review,
// then `action=update` flips the draft to published. Bearer app-token
// 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).
//
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the
// draft's final URL arrives in the Location header, the body carries
// url + preview; update is JSON-only action/replace.
//
import Foundation
import Security
nonisolated enum Micropub {
/// Micro.blog's Micropub endpoint (G2: the fixed v1 target — no
/// discovery, no per-blog config).
static let endpoint = URL(string: "https://micro.blog/micropub")!
enum Outcome: Equatable {
/// Create landed; `url` is the draft's final URL (Location
/// header, body url as fallback) — what `publish` targets and
/// what the piece remembers.
case drafted(url: String, preview: String?)
case published
/// No open saved piece (model guard) — nothing went out.
case refused(String)
case authFailed(String)
case requestFailed(status: Int, detail: String)
case unreachable(String)
}
// MARK: Transport (ProviderProbe seam: canned in tests, URLSession live)
typealias Transport = @Sendable (_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
static let urlSessionTransport: Transport = { request in
let (data, response) = try await URLSession.shared.data(for: request)
guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }
return (data, http)
}
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic)
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
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.
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
],
], options: [.sortedKeys])
return request
}
static func makePublishRequest(url: String, token: String) -> URLRequest {
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.httpBody = try? JSONSerialization.data(withJSONObject: [
"action": "update",
"url": url,
"replace": ["post-status": ["published"]],
], options: [.sortedKeys])
return request
}
// 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.
static func sendDraft(
title: String,
body: String,
token: String,
transport: Transport = urlSessionTransport,
) async -> Outcome {
await run(makeDraftRequest(title: title, body: body, token: token), transport: transport, decodeDraftURL: true)
}
/// Step 2: publish the draft — flip its post-status. Needs the
/// draft's URL from step 1 (the piece's remembered `micropub_url`).
static func publish(
url: String,
token: String,
transport: Transport = urlSessionTransport,
) async -> Outcome {
guard !url.isEmpty else { return .refused("No draft URL on this piece — send it as a draft first.") }
return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false)
}
/// One POST + the honest decode: 2xx → drafted/published (drafts
/// need a URL — Location header first, body `url` second; the
/// preview link is display-only, never the publish target; a create
/// with no trustworthy URL is a request failure, never a silent
/// success), 401/403 → authFailed, other statuses carry Micropub's
/// `error_description`, transport throws → unreachable.
private static func run(
_ request: URLRequest,
transport: Transport,
decodeDraftURL: Bool,
) async -> Outcome {
do {
let (data, response) = try await transport(request)
guard (200 ..< 300).contains(response.statusCode) else {
return decodeFailure(status: response.statusCode, body: data)
}
guard decodeDraftURL else { return .published }
let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
// #33 audit: the URL is trust-boundary data — it lands in
// frontmatter and drives a later publish. Location first,
// body url second; both must pass the format guard.
let url = response.value(forHTTPHeaderField: "Location") ?? root["url"] as? String
guard let url, trustworthyURL(url) else {
return .requestFailed(status: response.statusCode, detail: "no trustworthy URL in the response")
}
return .drafted(url: url, preview: root["preview"] as? String)
} catch {
return .unreachable(error.localizedDescription)
}
}
/// A draft URL Museion will persist and act on: https, a host, no
/// line/control characters — a `\n---` riding this value would close
/// the frontmatter block on the next parse and re-parse as BODY
/// (arbitrary markdown in the writer's piece, shipped under their
/// token by the next send). Applied at both ends: the decode above
/// and `Post.scan`'s read-back (imported frontmatter rides verbatim).
/// Format-only by design — ponytail: a well-formed foreign URL still
/// passes (the label shows its full text); host-allowlist when v2's
/// q=config surface names the blog's real domains.
static func trustworthyURL(_ string: String) -> Bool {
guard !string.isEmpty,
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
let url = URL(string: string),
url.scheme?.lowercased() == "https",
url.host != nil
else { return false }
return true
}
private 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 {
return .authFailed(detail)
}
return .requestFailed(status: status, detail: detail)
}
}
/// The Micro.blog app token — Museion's OWN credential, read only by
/// this app (ADR-0014's no-Keychain rule covers provider keys hermes
/// must read from `.env`; this token has no engine consumer).
/// Entered once, stored in the login keychain (the legacy file-based
/// store — no `kSecUseDataProtectionKeychain`, which needs
/// keychain-access-groups from a provisioning profile this
/// not-yet-distributed app doesn't sign with).
nonisolated enum MicropubTokenStore {
private static let service = "com.babylondreams.Museion.micropub"
/// The production slot. Tests pass their own account — the suite
/// must never touch (or, on a locked keychain, delete) a real
/// live token (#33 audit).
private static let account = "micro.blog"
/// `account` is overridable for tests only; production callers use
/// the default.
static func read(account: String = account) -> String? {
var query = baseQuery(account: account)
query[kSecReturnData as String] = true
query[kSecMatchLimit as String] = kSecMatchLimitOne
var out: CFTypeRef?
guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess,
let data = out as? Data
else { return nil }
return String(data: data, encoding: .utf8)
}
/// Add-or-replace (rotation replaces, never duplicates). An empty
/// token is never stored.
static func save(_ token: String, account: String = account) {
guard !token.isEmpty else { return }
let data = Data(token.utf8)
var update = baseQuery(account: account)
update[kSecValueData as String] = data
if SecItemUpdate(update as CFDictionary, [kSecValueData as String: data] as CFDictionary) == errSecItemNotFound {
var add = update
add[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
SecItemAdd(add as CFDictionary, nil)
}
}
static func delete(account: String = account) {
SecItemDelete(baseQuery(account: account) as CFDictionary)
}
private static func baseQuery(account: String) -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
}
}
// MARK: - #33 (S6.1) Micropub draft → publish
extension PostsModel {
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// as a draft (h=entry, name = Title, markdown content, post-status
/// draft — category frontmatter never travels). runPass's guard set
/// minus the engine gates (no engine involved); flush-first so the
/// wire carries the editor's latest. On success the piece remembers
/// the draft URL (`micropub_url` stamp) — a stamp failure never
/// un-sends the draft; it lands in lastError while the outcome stays
/// honest. Publishing (step 2) is stateless: the sheet calls
/// `Micropub.publish` against the remembered URL directly.
func micropubSendDraft(
home: URL,
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let session,
let id = session.postID,
id == selectedPostID,
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
return .refused("Open a saved post to publish.")
}
guard flushOrAbort(id) else {
return .refused(lastError ?? "Couldn't save the piece before sending.")
}
// Disk is the truth post-flush — ONE read serves both wire fields:
// Title (heading markers stripped — it publishes as the entry's
// name) and the frontmatter-stripped body (the stamp is
// bookkeeping, never prose; the body itself is never stripped,
// GLOSSARY). No scan dependency: the list can lag the open piece.
guard let dir = PostStore.folder(of: id, home: home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
return .refused("Couldn't read the piece before sending.")
}
let body = PostStore.splitFrontmatter(raw).body
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
return .refused("This piece has no text to send.")
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
body: body,
token: token,
transport: transport,
)
if case let .drafted(url, _) = outcome {
// Remember the draft URL for the publish step. A stamp
// failure can't un-send the draft; the sheet still holds
// the URL for this session — the piece just loses the
// memory across a reopen (re-send the draft then). Kept
// quiet: lastError's setter stays PostsModel-file-private,
// and the same disk accepted the flush moments before.
try? PostStore.stampMicropubURL(id: id, url: url, home: home)
}
return outcome
}
}
+212
View File
@@ -0,0 +1,212 @@
//
// MicropubPublishSheet.swift
// Museion
//
// #33 (S6.1): the publish ask — draft first, then publish (G9:
// publish is ask-before; each step is its own explicit click). The
// sheet owns the whole two-step flow over the OPEN piece: Send as
// Draft (h=entry, name, markdown content) → review on Micro.blog →
// Publish (the post-status update against the piece's remembered
// draft URL). The app token is entered here ONCE and lives in the
// Keychain (G11; re-offered only on an auth failure). Refusals show
// inline with the buttons kept (ApplyAskSheet posture).
//
import SwiftUI
/// #33 (S6.1): the two-step Micro.blog ask over the open piece.
struct MicropubPublishSheet: View {
let posts: PostsModel
let home: URL
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
case idle
case drafting
case drafted
case publishing
case published
}
@State private var phase: Phase = .idle
/// The draft URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (a draft sent in an earlier session).
@State private var draftURL: String?
@State private var previewURL: String?
@State private var refusal: String?
@State private var tokenField = ""
@State private var reentry = false
/// Token entry shows when none is saved — or again after an auth
/// failure (the entered-once token can be replaced, never a dead end).
private var showsTokenField: Bool {
reentry || MicropubTokenStore.read() == nil
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Publish to Micro.blog?")
.font(.headline)
Text(pieceTitle)
.font(.callout.weight(.semibold))
.lineLimit(2)
Text("Museion sends it as a draft first — nothing goes out until you publish.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
if showsTokenField {
SecureField("App token", text: $tokenField)
.textFieldStyle(.roundedBorder)
.font(.system(size: 12, design: DesignTokens.mono))
Text("From micro.blog → Account → App Tokens. Stored in your Keychain.")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
if phase == .drafting || phase == .publishing {
ProgressView()
}
if let url = statusURL {
// The draft lives on Micro.blog — the preview link goes
// there for review; once published it's the post itself.
VStack(alignment: .leading, spacing: 4) {
Text(phase == .published ? "Published" : "Draft on Micro.blog")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
if let link = URL(string: phase == .published ? url : (previewURL ?? url)) {
Link(destination: link) {
Text(link.absoluteString)
.font(.system(size: 11, design: DesignTokens.mono))
.lineLimit(1)
.truncationMode(.middle)
}
}
}
}
if let refusal {
Text(refusal)
.font(.callout)
.foregroundStyle(.orange)
}
HStack(spacing: 8) {
if phase == .published {
Button("Done") { dismiss() }
.buttonStyle(.borderedProminent)
} else {
Button("Publish") { publish() }
.buttonStyle(.borderedProminent)
.disabled(draftURL == nil || phase == .drafting || phase == .publishing)
if draftURL != nil {
// The piece changed since the draft — a fresh send
// replaces it (and the remembered URL).
Button("Send Again") { sendDraft() }
.buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing)
} else {
Button("Send as Draft") { sendDraft() }
.buttonStyle(.bordered)
.disabled(phase == .drafting || phase == .publishing)
}
Button("Cancel") { dismiss() }
.buttonStyle(.bordered)
}
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding(16)
.frame(width: 340, alignment: .leading)
.onAppear {
// A draft sent in an earlier session is still publishable:
// the piece remembers its URL.
if draftURL == nil, let id = posts.session?.postID {
if let remembered = posts.posts.first(where: { $0.id == id })?.micropubURL {
draftURL = remembered
}
}
}
}
// MARK: Steps
/// The open piece's Title (the sheet is only reachable with a piece
/// open; the id is the honest fallback).
private var pieceTitle: String {
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
}
private var statusURL: String? {
phase == .drafted || phase == .published || phase == .publishing ? draftURL : nil
}
/// Resolve the token: a freshly entered one is saved ONCE (rotation
/// replaces); otherwise the Keychain's. Nil → the inline ask, never
/// a silent send.
private func resolveToken() -> String? {
if !tokenField.trimmingCharacters(in: .whitespaces).isEmpty {
let token = tokenField.trimmingCharacters(in: .whitespaces)
MicropubTokenStore.save(token)
reentry = false
return token
}
guard let saved = MicropubTokenStore.read() else { return nil }
return saved
}
private func sendDraft() {
guard let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = .drafting
Task {
switch await posts.micropubSendDraft(home: home, token: token) {
case let .drafted(url, preview):
draftURL = url
previewURL = preview
phase = .drafted
case let .authFailed(detail):
reentry = true // the entered-once token may be wrong
refusal = "Micro.blog rejected the token: \(detail)"
phase = draftURL == nil ? .idle : .drafted
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = draftURL == nil ? .idle : .drafted
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = draftURL == nil ? .idle : .drafted
case .published:
break
}
}
}
private func publish() {
guard let url = draftURL, let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = .publishing
Task {
switch await Micropub.publish(url: url, token: token) {
case .published:
phase = .published
case let .authFailed(detail):
reentry = true
refusal = "Micro.blog rejected the token: \(detail)"
phase = .drafted
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = .drafted
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = .drafted
case .drafted:
break
}
}
}
}
+13
View File
@@ -34,6 +34,10 @@ struct PostEditorView: View {
var draftSave: (() -> Void)?
/// #109: render the outline editing surface instead of prose.
var outline = false
/// #33 (S6.1): open the Micro.blog publish ask. Nil (default) hides
/// the toolbar button — drafts, the external guest, and previews
/// have nothing to publish.
var publish: (() -> Void)?
@State private var closeObserver: AnyCancellable?
@State private var toggleObserver: AnyCancellable?
@@ -228,6 +232,15 @@ struct PostEditorView: View {
.lineLimit(1)
.truncationMode(.head)
Spacer()
// #33 (S6.1): the publish entry — draft first, then publish.
if let publish {
Button("Publish") { publish() }
.buttonStyle(.plain)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.help("Send to Micro.blog — draft first, then publish")
.padding(.trailing, 10)
}
if let session {
SaveStateDot(state: session.saveState)
} else {
+13
View File
@@ -28,6 +28,10 @@ nonisolated struct Post: Identifiable, Equatable {
var project: String
/// True when the piece lives under archive/ (#107).
var isArchived: Bool
/// #33 (S6.1): the remembered Micro.blog draft URL (frontmatter
/// `micropub_url`) — set when a draft was sent, the target the
/// publish step updates. Inert to everything else.
var micropubURL: String?
/// #32 (S5.2): the captured first-draft stats — present ONLY when
/// `captureFirstDraftStats` stamped the piece at a pass invocation
/// (writer origin, First Draft, post type, decided there against the
@@ -154,6 +158,15 @@ nonisolated struct Post: Identifiable, Equatable {
type: type,
project: projectDir.lastPathComponent,
isArchived: isArchived,
// #33: the remembered Micro.blog draft URL —
// one flat key, read leniently like the rest.
// #33 audit: imported frontmatter rides
// verbatim, so the read-back gates on the same
// format guard the decode applies — a hostile
// value never pre-arms the publish sheet.
micropubURL: frontmatter["micropub_url"].flatMap {
Micropub.trustworthyURL($0) ? $0 : nil
},
// #32 read-back gate: the capture gate's immutable
// pair (origin writer, type post) — NOT pass_state,
// which legitimately advances after the capture.
+17
View File
@@ -770,4 +770,21 @@ nonisolated extension PostStore {
)) != nil else { return false }
return true
}
// MARK: #33 (S6.1) — the remembered Micro.blog draft URL
/// Stamp `micropub_url` in place on a successful draft send — the
/// publish step's target (a frontmatter-only change: the body and
/// every other key stay byte-identical, so the open session's
/// readBody-based echo check never fires). A vanished piece throws
/// (write-never-resurrects, `writeNew` is the only creator).
static func stampMicropubURL(id: String, url: String, home: URL) throws {
guard let dir = folder(of: id, home: home) else {
throw CocoaError(.fileReadNoSuchFile)
}
let file = dir.appendingPathComponent("post.md")
let raw = try String(contentsOf: file, encoding: .utf8)
try LearningDecay.stampingFrontmatter(of: raw, with: [("micropub_url", url)])
.write(to: file, atomically: true, encoding: .utf8)
}
}
+3 -1
View File
@@ -473,7 +473,9 @@ final class PostsModel {
/// folder move must never carry away text that didn't land (the move
/// itself succeeds exactly when a file write fails). Returns false with
/// lastError set; the session stays up, dirty and honest.
private func flushOrAbort(_ postID: String) -> Bool {
/// #33: internal — the Micropub draft flow (Micropub.swift) flushes
/// through the same rail.
func flushOrAbort(_ postID: String) -> Bool {
guard let session, session.postID == postID else { return true }
// #114 audit: an unanswered #67 conflict means disk holds foreign
// text with the session's version unwritten — proceeding would act
+8
View File
@@ -29,6 +29,8 @@ struct PostsPaneView: View {
/// keeps previews compiling).
var onOpenSettings: (() -> Void)?
@Environment(AppGateState.self) private var gate
/// #33 (S6.1): the Micro.blog publish ask over the open piece.
@State private var showingPublish = false
private var showsLibrary: Bool {
availableWidth >= 1100 - DesignTokens.railWidth
@@ -71,6 +73,11 @@ struct PostsPaneView: View {
// Bind: initial off-main scan + (re)start the FSEvents watcher (#61).
model.bind(home: home)
}
// #33 (S6.1): the publish ask rides the pane (not the library
// column) — it targets the open piece.
.sheet(isPresented: $showingPublish) {
MicropubPublishSheet(posts: model, home: home)
}
}
private var paneBorder: some View {
@@ -113,6 +120,7 @@ struct PostsPaneView: View {
outline: session.postID != model.proseOverridePostID
&& (model.lastDraftWasOutline
|| model.posts.first(where: { $0.id == session.postID })?.type == .outline),
publish: { showingPublish = true },
)
.id(session.postID ?? "post")
} else if model.outlineGuardPieceID != nil {