feat(microblog): show Micro.blog publish status

The publish sheet flipped a draft live and remembered nothing, so
nothing on disk said a piece was out and the library could not show
it. A successful Publish now stamps `micropub_published` in the
piece's frontmatter; the row and the sheet read `published <date>`
or `draft on Micro.blog`, and a published piece's menu opens the
live post.

Sending a piece again no longer creates a second post: a piece that
remembers its post updates it in place (name and content only, so
categories set on Micro.blog survive). An image whose bytes are
unchanged rides its earlier upload through a per-piece memo. When
Micro.blog answers 404 the piece forgets both keys and the sheet
offers a fresh draft; a clear that cannot land says so instead of
claiming the link is gone.

Museion's micropub keys are dropped at the import boundary. An
imported `micropub_url` passes the format gate and would aim the
in-place update at one of the writer's own posts under their token,
so the keys are treated like `origin`: ours to set, never a foreign
file's to carry in. Publish is model-owned and trust-gates its URL
before anything is stamped.

Tests read recorded requests through an optional accessor: an
out-of-range subscript after a failed count expectation trapped the
hosted runner and reported every queued test as crashed.

+16 tests net (17 new pins in MicropubStatusTests, one retired whose
premise the in-place design voids); every new pin was watched fail
on its own guard. Rail 752/752; SwiftFormat and SwiftLint clean.
Reviews: standards + spec during the build, then a three-reviewer
finish audit. Docs: AGENTS.md bullets and learnings, GLOSSARY
terms, CHANGELOG [Unreleased], README, and the devlog.

Closes #206
This commit is contained in:
AlexKucera committed 2026-12-04 17:45:35 +01:00
1 parent 6938826101
commit 6aa31a419a
21 files changed
+1151 -225

No files matched your search

+10 -10
View File
@@ -15,7 +15,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `AppMetadata` is the single source for displayed name/tagline; members `nonisolated`.
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (all six project configs aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
- App Sandbox OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime ON for Developer ID notarization; no `.entitlements` file.
- No persistence layer. Exceptions (app metadata only, never content): the engine check's `state.json` and the session roster's `sessions.json` (names/ids only; transcripts stay engine-owned, ADR-0007).
- No persistence layer. Exceptions (app metadata only, never content): the engine check's `state.json` and the session roster's `sessions.json` (names/ids only; transcripts stay engine-owned, ADR-0007), and the per-piece Finder-invisible sidecars that die with the piece folder — the cursor state `.museion-state.json` (#66) and the Micro.blog upload memo `.museion-uploads.json` (#206).
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean. App icon: single-size 1024×1024 PNG in `Assets.xcassets/AppIcon.appiconset`.
## Workspace shell
@@ -24,15 +24,15 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination`: the drop surface for drags that land OUTSIDE the editor — macOS 27.2.1 routes a drag to the DEEPEST destination, so over the editor the text view takes the drag itself (`FileDropTextView`'s drag handlers) and this destination never fires (the inverse of the 27.0.1 ruling #141 was verified on); both route through `AppGateState.routeFileDrop` — the ONE file-drop router (pure-markdown → external guest, anything else → `ingestDrop`, Cold Turkey–guarded; a mixed md+image set and web URLs refuse loudly). A landed drop hops to Posts (unreachable for images today — the editor mounts only there). The house ask sheets present here (pending-state + binding pattern; the sheet structs live in `WorkspaceViewSheets.swift`, #193). #193 splits: `ArchivePaneView` → `ArchivePaneView.swift`, shared chrome (`SelectedRowStrip`/`BorderedSecondaryButtonStyle`/`PaneHeader`) → `WorkspaceChrome.swift`; `RailButton` stays here (the rail is its only caller).
- `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`. Row menu: Move Back / Rename / Convert, plus #205 Reveal in Finder / Copy Path.
- `ArchivePaneView.swift` — #193: the #108 Archive pane (moved from WorkspaceView.swift) — archive/ as a rail destination, List-only: clicking a piece selects it and hops to Posts (where the editor column lives); reuses `LibraryPostRow`. Row menu: Move Back / Rename / Convert, plus #205 Reveal in Finder / Copy Path and #206 Open on Micro.blog.
- `WorkspaceViewSheets.swift` — #193: the house ask sheets (moved from WorkspaceView.swift) — `OriginAskSheet` (the ONE origin ask per import batch, #94), `OutlineGuardSheet` (#111 mixed-content), `ConvertSheet` (#114), `NewProjectSheet` (#108).
- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them. #205 `FinderHandOffButtons` — the ONE Reveal in Finder / Copy Path fragment every piece-listing row menu mounts directly (library column, Archive pane); both act on `model.fileURL(for:)`, a nil URL no-ops.
- `WorkspaceChrome.swift` — #193: the shared chrome (moved from WorkspaceView.swift) — `SelectedRowStrip` (the selected-row capsule), `BorderedSecondaryButtonStyle` (the bordered secondary button), `PaneHeader` (the 52pt pane-head row); every pane reuses them. #205 `FinderHandOffButtons` — the ONE Reveal in Finder / Copy Path fragment every piece-listing row menu mounts directly (library column, Archive pane); both act on `model.fileURL(for:)`, a nil URL no-ops. #206 `MicroblogHandOffButton` — Open on Micro.blog, only for a PUBLISHED piece (a draft's final URL answers Not Found until the post is published — owner-verified 2026-12-04); mounted beside the Finder pair in both menus.
- `PostsPaneView.swift` — Posts destination (#193: the library column and the row live in their own files): editor column, mentor column (fixed 356). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu (#205: the shared `FinderHandOffButtons` fragment, between Move to Archive and Trash). Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Reveal in Finder/Copy Path/Trash (the menu is attached by the callers — `PostsLibraryColumn.swift`, `ArchivePaneView.swift`); the Archive pane reuses it.
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`) and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win), update-keys (`updating` — the in-place line-walk, every other line byte-identical). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter; a file the disk can't stat refuses as `missing`, never as a folder); `illustrationRef` is the one `![alt](assets/…)` builder.
- `PostsLibraryColumn.swift` — #193: the library column (moved from PostsPaneView.swift), shared by the unfocused layout and the focus-mode left reveal — one implementation, both surfaces. Project section heads + Pass-State groups, collapse toggle per-view; owns the rename + move sheets (`RenamePostSheet`, `MoveToProjectSheet`) and the row context menu (#205: the shared hand-off fragment — #206 `MicroblogHandOffButton`, then #205 `FinderHandOffButtons` — between Move to Archive and Trash). Library search: debounced, title+body over non-archived pieces through the file-scope `librarySearch` mount, body scan off-main through `readBody` (frontmatter never searched). `LaunchFocusReset` (r8) rides the column: the window's first become-key resigns focus back to the window, once per process.
- `LibraryPostRow.swift` — #193: the post row (moved from PostsPaneView.swift) — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Reveal in Finder/Copy Path/Open on Micro.blog (#206, published pieces)/Trash (the menu is attached by the callers — `PostsLibraryColumn.swift`, `ArchivePaneView.swift`); the Archive pane reuses it. #206: the mono-11 micro-label shows the piece's Micro.blog status when it has one (`published <date>` / `draft on Micro.blog`) in origin's place — 178pt of row content cannot carry both — and VoiceOver reads both (`accessibilityText`); origin stays one hover away (the label's tooltip).
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` through the ONE trust gate (`Micropub.rememberedURL`, format-only — ownership is settled upstream: the import boundary drops the key, so only Museion or the writer's own hand writes one); #206 `micropubPublished` (frontmatter `micropub_published`, the `stats_captured` stamp shape, read by the shared `parseStamp`) and the row label `micropubStatus` (`published <date>` / `draft on Micro.blog` / nil).
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`), `stampFormat` (the frontmatter timestamp shape both stamp writers and the reader share), and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win, and the Micro.blog bookkeeping dropped: `micropubKeys` — #206, a foreign file carries no post of this library), update-keys (`updating` — the in-place line-walk, every other line byte-identical; `dropping:` removes named keys' lines — the import and the 404 forget). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning and the Micro.blog bookkeeping dropped (#206: an imported `micropub_url` would aim the next send's content replace). Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter; a file the disk can't stat refuses as `missing`, never as a folder); `illustrationRef` is the one `![alt](assets/…)` builder. `stampMicropub` / `forgetMicropub` — the frontmatter-only micropub stamps (`micropub_url`, the #206 publish record `micropub_published`; on a 404 both lines are REMOVED — `forgetMicropub` throws when that write cannot land, so a failed clear refuses instead of claiming the link is gone), outside the write rail.
- `DraftStats.swift` — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; `words(in:)` is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift).
- `WritingGoal.swift` — the pure goal engine (no UI, no clock): `now` injected, `isMet` live and unlatched (deleting below target un-mets).
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session. `WritingLockAppDelegate` (same file) owns BOTH quit refusals: #162 asks once while a block holds; #200 gates quit-time document departure FIRST (never walk away from a block the quit then refuses to complete) — `quitReply(posts:)` is the pure decision (nil posts passes; the pins inject here), the one spoken refusal alert is hosted-guarded like the kiosk.
@@ -40,8 +40,8 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
- `DeslopLint.swift` — the deslop skill's findings computed in Swift at pass invocation (no engine round-trip; a failed lint never blocks a pass). `Resources/deslop-lint.json` bundled default; `<home>/deslop-lint.json` override wins when it exists AND decodes, any failure → bundled. Whole-word ICU matches; em-dash finding first, then tiers by first-match position; `emit` dedups against OPEN cards (closed never block, re-runs make progress).
- `Pass.swift` — `PassKind` (pass1/pass2 — the app's own names) + `PassContext.stub` (the pinned minimal engine prompt: verdict in the reply, findings as fix-card tool calls, research as candidate tool calls — the engine never writes to the piece folder) + `estimateTokens` (chars/4).
- `BlindRead.swift` — neutral "Version A/B" prompt (both bodies inline, origin-free words never appear — the judge must not know which is the rewrite; caller randomizes order), ask = pick + one line why; `reveal` mapping appended by the model ONLY after the turn ends.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter); 401/403 → authFailed with `error_description`; a 5xx over Micro.blog's HTML error page names their outage (`unavailable on their side — retry in a few minutes`), never a bare `HTTP 503` — ONE decode (`decodeFailure`), every step; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys) — entered in the sheet on first use, managed from Settings → Micro.blog (saved status, replace, remove; the page reads the slot back after every write — a locked keychain fails visibly, never a false "stored"; the status is a standing `✓ Token saved in your Keychain` row in the Settings verdict idiom, not an intro-line swap). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author. The sheet owns Send as Draft → Publish, each an explicit click; refusals inline with buttons kept; with a stored token in use it names it (the field's absence alone never said which token a send carries).
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`), (Home, ID) identity `PostsModelIdentity.swift` — `openSessionTargets` + #205 `fileURL(for:)`, the row menus' post.md path, a pure read) — the #146/#193 splits. **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text; #204 `revealCard` stamps ONE `revealRequest` (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (`caretHint`, now a `FixCardRevealRequest` — a non-zero range selects the span). `micropubSendDraft` = flush-first, ONE disk read serves both wire fields, success stamps `micropub_url`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register.
- Micropub (`Micropub.swift`, `MicropubMedia.swift`, `MicropubPublishSheet.swift`) — the Micro.blog publish path. Client over the injectable Transport: draft = h=entry (name, markdown content verbatim, post-status draft, sorted keys; `category:` frontmatter NEVER travels; NO `photo` property — uploaded illustrations ride INLINE in content, refs rewritten to uploaded URLs on the WIRE only, the piece on disk never changes). Every URL through `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; #206 the remembered URL is also an OWNERSHIP question the format gate cannot answer — the import boundary drops both micropub keys (`PostFrontmatter.micropubKeys`), so a foreign file never aims a send at one of the writer's posts); 401/403 → authFailed with `error_description`; a 5xx over Micro.blog's HTML error page names their outage (`unavailable on their side — retry in a few minutes`), never a bare `HTTP 503` — ONE decode (`decodeFailure`), every step; `preview` is display-only, never the publish target. `MicropubTokenStore` = the app's own login-keychain credential (ADR-0014's no-Keychain rule covers only provider keys) — entered in the sheet on first use, managed from Settings → Micro.blog (saved status, replace, remove; the page reads the slot back after every write — a locked keychain fails visibly, never a false "stored"; the status is a standing `✓ Token saved in your Keychain` row in the Settings verdict idiom, not an intro-line swap). Media: `illustrations(in:)` parses only `![alt](assets/…)` refs (remote refs ride as prose; multi-line alts don't parse at all — by design); parse + rewrite share ONE regex; markdown-active URLs ride the angle form. The model rail (`uploadIllustrations`) is the publish FLOOR: whitespace-empty alt refuses BEFORE any wire traffic, payload reads are contained (`../` or a symlinked asset refuses), uploads are all-or-nothing, style judgment stays with the author; #206 an UNCHANGED image never uploads twice — `.museion-uploads.json` in the piece folder maps `sha256(bytes) → URL` (trust-gated on read-back, a symlinked memo never reads, written as each upload lands), so a re-send with untouched images is ONE request. The sheet owns every explicit click and opens on the piece's publish record (#206): Send as Draft → Publish for a never-sent piece, Update Draft for a draft, Update Live Post for a published one (status line + the live link; a remembered draft shows no link — its final URL answers Not Found until published; a publish stamp with no remembered link offers Send as Draft — there is no post to update). #206 a re-send never duplicates — a piece that remembers a post UPDATES it in place (`action=update` + `replace` name/content: same URL, no second post; a draft stays a draft, a live post edits live); a 404 means the post is gone there, so the piece forgets both stamps — their lines removed (`.forgotten`) — and the sheet is back to Send as Draft — a forget that cannot land refuses with the by-hand instruction instead; refusals inline with buttons kept; with a stored token in use it names it (the field's absence alone never said which token a send carries).
- `PostsModel.swift` — @MainActor @Observable, app-scoped. Domain extensions live in their own files (guard+Convert `PostsModelOutline.swift`, passes+Blind Read `PostsModelPasses.swift`, fix cards `PostsModelCards.swift`, write rail+structural ops `PostsModelWrites.swift`, external guest+imports `PostsModelImports.swift`, watcher+rescan `PostsModelWatcher.swift` (home of `PostsWatcher`), (Home, ID) identity `PostsModelIdentity.swift` — `openSessionTargets` + #205 `fileURL(for:)`, the row menus' post.md path, a pure read) — the #146/#193 splits. **#179 write rail**: every library store write (draft save, session-born post, rename, move to project, archive/restore, trash, convert, project creation, import batch, pass advance) rides `performWrite` — ONE seam pairing the write with exactly one rescan and owning the error strip (cleared BEFORE the write, so importFiles' mid-closure per-file failures survive; a nil-Home refusal writes nothing); the MODEL owns the Home (`watchedHome` — written only by the watcher extension's `startWatching` behind `bind`, driven by WorkspaceView's root `.task(id: museionHome)` (first frame + every repoint, whichever pane is showing); no public method takes a Home parameter); the editor's debounced flush and the micropub publish stay OUTSIDE the rail (own error semantics). `PostDraft` in-memory until first save; `mountID` keys the editor `.id` so every staging REMOUNTS (the outliner re-seeds its tree). Mixed-outline guard: a lossy outline select HOLDS the ask over an empty editor (nothing can normalize on ⌘S before the choice); reselect of the held piece is a no-op. Convert: consent rechecked at answer time (Headings aborts when the body went lossy behind the ask); converting the open piece tears down and reopens routed prose. `runPass` chain: guards through `guardOpenPieceRun` (#181: the ONE guard rail shared with blindRead — nothing running, mentor not mid-turn, engine ready, open saved piece) → readiness (missingKey names the provider) → flush → snapshot (unconditional, even for a later cancel) → capture stats → lint emit → `runningPass` live → own-engine run → advance ONLY on `.ended` with stopReason ≠ "refusal"; #179 audit: a Home repoint across the engine's turn REFUSES the advance with a strip message (the rail resolves `watchedHome` at call time — stamping into the repointed library would be silent on a slug collision). `blindRead` rides the same guard rail; nothing advances or records. `refreshCards` rides the rescan + open tails; `applyCard` = flush-first, stale anchor flags the card with no text change, the edit lands through `EditorSession.adoptText`; `promoteCard` writes a Learning and touches no text; #204 `revealCard` stamps ONE `revealRequest` (the anchor's span in the LIVE session text + a per-jump token) — a view act, nothing written; the editor column feeds it into the #71 caret rail (`caretHint`, now a `FixCardRevealRequest` — a non-zero range selects the span). `micropubSend` (#206; was `micropubSendDraft`) = flush-first, ONE disk read serves the wire fields and the remembered URL — no URL → create + stamp `micropub_url`, a remembered URL → the in-place update; `micropubPublish` (step 2, model-owned since #206) trust-gates its URL (`trustworthyURL` — it lands in frontmatter), then stamps the publish record `micropub_published` and heals `micropub_url` in the same write; both share the (Home, ID) identity guard `openMicropubPiece`. `canArmWritingLock`/`editorBodyText` mirror the editor's outline routing (prose only). #200: quit is a document departure — `shutdown()` routes both sessions through `documentsMayDepart` (void — the verdict channel is quitReply's); `PostsModel.active` (weak static, registered by `AppGateState.init` — the `WritingLockState.active` precedent) is the quit gate's reachability, bare test rigs never register.
- `PostsModelWatcher.swift` — #193: the watching domain of PostsModel (moved from PostsModel.swift) — `PostsWatcher` (recursive FSEvents stream, file-level, 0.5 s latency) on BOTH `projects/` and `archive/`; `bind(home:)` (WorkspaceView's root `.task(id: museionHome)` drives it); `startWatching` (the one `watchedHome` writer); `rescan` off-main through the app-scoped scan cache, skipping the `posts` assignment on equality (@Observable invalidates on assignment — panes would regroup on autosave echoes), bumping `contentRevision` on list change OR cache miss (#144), handing the session the open post's disk text (the #67 check, watcher echo suppressed by equality), riding the cards refresh at the tail.
- `PostsModelWrites.swift` — #193: the #179 write rail + structural ops (moved from PostsModel.swift) — `performWrite` (ONE seam: write + exactly one rescan + the error strip, cleared before the write), `flushOrAbort` (flush-first; a failed write, an unanswered #67 conflict, or a never-loaded session's retyped words abort with nothing changed — the alert stays up), `documentsMayDepart` (#200: the departure gate's quit run — shutdown's flush half shared with `applicationShouldTerminate`; BLOCK-QUIT posture, never silently drop), rename, trash, the #108 project ops (create/stage, `moveTargets`, move to project, archive/restore/unarchive); document departure (new post/outline, select, open external, guest dismissal) rides the same gates through `sessionMayDepart`/`departOpenDocuments` — a navigation whose outgoing flush fails aborts with the dirty session retained (brief-25).
- `PostsModelImports.swift` — #193: the external guest (#91–#93) + import batch (#94/#95) (moved from PostsModel.swift) — `openExternal`/`dismissExternal` (`-> Bool` — false holds the departure)/the guest watch (one guest at a time, symlink-resolved — an atomic write renames over a symlink — dismissed flush-first by any post/draft open — held by the departure gate when its flush fails (brief-25: the guest, its buffer, and its watcher stay live until the edits land)); `stageImport`/`cancelImport`/`importFiles` (ONE origin ask per batch, per-file failures continue into `lastError`).
+1
View File
@@ -135,6 +135,7 @@ struct ArchivePaneView: View {
}
}
Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: post)
}
}
+20 -4
View File
@@ -9,8 +9,10 @@
import SwiftUI
/// One post row per the export: title + origin-only mono-11 meta (the Pass
/// State rides the uppercase group label above; it stays in the a11y label).
/// One post row per the export: title + a mono-11 meta line — origin, or
/// (#206) the piece's Micro.blog status in its place on a sent piece (the
/// Pass State rides the uppercase group label above; it stays in the a11y
/// label).
/// #108 (variant B): 2px accent edge bar on the leading side when selected
/// (`.vB .post-row[aria-current] { border-left-color: var(--accent) }`,
/// radius 0 8 8 0), and a muted ✳ suffix on outline pieces. Internal: the
@@ -55,10 +57,14 @@ struct LibraryPostRow: View {
// group label above (it stays in the accessibility label).
// r7: the status micro-label sits INSIDE the row's content
// padding — same x as the title, never flush with the edge.
Text(post.origin.rawValue)
// #206: a piece with a Micro.blog status shows THAT here
// (origin stays in the accessibility label and one hover
// away) — the row's content is 178pt, too narrow for both.
Text(post.micropubStatus ?? post.origin.rawValue)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
.help(post.origin.rawValue)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
@@ -89,6 +95,16 @@ struct LibraryPostRow: View {
// help sits on the row — the ✳ span isn't individually hoverable in
// SwiftUI (prototype: `title="outline"` on the star).
.help(post.type == .outline ? "\(post.title) — outline" : post.title)
.accessibilityLabel("\(post.title), \(post.passState.rawValue), origin \(post.origin.rawValue)")
.accessibilityLabel(accessibilityText)
}
/// VoiceOver reads every status the row carries — #206's Micro.blog
/// status included, since it takes the micro-label's place.
private var accessibilityText: String {
var parts = [post.title, post.passState.rawValue, "origin \(post.origin.rawValue)"]
if let status = post.micropubStatus {
parts.append(status)
}
return parts.joined(separator: ", ")
}
}
+242 -65
View File
@@ -11,7 +11,13 @@
// #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.
// MicropubMedia.swift, the orchestration in micropubSend below.
// #206: a piece that remembers its post re-sends as an IN-PLACE
// update (action=update + replace name/content — never a second
// post), Publish is remembered on the piece (`micropub_published`),
// and a 404 forgets the link. Wire facts live-verified 2026-12-04
// (microblog.dev/api/posting): `replace` sets name and content;
// updates answer 200 with an empty body, 404 when the URL is gone.
//
// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting,
// book.micro.blog/micropub): JSON create = type/properties; the
@@ -32,9 +38,17 @@ nonisolated enum Micropub {
/// header, body url as fallback) — what `publish` targets and
/// what the piece remembers.
case drafted(url: String, preview: String?)
/// #206: an in-place update landed — `url` is the post the piece
/// already remembered (a draft refreshed, a live post edited).
/// No second post, no new URL.
case updated(url: String)
case published
/// No open saved piece (model guard) — nothing went out.
case refused(String)
/// #206 (model-level): Micro.blog answered 404 — the post is gone
/// there. The piece has forgotten it (both stamps cleared); the
/// payload says so. The next send is a fresh draft.
case forgotten(String)
case authFailed(String)
case requestFailed(status: Int, detail: String)
case unreachable(String)
@@ -52,12 +66,19 @@ nonisolated enum Micropub {
// MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic)
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
/// The one JSON POST shape every request rides: the fixed endpoint,
/// Bearer token, 30 s, sorted keys.
private static func jsonPost(_ object: [String: Any], 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: object, options: [.sortedKeys])
return request
}
static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest {
// 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) — the one carve-out is #34's asset
@@ -66,32 +87,40 @@ nonisolated enum Micropub {
// 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: [
jsonPost([
"type": ["h-entry"],
"properties": [
"name": [title],
"content": [body],
"post-status": ["draft"],
] as [String: Any],
], options: [.sortedKeys])
return request
], token: token)
}
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: [
jsonPost([
"action": "update",
"url": url,
"replace": ["post-status": ["published"]],
], options: [.sortedKeys])
return request
], token: token)
}
// MARK: The two steps
/// #206: refresh the post the piece remembers — title and content
/// replaced IN PLACE over the remembered URL (wire-verified
/// 2026-12-04: `replace` sets name and content, JSON-only). Never
/// a status flip: a draft stays a draft, a published post stays live.
static func makeUpdateRequest(url: String, title: String, body: String, token: String) -> URLRequest {
jsonPost([
"action": "update",
"url": url,
"replace": [
"name": [title],
"content": [body],
],
], token: token)
}
// MARK: The steps
/// Step 1: send the piece as a draft. The piece's Title is the
/// entry's name; the markdown body is the content; #34's uploaded
@@ -116,6 +145,25 @@ nonisolated enum Micropub {
return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false)
}
/// #206: step 1 again, in place — the piece's current title and
/// body replace the remembered post's (a draft refreshed for
/// review; a live post edited). Needs the remembered URL.
static func update(
url: String,
title: String,
body: String,
token: String,
transport: Transport = urlSessionTransport,
) async -> Outcome {
let outcome = await run(makeUpdateRequest(url: url, title: title, body: body, token: token), transport: transport, decodeDraftURL: false)
// `run` has one success word for the URL-less steps; the update's
// carries the URL it touched.
if outcome == .published {
return .updated(url: url)
}
return outcome
}
/// 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
@@ -152,10 +200,12 @@ nonisolated enum Micropub {
/// 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.
/// and `Post.scan`'s read-back. Format-only by design — ownership is
/// settled upstream, not here: the import boundary drops the micropub
/// keys (`PostFrontmatter.micropubKeys`, #206 — since the in-place
/// update a well-formed foreign URL would aim a content replace), so
/// only Museion or the writer's own hand writes one. ponytail:
/// host-allowlist stays the upgrade if another way in ever appears.
static func trustworthyURL(_ string: String) -> Bool {
guard !string.isEmpty,
string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil,
@@ -166,6 +216,21 @@ nonisolated enum Micropub {
return true
}
/// The remembered post URL read from frontmatter — the ONE read the
/// scan and the send share, gated like the decode: a hand-written
/// broken value is no memory at all (an imported one never arrives —
/// the boundary drops the key).
static func rememberedURL(_ matter: [String: String]) -> String? {
guard let raw = matter["micropub_url"], trustworthyURL(raw) else { return nil }
return raw
}
/// #206: the short date the library row and the publish sheet both
/// show (`Dec 4, 2026`) — one format, so the two can't drift.
static func shortDate(_ date: Date) -> String {
FixCardStore.formatted(date, "MMM d, yyyy")
}
/// Internal for MicropubMedia's media steps (#34) — the one failure
/// decode this client speaks; extensions share it rather than fork it.
/// A 5xx is Micro.blog's side (their nginx front with the app not
@@ -240,29 +305,15 @@ nonisolated enum MicropubTokenStore {
}
}
// MARK: - #33 (S6.1) Micropub draft → publish
// MARK: - #33 (S6.1) / #206 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.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSendDraft(
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
// brief-28: identity — the open session must target THIS library's
// selected piece (Home, ID); the wire below reads the session's OWN
// library, never the current Home's same-slug file. The completion
// stamp targets the same captured pair — the piece actually sent,
// wherever the writer has since pointed the app.
/// The OPEN saved library piece as the micropub pair (id, Home) —
/// the identity guard both publish steps share. brief-28: the open
/// session must target THIS library's selected piece; the wire and
/// every stamp below act on the piece actually sent (Home, ID),
/// never the current Home's same-slug file. Nil = nothing to send.
private var openMicropubPiece: (id: String, home: URL)? {
guard let session,
let id = session.postID,
let home = watchedHome,
@@ -271,18 +322,39 @@ extension PostsModel {
draft == nil,
externalSession == nil,
outlineGuardPieceID == nil
else {
else { return nil }
return (id, home)
}
/// Step 1 of the two-step publish: send the OPEN piece to Micro.blog
/// (name = Title, markdown content — 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.
/// #206: a piece that remembers no post is CREATED as a draft
/// (h=entry, post-status draft) and remembers its URL
/// (`micropub_url` stamp); a piece that remembers one UPDATES that
/// post in place — same URL, no second post — so a draft refreshes
/// for review and a published piece edits live. A stamp failure
/// never un-sends the draft.
/// #179: outside the write rail by design — publish is not a library
/// verb, and a stamp failure must never un-send the draft.
func micropubSend(
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
return .refused("Open a saved post to publish.")
}
guard flushOrAbort(id) else {
guard flushOrAbort(piece.id) else {
return .refused(lastError ?? "Couldn't save the piece before sending.")
}
// Disk is the truth post-flush — ONE read serves both wire fields:
// Disk is the truth post-flush — ONE read serves the wire fields:
// Title (heading markers stripped — it publishes as the entry's
// name) and the frontmatter-stripped body (the stamp is
// name), 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),
// GLOSSARY), and the remembered URL. No scan dependency: the
// list can lag the open piece.
guard let dir = PostStore.folder(of: piece.id, home: piece.home),
let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else {
return .refused("Couldn't read the piece before sending.")
@@ -303,25 +375,91 @@ extension PostsModel {
return outcome
}
}
let title = Post.title(of: raw)
// #206: the piece remembers its post → update THAT post in
// place (the remembered URL never moves; nothing new to stamp).
// A 404 means the post is gone on Micro.blog — the piece forgets
// it rather than fail forever against a dead URL.
if let remembered = Micropub.rememberedURL(PostFrontmatter.parse(raw)) {
let outcome = await Micropub.update(url: remembered, title: title, body: wireBody, token: token, transport: transport)
if case .requestFailed(404, _) = outcome {
return micropubPostGone(id: piece.id, home: piece.home)
}
return outcome
}
let outcome = await Micropub.sendDraft(
title: Post.title(of: raw),
title: title,
body: wireBody,
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)
// Remember the draft's URL for the publish step and every
// later in-place update. 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 (it
// would create a second draft then). Kept quiet: the same
// disk accepted the flush moments before.
try? PostStore.stampMicropub(piece.id, home: piece.home, [("micropub_url", url)])
}
return outcome
}
/// #34 (S6.2): the illustration rail of `micropubSendDraft`. The
/// Step 2: flip the remembered draft to published. #206: the model
/// owns it — the sheet used to call the client directly, so nothing
/// remembered a publish. Success is the piece's publish record:
/// `micropub_published` stamped now (first publish wins — a later
/// in-place update of the live post never moves it) and
/// `micropub_url` healed in the same write should the send's stamp
/// have failed. A stamp failure never un-publishes. No flush: no
/// content travels, and the editor never writes frontmatter. The URL
/// is trust-gated HERE — it lands in frontmatter (the heal), and a
/// caller's value is external until proven.
func micropubPublish(
url: String,
token: String,
transport: Micropub.Transport = Micropub.urlSessionTransport,
) async -> Micropub.Outcome {
guard let piece = openMicropubPiece else {
return .refused("Open a saved post to publish.")
}
guard Micropub.trustworthyURL(url) else {
return .refused("That post address isn't a clean https URL — nothing was sent or remembered.")
}
let outcome = await Micropub.publish(url: url, token: token, transport: transport)
switch outcome {
case .published:
try? PostStore.stampMicropub(piece.id, home: piece.home, [
("micropub_url", url),
("micropub_published", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)),
])
case .requestFailed(404, _):
return micropubPostGone(id: piece.id, home: piece.home)
default:
break
}
return outcome
}
/// #206: Micro.blog answered 404 — the post is gone there, so the
/// piece is no longer on Micro.blog: it forgets both stamps and the
/// writer hears why (the next send is a fresh draft). A forget that
/// cannot land refuses instead — never a "cleared" the disk
/// contradicts: the link is still on the piece, so the sheet stays
/// on it and says what to do by hand.
private func micropubPostGone(id: String, home: URL) -> Micropub.Outcome {
do {
try PostStore.forgetMicropub(id: id, home: home)
} catch {
return .refused(
"Micro.blog no longer has this post — it was deleted there — but its link couldn't be cleared from this piece "
+ "(\(error.localizedDescription)). Delete the `micropub_url` line from its frontmatter, then send it as a draft.",
)
}
return .forgotten("Micro.blog no longer has this post — it was deleted there. Its link is cleared; send it as a draft again.")
}
/// #34 (S6.2): the illustration rail of `micropubSend`. 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,
@@ -350,11 +488,6 @@ extension PostsModel {
// `../` 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 }) {
@@ -369,8 +502,36 @@ extension PostsModel {
}
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.
return await uploadRemembered(payloads, dir: dir, body: body, token: token, transport: transport)
}
/// One asset about to travel: its ref destination (the rewrite's
/// map key), its wire content type, its bytes.
private struct Payload {
let destination: String
let mimeType: String
let data: Data
}
/// #206: the piece's upload memo answers first — an image whose
/// bytes uploaded before rides that URL again (Micro.blog keeps
/// every copy, and their listing carries no hash to match against,
/// so the memory is local). Only what the memo lacks touches the
/// wire: q=config, then one upload per pending payload, each
/// remembered as it lands.
private func uploadRemembered(
_ payloads: [Payload],
dir: URL,
body: String,
token: String,
transport: Micropub.Transport,
) async -> IllustrationRail {
var memo = Micropub.readUploadMemo(in: dir)
let remembered = uploadedDestinations(payloads, memo: memo)
let pending = payloads.filter { remembered[$0.destination] == nil }
guard !pending.isEmpty else {
return .ready(Micropub.rewritingIllustrations(body, uploaded: remembered))
}
let mediaEndpoint: String
switch await Micropub.mediaEndpoint(token: token, transport: transport) {
case let .url(named):
@@ -378,8 +539,9 @@ extension PostsModel {
case let .failed(outcome):
return .blocked(outcome)
}
var uploaded: [String: String] = [:]
for payload in payloads {
// The `where` skips a later payload with the same bytes as one
// uploaded earlier in this batch.
for payload in pending where memo[Micropub.uploadKey(payload.data)] == nil {
let outcome = await Micropub.uploadMedia(
mediaEndpoint: mediaEndpoint,
filename: URL(fileURLWithPath: payload.destination).lastPathComponent,
@@ -390,11 +552,26 @@ extension PostsModel {
)
switch outcome {
case let .url(url):
uploaded[payload.destination] = url
// Remembered as it lands: a later failure in the batch
// keeps the earlier uploads (a retry never repeats them).
memo[Micropub.uploadKey(payload.data)] = url
Micropub.writeUploadMemo(memo, in: dir)
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))
// Every payload is memoized now — the earlier uploads and this batch's.
return .ready(Micropub.rewritingIllustrations(body, uploaded: uploadedDestinations(payloads, memo: memo)))
}
/// The rewrite's map: each payload's ref destination → its upload URL.
private func uploadedDestinations(_ payloads: [Payload], memo: [String: String]) -> [String: String] {
var uploaded: [String: String] = [:]
for payload in payloads {
if let url = memo[Micropub.uploadKey(payload.data)] {
uploaded[payload.destination] = url
}
}
return uploaded
}
}
+40
View File
@@ -16,8 +16,11 @@
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
// `GET /micropub?q=config` carries `media-endpoint`;
// `POST <media-endpoint>` multipart → 202 + Location = upload URL.
// #206: the upload memo — an image whose bytes uploaded before rides
// that URL again (`.museion-uploads.json` in the piece folder).
//
import CryptoKit
import Foundation
nonisolated extension Micropub {
@@ -194,6 +197,43 @@ nonisolated extension Micropub {
}
}
// MARK: #206 — the upload memo (a re-send never re-uploads)
/// `.museion-uploads.json` in the piece folder — the cursor
/// sidecar's posture: Finder-invisible, dies with the folder.
static let uploadMemoFile = ".museion-uploads.json"
/// The memo's key: the asset's exact bytes. Rename the file or
/// rewrite the alt and it is still the same upload; change one byte
/// and it uploads fresh.
static func uploadKey(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
/// `uploadKey → uploaded URL`. Disk is external data: a symlinked
/// memo never reads (the rail's planted-link posture) and only
/// trustworthy URLs come back — a memo URL lands in published
/// content. ponytail: an upload deleted on Micro.blog stays memoized
/// (a dead image URL) until the sidecar is removed; no liveness probe.
static func readUploadMemo(in pieceFolder: URL) -> [String: String] {
let url = pieceFolder.appendingPathComponent(uploadMemoFile)
guard let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey]),
values.isSymbolicLink != true,
let data = try? Data(contentsOf: url)
else { return [:] }
let memo = (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
return memo.filter { trustworthyURL($1) }
}
/// Best-effort, like the cursor sidecar: a failed memo write only
/// costs a re-upload, never a send.
static func writeUploadMemo(_ memo: [String: String], in pieceFolder: URL) {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys // a stable file: no churn across sends or syncs
guard let data = try? encoder.encode(memo) else { return }
try? data.write(to: pieceFolder.appendingPathComponent(uploadMemoFile), options: .atomic)
}
/// 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
+142 -57
View File
@@ -11,6 +11,10 @@
// lives in the Keychain (G11; re-offered only on an auth failure —
// Settings → Micro.blog is the standing manager). Refusals show
// inline with the buttons kept (ApplyAskSheet posture).
// #206: the sheet opens on the piece's publish record. A published
// piece says so (and links its live post) and offers Update Live
// Post; a draft offers Publish / Update Draft. Both re-sends update
// the remembered post IN PLACE — never a second post.
//
import SwiftUI
@@ -21,17 +25,26 @@ struct MicropubPublishSheet: View {
@Environment(\.dismiss) private var dismiss
private enum Phase: Equatable {
/// Never sent — nothing on Micro.blog yet.
case idle
case drafting
/// A draft is on Micro.blog, not published (fresh or remembered).
case drafted
case updating
case updated
case publishing
/// The publish record — this session's Publish, or the piece's stamp.
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?
/// The post URL this sheet knows: fresh from a send, or the piece's
/// remembered `micropub_url` (sent in an earlier session) — a draft's
/// until it is published, the live post's after.
@State private var postURL: String?
/// #206: when the piece was published — its stamp, or this session's
/// Publish. Nil while it is a draft.
@State private var publishedAt: Date?
@State private var previewURL: String?
@State private var refusal: String?
@State private var tokenField = ""
@@ -43,16 +56,22 @@ struct MicropubPublishSheet: View {
reentry || MicropubTokenStore.read() == nil
}
private var busy: Bool {
phase == .drafting || phase == .updating || phase == .publishing
}
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Publish to Micro.blog?")
Text(publishedAt == nil ? "Publish to Micro.blog?" : "On 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 phase == .idle {
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)
@@ -69,18 +88,18 @@ struct MicropubPublishSheet: View {
.foregroundStyle(DesignTokens.muted)
}
if phase == .drafting || phase == .publishing {
if busy {
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.
if let label = statusLabel {
// A published piece's link is the post itself; a draft's
// is its review page.
VStack(alignment: .leading, spacing: 4) {
Text(phase == .published ? "Published" : "Draft on Micro.blog")
Text(label)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
if let link = URL(string: phase == .published ? url : (previewURL ?? url)) {
if let link = statusLink {
Link(destination: link) {
Text(link.absoluteString)
.font(.system(size: 11, design: DesignTokens.mono))
@@ -97,24 +116,25 @@ struct MicropubPublishSheet: View {
}
HStack(spacing: 8) {
if phase == .published {
if publishedAt != nil {
// The piece is out: the only send left edits the live
// post, immediately — the label says so. A stamp with no
// remembered link (a hand-added key) has no post to
// update: that send is a fresh draft, and says so.
Button(postURL == nil ? "Send as Draft" : "Update Live Post") { send() }
.buttonStyle(.bordered)
.disabled(busy)
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)
}
.disabled(postURL == nil || busy)
// The piece changed since the draft — a re-send
// updates that same draft (never a second post).
Button(postURL == nil ? "Send as Draft" : "Update Draft") { send() }
.buttonStyle(.bordered)
.disabled(busy)
Button("Cancel") { dismiss() }
.buttonStyle(.bordered)
}
@@ -124,17 +144,18 @@ struct MicropubPublishSheet: View {
.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
}
}
// A piece sent in an earlier session still has its record:
// the remembered URL, and (#206) its publish stamp.
guard postURL == nil, let id = posts.session?.postID,
let post = posts.posts.first(where: { $0.id == id })
else { return }
postURL = post.micropubURL
publishedAt = post.micropubPublished
phase = settledPhase
}
}
// MARK: Steps
// MARK: Status
/// The open piece's Title (the sheet is only reachable with a piece
/// open; the id is the honest fallback).
@@ -142,10 +163,49 @@ struct MicropubPublishSheet: View {
posts.session?.postID.map { posts.title(of: $0) } ?? "This piece"
}
private var statusURL: String? {
phase == .drafted || phase == .published || phase == .publishing ? draftURL : nil
private var statusLabel: String? {
switch phase {
case .idle:
nil
case .drafting:
"Sending draft…"
case .drafted:
"Draft on Micro.blog — not published yet"
case .updating:
publishedAt == nil ? "Updating draft…" : "Updating live post…"
case .updated:
publishedAt.map { "Updated live — published \(Micropub.shortDate($0))" } ?? "Draft updated — not published yet"
case .publishing:
"Publishing…"
case .published:
publishedAt.map { "Published \(Micropub.shortDate($0))" }
}
}
/// A published piece links its live post; a draft links the review
/// page — only the send that created it carries one, so a draft
/// remembered from an earlier session shows no (dead) link.
private var statusLink: URL? {
if publishedAt != nil {
return postURL.flatMap { URL(string: $0) }
}
return previewURL.flatMap { URL(string: $0) }
}
/// Where the sheet rests on the piece's record: published, draft,
/// or never sent.
private var settledPhase: Phase {
if publishedAt != nil {
return .published
}
if postURL != nil {
return .drafted
}
return .idle
}
// MARK: Steps
/// Resolve the token: a freshly entered one is saved ONCE (rotation
/// replaces); otherwise the Keychain's. Nil → the inline ask, never
/// a silent send.
@@ -160,29 +220,44 @@ struct MicropubPublishSheet: View {
return saved
}
private func sendDraft() {
/// A failed step: the message shows inline with the buttons kept, and
/// the sheet rests on the piece's record (a rejected token re-opens
/// entry — the entered-once token may be wrong).
private func fail(_ message: String, tokenRejected: Bool = false) {
if tokenRejected {
reentry = true
}
refusal = message
phase = settledPhase
}
/// Step 1 — the model decides create-vs-update by the piece's
/// remembered URL: a first send creates the draft, every later one
/// updates that post in place.
private func send() {
guard let token = resolveToken() else {
refusal = "Paste your Micro.blog app token first."
return
}
refusal = nil
phase = .drafting
phase = postURL == nil ? .drafting : .updating
Task {
switch await posts.micropubSendDraft(token: token) {
switch await posts.micropubSend(token: token) {
case let .drafted(url, preview):
draftURL = url
postURL = url
previewURL = preview
phase = .drafted
case let .updated(url):
postURL = url
phase = .updated
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
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = draftURL == nil ? .idle : .drafted
fail(reason)
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = draftURL == nil ? .idle : .drafted
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .published:
break
}
@@ -190,29 +265,39 @@ struct MicropubPublishSheet: View {
}
private func publish() {
guard let url = draftURL, let token = resolveToken() else {
guard let url = postURL, 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) {
switch await posts.micropubPublish(url: url, token: token) {
case .published:
publishedAt = Date()
phase = .published
case let .authFailed(detail):
reentry = true
refusal = "Micro.blog rejected the token: \(detail)"
phase = .drafted
fail("Micro.blog rejected the token: \(detail)", tokenRejected: true)
case let .refused(reason), let .unreachable(reason):
refusal = reason
phase = .drafted
fail(reason)
case let .requestFailed(status, detail):
refusal = "Micro.blog said \(status): \(detail)"
phase = .drafted
case .drafted:
fail("Micro.blog said \(status): \(detail)")
case let .forgotten(reason):
forgot(reason)
case .drafted, .updated:
break
}
}
}
/// #206: Micro.blog lost the post and the piece forgot it — the
/// sheet is back on a never-sent piece (a fresh draft is one click
/// away).
private func forgot(_ reason: String) {
refusal = reason
postURL = nil
publishedAt = nil
previewURL = nil
phase = .idle
}
}
+44 -13
View File
@@ -24,7 +24,9 @@ import Foundation
/// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file
/// normalization on save/advance, convert. Replaces any existing block.
/// - **merge-import** (`mergingImport`) — an external block kept verbatim
/// with our three owned keys winning in place (importFile, #95).
/// with our three owned keys winning in place (importFile, #95), and
/// Museion's Micro.blog bookkeeping dropped (#206 — a foreign file
/// carries no post of THIS library).
/// - **update-keys** (`updating`) — the surgical in-place key stamp:
/// every other line byte-identical (editor save, pass advance, stats
/// capture, micropub URL, learnings dismiss).
@@ -33,6 +35,19 @@ import Foundation
/// `origin`) are ONE rule shared by every posture: absent owned keys
/// insert before the closing `---` in that order.
nonisolated enum PostFrontmatter {
/// The frontmatter timestamp shape (`stats_captured`, #31;
/// `micropub_published`, #206) — local time, lexically sortable. The
/// one home for the format: both stamp writers and the reader share it.
static let stampFormat = "yyyy-MM-dd'T'HH:mm:ss"
/// Museion's Micro.blog bookkeeping — written only by the app (or the
/// writer's own hand, the legacy migration), never trusted from
/// outside: the import boundary DROPS these keys and the 404 forget
/// removes them. #206: an imported `micropub_url` passes the format
/// gate and would steer the next send's content replace — under the
/// writer's token — onto whatever post it names.
static let micropubKeys: Set<String> = ["micropub_url", "micropub_published"]
/// The leniently-decoded identity triple — one home for the `?? default`
/// reads scan, the write paths, and the eligibility predicates share
/// (the extraction the #31 capture's ponytail note deferred until this
@@ -139,8 +154,9 @@ nonisolated enum PostFrontmatter {
/// order), preserve every other line verbatim (leading hand-edit lines
/// above the opening `---` included, #27 review), keep the block's
/// trailing newline. No block at all → prepend a fresh one with the
/// pairs.
static func updating(text: String, with pairs: [(key: String, value: String)]) -> String {
/// pairs. `dropping` removes those keys' lines outright, first (#206:
/// the import boundary and the 404 forget).
static func updating(text: String, with pairs: [(key: String, value: String)], dropping: Set<String> = []) -> String {
let (block, body) = split(text)
guard !block.isEmpty else {
return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body
@@ -159,17 +175,15 @@ nonisolated enum PostFrontmatter {
// the lenient flat reader never claimed nested support (posture
// inherited verbatim, #180 audit INFO-1). Indentation-aware walk
// if nested frontmatter ever matters.
if !dropping.isEmpty {
lines.removeAll { key(ofLine: $0).map(dropping.contains) == true }
}
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
// whitespacesAndNewlines: CRLF lines carry a trailing \r.
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { continue }
let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
if let value = oursByKey[key] {
lines[index] = "\(key): \(value)"
seen.insert(key)
}
guard let key = key(ofLine: line), let value = oursByKey[key] else { continue }
lines[index] = "\(key): \(value)"
seen.insert(key)
}
let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" }
if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 {
@@ -181,13 +195,30 @@ nonisolated enum PostFrontmatter {
/// Posture 2 — merge-import: external frontmatter rides verbatim;
/// `type: post`, `pass_state: First Draft`, `origin: <chosen>` win
/// (#95: our three keys win — external `type: outline` still imports
/// as post). The update posture over the known-key table.
/// as post), and Museion's Micro.blog bookkeeping is dropped (#206: a
/// foreign file carries no post of this library — its `micropub_url`
/// would otherwise aim the next send's content replace). The update
/// posture over the known-key table.
///
/// #180 divergence from the absorbed mergedFrontmatter, deliberate:
/// hand-edit lines above the opening `---` now survive import (the old
/// split-first shape silently dropped them) — lossless through every
/// posture is the ticket's contract.
static func mergingImport(text: String, origin: Post.Origin) -> String {
updating(text: text, with: ownedKeys(type: .post, passState: .firstDraft, origin: origin))
updating(
text: text,
with: ownedKeys(type: .post, passState: .firstDraft, origin: origin),
dropping: micropubKeys,
)
}
/// A block line's key — the update posture's ONE key read (so the
/// drop and the walk can never disagree about a line): leading and
/// trailing whitespace trimmed, a trailing `\r` included (CRLF
/// files). Nil for the fences and blank lines.
private static func key(ofLine line: String) -> String? {
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { return nil }
return String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
}
}
+38 -22
View File
@@ -28,10 +28,18 @@ 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.
/// #33 (S6.1): the remembered Micro.blog post URL (frontmatter
/// `micropub_url`) — set when a draft was sent; the target the
/// publish step updates and a re-send replaces in place (#206), and
/// half of the row's status. Inert to everything else.
var micropubURL: String?
/// #206: when Publish succeeded — frontmatter `micropub_published`,
/// the `stats_captured` stamp shape (local time). The Museion-side
/// publish record: the library answers "is this piece out, and
/// since when" from disk, never from a live query. Nil = never
/// published from here (a piece published before this stamp read
/// as a draft until its next Publish).
var micropubPublished: Date?
/// #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
@@ -41,6 +49,15 @@ nonisolated struct Post: Identifiable, Equatable {
/// keys, and non-writer or outline pieces never render them.
var firstDraftStats: FirstDraftStats?
/// #206: the row's Micro.blog status — nil when the piece was never
/// sent; a remembered URL alone is a draft; the publish stamp wins.
var micropubStatus: String? {
if let micropubPublished {
return "published \(Micropub.shortDate(micropubPublished))"
}
return micropubURL == nil ? nil : "draft on Micro.blog"
}
/// New pieces land here when no project is selected (#107).
static let defaultProject = "posts"
@@ -58,7 +75,7 @@ nonisolated struct Post: Identifiable, Equatable {
/// reads "steady" in the verdict (finish-audit #32).
init?(frontmatter: [String: String]) {
guard
let captured = frontmatter["stats_captured"].flatMap(Self.parseCaptured),
let captured = frontmatter["stats_captured"].flatMap(Post.parseStamp),
let burstiness = frontmatter["stats_burstiness"].flatMap(Self.finite),
let typeTokenRatio = frontmatter["stats_type_token_ratio"].flatMap(Self.finite),
let sentenceVariation = frontmatter["stats_sentence_variation"].flatMap(Self.finite),
@@ -73,15 +90,6 @@ nonisolated struct Post: Identifiable, Equatable {
)
}
/// The symmetric read of the capture stamp (`FixCardStore.formatted`,
/// local time) — per-access formatter, the repo's no-static convention.
private static func parseCaptured(_ stamp: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.date(from: stamp)
}
/// Frontmatter is external data (hand-edits, imports): reject the
/// non-finite doubles Swift's `Double(String)` happily parses.
private static func finite(_ raw: String) -> Double? {
@@ -189,15 +197,12 @@ nonisolated struct Post: Identifiable, Equatable {
type: stamp.type,
project: project,
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
},
// #33: the remembered Micro.blog URL — one flat key
// through the ONE trust gate (an import drops the key,
// #206, so a hostile value never pre-arms the publish
// sheet); #206: the publish stamp beside it.
micropubURL: Micropub.rememberedURL(frontmatter),
micropubPublished: frontmatter["micropub_published"].flatMap(parseStamp),
// #32/#180 read-back gate: the named immutable pair
// (origin writer, type post) — NOT pass_state, which
// legitimately advances after the capture. `stats_*`
@@ -210,6 +215,17 @@ nonisolated struct Post: Identifiable, Equatable {
)
}
/// The frontmatter timestamp reader — `yyyy-MM-dd'T'HH:mm:ss`, local
/// time (`FixCardStore.formatted`'s writer side); nil on anything
/// else. The symmetric read of the #31 capture stamp and the #206
/// publish stamp. Per-access formatter, the repo's no-static convention.
private static func parseStamp(_ stamp: String) -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = PostFrontmatter.stampFormat
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.date(from: stamp)
}
/// The Post's Title: first non-empty line after any frontmatter block,
/// `#` heading markers stripped; `untitled` when nothing readable remains.
static func title(of text: String) -> String {
+24 -9
View File
@@ -166,7 +166,9 @@ nonisolated enum PostStore {
/// #22/#94/#95: import one external markdown file as a Post — copy, never
/// move (ADR-0004). Body byte-for-byte; external frontmatter keys kept
/// verbatim with `type: post`, `pass_state: First Draft` and
/// `origin: <chosen>` set / overwritten (our three keys win); id = Title
/// `origin: <chosen>` set / overwritten (our three keys win) and the
/// Micro.blog bookkeeping dropped (#206 — a foreign file carries no
/// post of this library); id = Title
/// slug at import; collisions `-2`/`-3`… (#60 machinery); a fresh copy,
/// no mtime preservation (#96).
static func importFile(at url: URL, origin: Post.Origin, project: String = Post.defaultProject, home: URL) throws -> Post {
@@ -663,7 +665,7 @@ nonisolated extension PostStore {
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
let stats = DraftStats.compute(body: body)
let stamped = PostFrontmatter.updating(text: text, with: [
("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable
("stats_captured", FixCardStore.formatted(Date(), PostFrontmatter.stampFormat)), // lexically sortable
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
("stats_sentence_variation", String(format: "%.3f", stats.sentenceVariation)),
@@ -675,22 +677,35 @@ nonisolated extension PostStore {
return true
}
// MARK: #33 (S6.1) — the remembered Micro.blog draft URL
// MARK: #33 (S6.1) / #206 — the remembered Micro.blog post
/// Stamp `micropub_url` in place on a successful draft send — the
/// publish step's target (a frontmatter-only change: the body and
/// Stamp micropub keys in place (`micropub_url`, the publish record
/// `micropub_published`) — 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 {
/// readBody-based echo check never fires, and every later editor
/// save re-reads the block (the stamps survive it). A vanished piece
/// throws (write-never-resurrects, `writeNew` is the only creator).
/// `dropping` removes those keys' lines outright (the forget).
static func stampMicropub(_ id: String, home: URL, _ pairs: [(key: String, value: String)], dropping: Set<String> = []) 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 PostFrontmatter.updating(text: raw, with: [("micropub_url", url)])
try PostFrontmatter.updating(text: raw, with: pairs, dropping: dropping)
.write(to: file, atomically: true, encoding: .utf8)
}
/// #206: the piece forgets Micro.blog — both keys' lines removed
/// through the update posture's drop (no empty key left behind; an
/// absent key scans as no memory, and the next send inserts the line
/// fresh). Called when Micro.blog answers 404: the post is gone
/// there, so the piece is no longer on Micro.blog. Throws when the
/// write cannot land — the caller must not then claim the link is
/// gone.
static func forgetMicropub(id: String, home: URL) throws {
try stampMicropub(id, home: home, [], dropping: PostFrontmatter.micropubKeys)
}
}
// MARK: Cursor-state sidecar (#66)
+1
View File
@@ -219,6 +219,7 @@ struct PostsLibraryColumn: View {
model.archivePost(post)
}
Divider()
MicroblogHandOffButton(post: post)
FinderHandOffButtons(model: model, post: post)
Button("Move to Trash", role: .destructive) {
model.trash(post)
+18 -1
View File
@@ -5,7 +5,7 @@
// #193: the shared workspace chrome, moved from WorkspaceView.swift
// (file-length ceiling) — SelectedRowStrip, BorderedSecondaryButtonStyle,
// PaneHeader; every pane reuses them, code unchanged. #205 adds
// FinderHandOffButtons (born here).
// FinderHandOffButtons, #206 MicroblogHandOffButton (both born here).
//
import AppKit
@@ -119,3 +119,20 @@ struct FinderHandOffButtons: View {
}
}
}
/// #206: the row menus' Micro.blog hand-off — Open on Micro.blog, for a
/// piece that is published (a draft's final URL does not exist yet on
/// their side, so a draft shows no entry; neither does a never-sent
/// piece). The URL is the piece's remembered `micropub_url`, already
/// trust-gated at the scan.
struct MicroblogHandOffButton: View {
let post: Post
var body: some View {
if post.micropubPublished != nil, let url = post.micropubURL.flatMap({ URL(string: $0) }) {
Button("Open on Micro.blog") {
NSWorkspace.shared.open(url)
}
}
}
}